Report abuse

<?php

// **************************************************************************************************
// Linklok URL V2.01
// Copyright (c) 2003-2008 Vibralogix
// www.vibralogix.com
// sales@vibralogix.com
// You are licensed to use this product on one domain only.
// Please contact us for extra licenses if required.
// **************************************************************************************************

// General settings
$LinklokKey="";                                 // Set to random string used to encrypt links
$LinklokLocation="";             // Location where files are securely stored
$ManualPassword="";                                  // password used to access manual entry form
$ErrorTemplate="";                                          // Optional error page template (html)

// The following variables must be set if you wish to use the email links feature of Linklok
$YourCompany="";                                // Your company name
$YourEmail="";                            // Your email address
$EmailTemplate="";                                          // Optional html or text format email template
$HTMLEmail="Y";                                             // Set to Y to send the default email in HTML formator N to send in text format
$LinklokLog="";                                             // Optional text log file to store form entry fields
$NotifyEmail="";                                            // Optional email template sent to admin. Leave blank for default template

$LinklokDownloadLog="";                                     // Optional text log to store downloads
$RequireTuring=0;                                           // Set to 1 to use Turing code. Set to 0 to disable
$NotifyDownloadEmail="";                                    // Email address to receive download notificaton email

// Optional list of email addresses / services to block if required. You can add delete from this list
$FreeEmail[]="yahoo.";
$FreeEmail[]="hotmail.";
$FreeEmail[]="gmail.";
$FreeEmail[]="altavista.";
$FreeEmail[]="prontomail.";
$FreeEmail[]="talk21.";
$FreeEmail[]="address.";
$FreeEmail[]="@mail.";
$FreeEmail[]="@australia.";
$FreeEmail[]="boardermail.";
$FreeEmail[]="@canada.";
$FreeEmail[]="bolt.";
$FreeEmail[]="dbzmail.";
$FreeEmail[]="etoast.";
$FreeEmail[]="fastmail.";
$FreeEmail[]="freemail.";
$FreeEmail[]="icqmail.";
$FreeEmail[]="jaydemail.";
$FreeEmail[]="keromail.";
$FreeEmail[]="linuxmail.";
$FreeEmail[]="lycos.";
$FreeEmail[]="myrealbox.";
$FreeEmail[]="netscape.";
$FreeEmail[]="popmail.";
$FreeEmail[]="themail.";
$FreeEmail[]="toast.";
$FreeEmail[]="webcity.";

// Supported mime types. These are only required for displaying these file types inline.
// Linklok can download any file type using the Save As dialog box in the browser.
// You can add to this list as required.

$mt['.jpg']="image/jpeg";
$mt['.gif']="image/gif";
$mt['.cgm']="image/cgm";
$mt['.gif']="image/gif";
$mt['.htm']="text/html";
$mt['.html']="text/html";
$mt['.txt']="text/plain";
$mt['.pdf']="application/pdf";
$mt['.mpg']="video/mpeg";
$mt['.mpeg']="video/mpeg";
$mt['.rm']="audio/x-pn-realaudio";
$mt['.wmv']="application/x-ms-wmv";
$mt['.swf']="application/x-shockwave-flash";
$mt['.mov']="video/quicktime";
$mt['.asf']="video/x-ms-asf";
$mt['.asx']="video/x-ms-asf";
$mt['.rm']="audio/x-realaudio";
$mt['.ram']="audio/x-pn-realaudio";
$mt['.zip']="application/zip";

// Code beloe this point should not need modifying
///////////////////////////////////////////////////////////////////////////////////////////////////////

@error_reporting (E_ALL ^ E_NOTICE);
if ($YourEmail!="")
{
  if (!isset($EmailHeaderNoSlashR))
    $EmailHeaderNoSlashR=1;
  if ((!isset($ExtraMailParam)) && (strtolower(@ini_get("safe_mode")) != 'on') && (@ini_get("safe_mode") != '1'))
    $ExtraMailParam="-f ".$YourEmail;
  @ini_set(sendmail_from,$YourEmail);
}
if (!empty($_GET)) while(list($name, $value) = each($_GET)) $$name = $value;
if (!empty($_POST)) while(list($name, $value) = each($_POST)) $$name = $value;
$found = false;
if (!empty($_REQUEST))
{
  reset($_REQUEST);
  while (list($namepair, $valuepair) = each($_REQUEST))
  {
    if ($namepair == "LinklokKey") $found = true;
    if ($namepair == "ManualPassword") $found = true;
    if ($namepair == "EmailTemplate") $found = true;
    if ($namepair == "LinklokLog") $found = true;
    if ($namepair == "LinklokDownloadLog") $found = true;
    if ($namepair == "YourEmail") $found = true;
    if ($namepair == "YourCompany") $found = true;
    if ($namepair == "RequireTuring") $found = true;
    if ($namepair == "AllowEmailOnce") $found = true;
    if ($namepair == "AllowIPOnce") $found = true;
    if (substr($namepair, 0, 15) == "LinklokLocation") $found = true;
    if (substr($namepair, 0, 9) == "FreeEmail") $found = true;
  }
}
if ($found)
{
  linklokShowMessage($ErrorTemplate, "Access Denied.", $ErrorEmail);
  exit;
}
if (isset($_REQUEST['linklokauth']))
  $linklokauth=$_REQUEST['linklokauth'];
if (isset($_REQUEST['linklokauthe']))
  $linklokauthe=$_REQUEST['linklokauthe'];  
if (isset($_REQUEST['linklokform']))
  $linklokform=$_REQUEST['linklokform'];
$ipaddr=$_SERVER['REMOTE_ADDR'];
$thispage=$_SERVER['PHP_SELF'];
$thisurl="http://".$_SERVER['HTTP_HOST'].$thispage;
// If ?orderform them request password
if ((isset($manualentry)) || (isset($MANUALENTRY)))
{
  print "<html><head><title>Linklok URL Manual Entry Form</title></head><body>\n";
  print "<script language=\"JavaScript\">\n";
  print "<!-- JavaScript\n";
  print "function validateform(form)\n";
  print "{\n";
  print "  if (form.linklokpassword.value==\"\")\n";
  print "  {\n";
  print "    alert(\"Please enter the password\")\n";
  print "    form.linklokpassword.focus()\n";
  print "    return false\n";
  print "  }\n";
  print "  return true;\n";
  print "}\n";
  print "// - JavaScript - -->\n";
  print "</script>\n";
  print "<form name=\"form1\" method=\"post\" action=\"$thisurl\" onSubmit=\"return validateform(this)\">\n";
  print "<p align=\"left\"><font face=\"Arial\" color=\"#333399\"><span style=\"font-size:16pt;\"><b>Linklok Manual Entry Form</b></span></font></p>\n";
  print "<table border=\"0\" cellpadding=\"0\" cellspacing=\"10\" bgcolor=\"#FFFFCC\">\n";
  print "<tr><td><p><font face=\"Arial\" size=\"2\">Password</font></p></td>\n";
  print "<td><p><input type=\"password\" name=\"linklokpassword\" maxlength=\"50\" size=\"30\"></p></td></tr><tr><td><p>&nbsp;</p></td>\n";
  print "<td align=\"right\"><p><input type=\"submit\" name=\"button1\" value=\"Login\"></p></td>\n";
  print "</tr></table></form><script language=\"JavaScript\">document.forms[0].linklokpassword.focus()</script></body></html>\n";
  exit;
}
if (($ManualPassword!="") && (isset($linklokpassword)) && ($ManualPassword!=$linklokpassword))
{
  linklokShowMessage($ErrorTemplate,"Incorrect password.");
  exit;
}
if (isset($linklokauthe))
{ 
  if ($DownloadBackground!="")
  {
    if (($fh = @fopen($DownloadBackground, "r")))
    {  
      $page = fread ($fh, 200000);
      fclose($fh);
      $page = eregi_replace("!!!link!!!", $LinklokURL."?linklokauth=".$linklokauthe, $page);
      $page = eregi_replace("<body", "<body onLoad=\"download()\"", $page);      
      $redirectcode ="<script language=\"JavaScript\" type=\"text/javascript\">\n";
      $redirectcode.="function download()\n";
      $redirectcode.="{\n";
      $redirectcode.="  window.location=\"".$LinklokURL."?linklokauth=".$linklokauthe."\"\n";
      $redirectcode.="}\n";
      $redirectcode.="</script>\n";
      $redirectcode.="</body>\n";  
      $page = eregi_replace("</body>", $redirectcode, $page);
      print $page;
      exit;      
    }
    else
      $linklokauth=$linklokauthe;
  }
  else
    $linklokauth=$linklokauthe;
}
if ($linklokauth!="")
{
  // Request to access file
  linklokgetfile($linklokauth);
}
if ($linklokform!="")
{
  // Request to send email with links
  linklokemaillinks($FreeEmail);
}
// If password entered and correct then display manual order form
if (($ManualPassword!="") && ($ManualPassword==$linklokpassword))
{
  print "<html><head><title>Linklok URL Manual Entry Form</title></head><body>\n";
  print "<script language=\"JavaScript\">\n";
  print "<!-- JavaScript\n";
  print "function validateform(form)\n";
  print "{\n";
  print "  if (form.f0.value==\"\")\n";
  print "  {\n";
  print "    alert(\"Please enter at least one file\")\n";
  print "    form.f0.focus()\n";
  print "    return false\n";
  print "  }\n";
  print "  if (form.newexpiry2.value!=\"\")\n";
  print "  {\n";
  print "    if (ValidChars(form.newexpiry2.value,\"0123456789\")==false)\n";
  print "    {\n";
  print "      alert(\"Please enter a valid expiry time or select from the menu\")\n";
  print "      form.newexpiry2.focus()\n";
  print "      return(false)\n";
  print "    }\n";
  print "    form.x.value=form.newexpiry2.value\n";  
  print "  }\n";
  print "  else\n";
  print "  {\n";
  print "    form.x.value=form.newexpiry1.value\n";
  print "  }\n";

  print "  if (form.email.value!=\"\")\n";
  print "  {\n";
  print "    if (ValidateEmail(form.email.value)==false)\n";
  print "    {\n";
  print "      alert(\"Please enter a valid email address\")\n";
  print "      form.email.focus()\n";
  print "      return false\n";
  print "    }\n";
  print "  }\n";
  print "  if (ValidateIP(form.i.value)==false)\n";
  print "  {\n";
  print "    alert(\"Please enter a valid IP address or leave blank\")\n";
  print "    form.i.focus()\n";
  print "    return false\n";
  print "  }\n";
  print "  if (form.i.value==\"\")\n";
  print "    form.i.value=\"0.0.0.0\";\n";
  print "  if (form.email.value==\"\")\n";
  print "    form.linklokform.value=\"\";\n";
  print "  return true\n";
  print "}\n";
  print "\n";
  print "function ValidateEmail(str)\n";
  print "{\n";
  print "    // are regular expressions supported?\n";
  print "    var supported = 0;\n";
  print "    if (window.RegExp) {\n";
  print "      var tempStr = \"a\";\n";
  print "      var tempReg = new RegExp(tempStr);\n";
  print "      if (tempReg.test(tempStr)) supported = 1;\n";
  print "    }\n";
  print "    if (!supported)\n";
  print "      return (str.indexOf(\".\") > 2) && (str.indexOf(\"@\") > 0);\n";
  print "    var r1 = new RegExp(\"(@.*@)|(\\\.\\\.)|(@\\\.)|(^\\\.)\");\n";
  print "    var r2 = new RegExp(\"^.+\\\@(\\\[?)[a-zA-Z0-9\\\-\\\.]+\\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\\]?)$\");\n";
  print "    return (!r1.test(str) && r2.test(str));\n";
  print "}\n";
  print "function ValidateIP(ip)\n";
  print "{\n";
  print "  if (ip!=\"\")\n";
  print "  {\n";
  print "    var ni\n";
  print "    if (ValidChars(ip,\"0123456789.\")==false)\n";
  print "      return(false)\n";
  print "    var ipparts=ip.split(\".\")\n";
  print "    if (ipparts.length!=4)\n";
  print "      return(false)\n";
  print "    for (var k=0; k<4; k++)\n";
  print "    {\n";
  print "      if (ipparts[k].length<1)\n";
  print "      return(false)\n";
  print "      if ((ipparts[k].charAt(0)==\"0\") && (ipparts[k].length>1))\n";
  print "      return(false)\n";
  print "    ni=parseInt(ipparts[k],10)\n";
  print "    if ((ni<0) || (ni>255))\n";
  print "      return (false)\n";
  print "    }\n";
  print "  }\n";
  print "    return(true)\n";
  print "}\n";
  print "\n";
  print "function ValidChars(str,valid)\n";
  print "{\n";
  print "  var v=true\n";
  print "  for (i=0;i<str.length;i++)\n";
  print "  {\n";
  print "    if (valid.indexOf(str.charAt(i))==-1)\n";
  print "    {\n";
  print "      v=false\n";
  print "      break\n";
  print "    }\n";
  print "  }\n";
  print "  return(v)\n";
  print "}\n";
  print "// - JavaScript - -->\n";
  print "</script>\n";
  print "<form name=\"form1\" method=\"post\" action=\"$thisurl\" onSubmit=\"return validateform(this)\">\n";
  print "<input type=\"hidden\" name=\"linklokpassword\" value=\"$linklokpassword\">\n";
  print "<input name=\"m\" type=\"hidden\" value=\"0\">\n";
  print "<input name=\"a\" type=\"hidden\" value=\"$linklokpassword\">\n";
  print "<input name=\"g\" type=\"hidden\" value=\"\">\n";
  print "<input name=\"linklokform\" type=\"hidden\" value=\"1\">\n";
  print "<p align=\"left\"><font face=\"Arial\" color=\"#333399\"><span style=\"font-size:16pt;\"><b>Linklok Manual Entry Form</b></span></font></p>\n";
  print "<table border=\"0\" cellpadding=\"0\" cellspacing=\"10\" bgcolor=\"#FFFFCC\">\n";
  for ($k=0;$k<=19;$k++)
  {
    print "<tr>\n";
    print "<td><p><font face=\"Arial\" size=\"2\">File ".($k+1)."</font></p></td>\n";
    $fnum="f".$k;
    $loc="l".$k;
    print "<td><p>";
    if ($$fnum!="")
    {
      print "<input name=\"f$k\" type=\"text\" value=\"".$$fnum."\">";
      if (!empty($LinklokLocations))
      {
        print "<font face=\"Arial\" size=\"2\">&nbsp;in location&nbsp;</font><select name=\"l$k\" size=\"1\">\n";
        if (($LinklokLocation!="") && ($$loc==""))
          print "<option selected value=\"\">Default</option>\n";
        if (($LinklokLocation!="") && ($$loc!=""))
          print "<option selected value=\"\">Default</option>\n";
        reset($LinklokLocations);
        while(list($namepair, $valuepair) = each($LinklokLocations))
        {
          $$namepair = $valuepair;
          if ($$loc==$namepair)
            print "<option selected value=\"".$namepair."\">".$namepair."</option>\n";
          else
            print "<option value=\"".$namepair."\">".$namepair."</option>\n";
        }
        print "</select>\n";
      }
      if ($email=="")
      {
        if ($x != 0)
        {
          if (strlen($x) == 12)
            $expirytime = mktime(substr($x, 8, 2), substr($x, 10, 2), 0, substr($x, 4, 2), substr($x, 6, 2), substr($x, 0, 4), -1);
          else
            $expirytime = time() + ($x * 60);
        }
        else
          $expirytime = 0;
        $plink=linkokGetSecureLink($$fnum, $$loc,$expirytime, "LL_1", $i, $l, $LinklokKey, "1", $thisurl);
        $fnameonly=linklokfilename($$fnum);
        print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"$plink\" target=\"_linklok\">$fnameonly</a>";
      }
    }
    else
    {
      print "<input name=\"f$k\" type=\"text\" value=\"\">";
      if (!empty($LinklokLocations))
      {
        print "<font face=\"Arial\" size=\"2\">&nbsp;in location&nbsp;</font><select name=\"l$k\" size=\"1\">\n";
        if (($LinklokLocation!="") && ($$loc==""))
          print "<option selected value=\"\">Default</option>\n";
        if (($LinklokLocation!="") && ($$loc!=""))
          print "<option selected value=\"\">Default</option>\n";
        reset($LinklokLocations);
        while(list($namepair, $valuepair) = each($LinklokLocations))
        {
          $$namepair = $valuepair;
          if ($$loc==$namepair)
            print "<option selected value=\"".$namepair."\">".$namepair."</option>\n";
          else
            print "<option value=\"".$namepair."\">".$namepair."</option>\n";
        }
        print "</select>\n";
      }
    }
    print"</p></td>\n";
    print "</tr>\n";
  }
  print "<tr><td><p><font face=\"Arial\" size=\"2\">Expiry Time</font></p></td>\n";
  print "<input type=\"hidden\" name=\"x\" value=\"\">\n";
  print "<td><p><select name=\"newexpiry1\" size=\"1\">\n";
  if ($newexpiry1=="10")
    print "<option selected value=\"10\">10 minutes</option>\n";
  else
    print "<option value=\"10\">10 minutes</option>\n";
  if ($newexpiry1=="60")
    print "<option selected value=\"60\">1 Hour</option>\n";
  else
    print "<option value=\"60\">1 Hour</option>\n";
  if ($newexpiry1=="180")
    print "<option selected value=\"180\">3 Hours</option>\n";
  else
    print "<option value=\"180\">3 Hours</option>\n";
  if (($newexpiry1=="1440") || (!isset($x)))
    print "<option selected value=\"1440\">24 Hours</option>\n";
  else
    print "<option value=\"1440\">24 Hours</option>\n";
  if ($newexpiry1=="43200")
    print "<option selected value=\"43200\">30 Days</option>\n";
  else
    print "<option value=\"43200\">30 Days</option>\n";
  if ($newexpiry1=="525600")
    print "<option selected value=\"525600\">1 Year</option>\n";
  else
    print "<option value=\"525600\">1 Year</option>\n";
  if ($newexpiry1=="0")
    print "<option selected value=\"0\">No Expiry</option>\n";
  else
    print "<option value=\"0\">No Expiry</option>\n";
  print "</select>\n";
  print "<font face=\"Arial\" size=\"2\">&nbsp;or&nbsp;</font><input type=\"text\" name=\"newexpiry2\" value=\"$newexpiry2\" maxlength=\"12\" size=\"15\">\n";
  print "</p></td></tr>\n";
  print "<tr><td><p><font face=\"Arial\" size=\"2\">IP address</font></p></td><td><p>\n";
  print "<font face=\"Arial\"><span style=\"font-size:10pt;\"><input type=\"text\" name=\"i\" maxlength=\"15\" size=\"30\">\n";
  print "<select name=\"l\" size=\"1\">\n";
  print "  <option selected value=\"0\">Level 0 (off)</option>\n";
  print "  <option value=\"1\">Level 1</option>\n";
  print "  <option value=\"2\">Level 2</option>\n";
  print "  <option value=\"3\">Level 3</option>\n";
  print "  <option value=\"4\">Level 4</option>\n";
  print "</select>\n";
  print "</span></font></p></td></tr>\n";
  print "<tr><td><p><font face=\"Arial\" size=\"2\">Email address</font></p></td><td><p>\n";
  print "<font face=\"Arial\"><span style=\"font-size:10pt;\"><input type=\"text\" name=\"email\" size=\"30\">&nbsp; Leave blank to display links only</span></font></p></td></tr>\n";
  if ($Emails!="")
  {
    print "<tr><td><p><font face=\"Arial\" size=\"2\">Email Template</font></p></td>\n";
    print "<td><p><select name=\"t\" size=\"1\">\n";
    if ($EmailTemplate!="")
    {
      if ($t=="")
        print "<option selected value=\"\">".linklokfilename($EmailTemplate)."</option>\n";
      else
        print "<option value=\"\">".linklokfilename($EmailTemplate)."</option>\n";
    }
    $hDirectory=opendir("$Emails");
    if ($hDirectory!=false)
    {
      while($entryname=readdir($hDirectory))
      {
        if (($entryname!=".") && ($entryname!="..") && ($entryname!=""))
          print "<option value=\"$entryname\">$entryname</option>";
      }
      closedir($hDirectory);
    }
    print "</select></p></td></tr>\n";
  }
  print "<tr><td><p><font face=\"Arial\"><span style=\"font-size:10pt;\">\n";  
  print "&nbsp;</span></font></p></td>\n";
  print "<td><p align=\"right\"><font face=\"Arial\"><span style=\"font-size:10pt;\">\n";
  if ($email!="")
    print "Download links sent to $email&nbsp;&nbsp;";
  print "<input type=\"submit\" name=\"submit\" value=\"Submit\">\n";
  print "</span></font></p></td></tr></table></form>\n";
  print "<script language=\"JavaScript\">document.forms[0].f0.focus()</script>\n";
  print "</body></html>\n";
  exit;
}

function linklokurl($fname,$expiry,$dialog,$iplevel=0)
{
  global $LinklokKey,$thispage,$ipaddr;
  if ($expiry != 0)
  {
    if (strlen($expiry) == 12)
      $expirytime = mktime(substr($expiry, 8, 2), substr($expiry, 10, 2), 0, substr($expiry, 4, 2), substr($expiry, 6, 2), substr($expiry, 0, 4), -1);
    else
      $expirytime = time() + ($expiry * 60);
  }
  else
    $expirytime = 0;
  $locs=explode(":",$fname);
  $plink=linkokGetSecureLink($locs[0], $locs[1], $expirytime, "LL_0", $ipaddr, $iplevel, $LinklokKey, $dialog, $thispage);
  print($plink);
}

function linklokurl_api($fname,$expiry,$dialog,$ip="",$iplevel=0)
{
  global $LinklokKey,$thispage,$NoExtraPath,$ipaddr;
  if ($ip=="")
    $ip=$ipaddr;
  if ($expiry != 0)
  {
    if (strlen($expiry) == 12)
      $expirytime = mktime(substr($expiry, 8, 2), substr($expiry, 10, 2), 0, substr($expiry, 4, 2), substr($expiry, 6, 2), substr($expiry, 0, 4), -1);
    else
      $expirytime = time() + ($expiry * 60);
  }
  else
    $expirytime = 0;
  $locs=explode(":",$fname);
  $plink=linkokGetSecureLink($locs[0], $locs[1], $expirytime, "LL_0", $ip, $iplevel, $LinklokKey, $dialog, $thispage);
  return($plink);
}

function linklokemail($files,$expiry,$filter,$goto,$iplevel=0,$temp="")
{
  global $LinklokKey,$ipaddr;
  $created=(string)time();
  $fnames=explode(",",$files);
  $tohash=$LinklokKey;
  for ($k=0;$k<count($fnames);$k++)
  {
   $locs=explode(":",$fnames[$k]);
   print("<input name=\"f$k\" type=\"hidden\" value=\"$locs[0]\">\n");
   print("<input name=\"l$k\" type=\"hidden\" value=\"$locs[1]\">\n");
   $tohash.=$locs[0].$locs[1];
  }
  print("<input name=\"x\" type=\"hidden\" value=\"$expiry\">\n");
  $tohash.=$expiry;
  print("<input name=\"m\" type=\"hidden\" value=\"$filter\">\n");
  $tohash.=$filter;
  print("<input name=\"l\" type=\"hidden\" value=\"$iplevel\">\n");
  $tohash.=$iplevel;
  print("<input name=\"t\" type=\"hidden\" value=\"$temp\">\n");
  $tohash.=$temp;
  print("<input name=\"c\" type=\"hidden\" value=\"$created\">\n");
  $tohash.=$created;
  $hash=md5($tohash);
  print("<input name=\"g\" type=\"hidden\" value=\"$goto\">\n");
  print("<input name=\"a\" type=\"hidden\" value=\"$hash\">\n");
  print("<input name=\"linklokform\" type=\"hidden\" value=\"1\">\n");
}

function linklokemail_api($email,$files,$expiry,$ip="",$iplevel=0,$template="")
{
  global $LinklokKey,$ipaddr,$Emails,$EmailTemplate;
  $fnames=explode(",",$files);
  for ($k=0;$k<count($fnames);$k++)
  {
   $loc=explode(":",$fnames[$k]);
   $fnames[$k]=$loc[0];
   $floc[$k]=$loc[1];
  }
  if ($ip=="")
    $ip=$ipaddr;
  if ($template!="")
    $template=$Emails.$template;
  if (($template=="") && ($EmailTemplate!=""))
    $template=$EmailTemplate;
  if ($template=="")
  {
    $res=linklokSendEmail($email, $email, $expiry, $ip, $iplevel, $fnames, $floc);
    return($res);
  }
  else
  {
    $res=linkloklinklokSendEmailUsingTemplate($email, $template, $email, $expiry, $ip, $iplevel, $fnames, $floc);
    return($res);
  }
}

function linkokGetSecureLink($fname, $loc, $expirytime, $id, $ip, $ipl, $lkey, $dlog, $lurl)
{
  global $NoFilename, $DownloadURL;
  $auth=md5($lkey.$fname.$expirytime.$ip.$ipl.$id.$loc);
  $plink=$fname.",".$expirytime.",".$ip.",".$ipl.",".$dlog.",".$id.",".$loc.",".$auth;
  $plink=base64_encode($plink);
  $plink=rawurlencode($plink);
  if ($DownloadURL!="")
    $lurl=$DownloadURL;
  if ($NoFilename == 1)
    $plink = "$lurl?linklokauth=".$plink;
  else
  {
    // Get filename only
    $fnameonly=linklokfilename($fname);
    // See if alternative save filename required
    $pos=strpos($fnameonly,"^");
    if (is_integer($pos))
      $fnameonly=substr($fnameonly,$pos+1);
    $plink = "$lurl?linklokauth=".$plink."/".$fnameonly;
  }
  return($plink);
}

function linklokgetfile($linklokauth)
{
  global $LinklokKey, $LinklokLocation,$ErrorTemplate,$ipaddr,$LinklokLocations,$NotifyDownloadEmail,$LinklokDownloadLog;
  // Remove any /filename from end
  $pos = strpos($linklokauth, "/");
  if (is_integer($pos))
    $linklokauth = substr($linklokauth, 0, $pos);
  // Split linklokauth into its parts
  $linklokauth=rawurldecode($linklokauth);
  $oldlink=false;
  if (is_integer(strpos($linklokauth,",")))
    $oldlink=true;
  if ($oldlink==false)
  {
    $linklokauth=base64_decode($linklokauth);
  }
  $ip="";
  $iplevel="";
  $id="";
  $loc="";
  $fields=explode(",",$linklokauth);
  $fname=$fields[0];
  $expirytime=$fields[1];
  if (count($fields)==4)
  {
    $dialog=$fields[2];
    $auth=$fields[3];
  }
  if (count($fields)==6)
  {
    $ip=$fields[2];
    $iplevel=$fields[3];
    $dialog=$fields[4];
    $auth=$fields[5];
  }
  if (count($fields)==8)
  {
    $ip=$fields[2];
    $iplevel=$fields[3];
    $dialog=$fields[4];
    $id=$fields[5];
    $loc=$fields[6];
    $auth=$fields[7];
  }
  // Verify hash value to ensure nothing tampered wth
  if (md5($LinklokKey.$fname.$expirytime.$ip.$iplevel.$id.$loc)!=$auth)
  {
     linklokShowMessage($ErrorTemplate,"Linklok URL authentication failed");
     exit;
  }
  // Check link hasn't expired
  if ($expirytime!=0)
  {
    $curtime=time();
    if ($curtime>$expirytime)
    {
      linklokShowMessage($ErrorTemplate,"Sorry but this Linklok link has expired.\n");
      exit;
    }
  }
  if (($iplevel!=0) && ($ip!="0.0.0.0"))
  {
    $ipo[1]=strtok($ip,".");
    $ipo[2]=strtok(".");
    $ipo[3]=strtok(".");
    $ipo[4]=strtok(".");
    $ipn[1]=strtok($ipaddr,".");
    $ipn[2]=strtok(".");
    $ipn[3]=strtok(".");
    $ipn[4]=strtok(".");
    for ($k=1;$k<=$iplevel;$k++)
    {
      if ($ipo[$k]!=$ipn[$k])
      {
        linklokShowMessage($ErrorTemplate,"Linklok link IP address is not valid.\n");
        exit;
      }
    }
  }
  // Make full path or url to file
  // If $loc blank then use default location
  if ($loc=="")
    $link=$LinklokLocation.$fname;
  else
    $link=$LinklokLocations[$loc].$fname;
  $ext=linklokfileextension($link);
  $fname=linklokfilename($link);
  $actualfname=$fname;
  // See if alternative save filename required
  $pos=strpos($fname,"^");
  if (is_integer($pos))
  {
    $fname=substr($fname,$pos+1);
    $link=str_replace("^".$fname,"",$link);
    $actualfname=linklokfilename($link);
  }
  // If download link is php page then just include it.
  if ($ext==".php")
  {
    if ($NotifyDownloadEmail != "")
      linklokEmailDownloadNotify($actualfname, $id, $_SERVER['REMOTE_ADDR'],$expirytime);    
    if ($LinklokDownloadLog!="")
      linkloklogdownload($LinklokDownloadLog,$actualfname,$id);    
    include $link;
    exit;
  }
  // If download link is html page then just display it.
  if (($ext==".html") || ($ext==".htm"))
  {
    if (!($fh=@fopen($link,"rb")))
    {
      linklokShowMessage($ErrorTemplate,"Could not open file.");
      exit;
    }
    if ($NotifyDownloadEmail != "")
      linklokEmailDownloadNotify($actualfname, $id, $_SERVER['REMOTE_ADDR'],$expirytime);     
    if ($LinklokDownloadLog!="")
      linkloklogdownload($LinklokDownloadLog,$actualfname,$id);        
    header("Content-type: text/html\n");
    header("Content-transfer-encoding: binary\n");
    @linklokxfpassthru($fh);
    exit;
  }
  // See if link is local path or URL
  $pos=strpos(strtolower($link),"http://");
  if (!is_integer($pos))
  {
    // If link is a local path then get local path and handle resume & download managers
    $fsize=@filesize($link);
    /* is resume requested? */
    $headers = linklokxgetallheaders();
    if(isset($headers["Range"]))
    {
      header("HTTP/1.1 206 Partial content");
      $val=split("=",$headers["Range"]);
      if(ereg("^-",$val[1]))
      {
        $slen = ereg_replace("-","",$val[1]);
        $sfrom = $fsize - $slen;
        header("Content-Length: ".$slen);
      }
      else if(ereg("-$",$val[1]))
      {
        $sfrom = ereg_replace("-","",$val[1]);
        $slen = $fsize - $sfrom;
        header("Content-Length: ".(string)((int)$fsize-(int)$sfrom));
      }
      else if(is_integer(strpos($val[1],"-")))
      {
        $ranges=split("-",$val[1]);
        $sfrom = $ranges[0];
        $slen = $ranges[1]-$ranges[0];
        header("Content-Length: ".(string)((int)$fsize-(int)$sfrom));
      }
      $br = $sfrom."-".(string)($fsize-1)."/".$fsize;
      header("Content-Range: bytes $br");
      $mimetype=linklokgetmimetype($link);
      if ($mimetype!="")
        header("Content-type: $mimetype\n");      
      else
        header("Content-type: application/octet-stream\n");          
      header("Connection: close");
      if (!($fh=@fopen($link,"rb")))
      {
        linklokShowMessage($ErrorTemplate,"Linklok could not open the file.");
        exit;
      }
      if ($NotifyDownloadEmail != "")
      {
        if ($sfrom == 0)
          linklokEmailDownloadNotify($actualfname, $id, $_SERVER['REMOTE_ADDR'],$expirytime);
      }       
      if ($LinklokDownloadLog!="")
      {
        if ($sfrom == 0)        
          linkloklogdownload($LinklokDownloadLog,$actualfname,$id);        
      }        
      fseek($fh, $sfrom);
      @linklokxfpassthru($fh);
    }
    else
    {
      $size=@filesize($link);
      if (!($fh=@fopen($link,"rb")))
      {
        linklokShowMessage($ErrorTemplate,"Linklok could not open the file.");
        exit;
      }
      $mimetype=linklokgetmimetype($link);
      if ($dialog==1)
        header("Content-disposition: attachment; filename=".$fname."\n");
      if ($mimetype!="")
        header("Content-type: $mimetype\n");      
      else
        header("Content-type: application/octet-stream\n");          
      header("Content-transfer-encoding: binary\n");
      header("Content-Length: ".$size."\n");
      if ($NotifyDownloadEmail != "")
        linklokEmailDownloadNotify($actualfname, $id, $_SERVER['REMOTE_ADDR'],$expirytime);         
      if ($LinklokDownloadLog!="")
        linkloklogdownload($LinklokDownloadLog,$actualfname,$id);              
      @linklokxfpassthru($fh);
    }
  }
  else
  {
    // link is a URL rather than local path so do simple download
    $link=str_replace(" ","%20",$link);
    $size=filesize_remote($link);    
    if (!($fh=@fopen($link,"rb")))
    {
      linklokShowMessage($ErrorTemplate,"Linklok could not open the file.");
      exit;
    }
    if ($NotifyDownloadEmail != "")
      linklokEmailDownloadNotify($actualfname, $id, $_SERVER['REMOTE_ADDR'],$expirytime);         
    if ($LinklokDownloadLog!="")
      linkloklogdownload($LinklokDownloadLog,$actualfname,$id);            
    $mimetype=linklokgetmimetype($link);
    if ($dialog==1)
      header("Content-disposition: attachment; filename=".$fname."\n");
    if ($mimetype!="")
      header("Content-type: $mimetype\n");      
    else
      header("Content-type: application/octet-stream\n");          
    header("Content-transfer-encoding: binary\n");
    if ((int)$size>0)
      header("Content-Length: ".$size."\n");
    @linklokxfpassthru($fh);
  }
  exit;
}

function linklokemaillinks($freem)
{
global $LinklokKey,$EmailTemplate,$YourCompany,$YourEmail,$LinklokLog,$NoExtraPath,$ManualPassword;
global $LinklokLocation,$LinklokLocations,$ErrorTemplate,$ipaddr,$Emails;
global $NotifyEmail,$NotifyTemplate,$FormExpire;
global $AllowEmailOnce, $AllowIPOnce, $RequireTuring, $turing, $manualentryused;   
$tohash=$LinklokKey;
for ($k=0;$k<100;$k++)
{
  $fvar="f".$k;
  $lvar="l".$k;
  if ((isset($_REQUEST[$fvar])) && ($_REQUEST[$fvar]!=""))
  {
    $fname[]=$_REQUEST[$fvar];
    $tohash.=$fname[$k];
    $floc[]=$_REQUEST[$lvar];
    $tohash.=$floc[$k];
  }
}
if (isset($_REQUEST['x']))
{
  $expiry=$_REQUEST['x'];
  $tohash.=$expiry;
}
if (isset($_REQUEST['m']))
{
  $filter=$_REQUEST['m'];
  $tohash.=$filter;
}
if (isset($_REQUEST['l']))
{
  $iplevel=$_REQUEST['l'];
  $tohash.=$iplevel;
}
if (isset($_REQUEST['t']))
{
  $template=$_REQUEST['t'];
  $tohash.=$template;
}
if (isset($_REQUEST['c']))
{
  $created=$_REQUEST['c'];
  $tohash.=$created;
}
if (isset($_REQUEST['email']))
  $clientemail=$_REQUEST['email'];
if (isset($_REQUEST['turing']))
  $turing=$_REQUEST['turing'];
$goto="";
if (isset($_REQUEST['g']))
  $goto=$_REQUEST['g'];
if (isset($_REQUEST['a']))
  $auth=$_REQUEST['a'];
// See if called from the manual entry form
$manualentryused=false;
if (($auth==$ManualPassword) && ($ManualPassword!=""))
{
$manualentryused=true;
}



// Check email address entered is valid
if (!linklokvalidemail($clientemail))
{
    linklokShowMessage($ErrorTemplate,"Please enter a valid email address.<BR><BR>Click your browsers BACK button and try again.");
    exit;  
}
// if filter set to 1 then block free email services listed above
if ($filter=="1")
{
  for ($k=0; $k<count($freem);$k++)
  {
    $pos=strpos(strtolower($clientemail),strtolower($freem[$k]));
    if (is_integer($pos))
    {
      linklokShowMessage($ErrorTemplate,"Linklok does not accept free email addresses.<BR><BR>Click your browsers BACK button and try again.");
      exit;
    }
  }
}
// If required check turing code (unless called from the manual entry form
if (($RequireTuring==1) && ($manualentryused==false))
{
  session_start();
  $turingmatch=false;
  if ((strtolower($_SESSION['ses_llurlturingcode'])==strtolower(trim($turing))) && ($_SESSION['ses_llurlturingcode']!=""))
  {
    $turingmatch=true;
    $_SESSION['ses_llurlturingcode']="";
  }
  else if ((strtolower($_SESSION['ses_llurlpreviousturingcode'])==strtolower(trim($turing))) && ($_SESSION['ses_llurlpreviousturingcode']!=""))
  {
    $turingmatch=true;
    $_SESSION['ses_llurlpreviousturingcode']="";
  }
  if (!$turingmatch)
  {
    linklokShowMessage($ErrorTemplate,"The turing (CAPTCHA)code entered was not correct.<BR><BR>Click your browsers BACK button and try again.");
    exit;      
  }  
}
// if required block if email address is already listed in log file within the days specified
if  (($LinklokLog!="") && ((isset($AllowEmailOnce)) || (isset($AllowIPOnce))))
{
  $limitemailtimestamp=mktime()-($AllowEmailOnce*60);
  $limitiptimestamp=mktime()-($AllowIPOnce*60);
  $testemail=strtolower($clientemail);
  $fh=@fopen($LinklokLog,"r");
  if ($fh)
  {
    while (!feof($fh))
    {
      $lne = fgets($fh, 2048);
      $lne = strtolower($lne);
      if (is_integer(strpos($lne,$testemail)))
      {
        $lnearray=explode(",",$lne);
        $entrytimestamp=mktime(substr($lnearray[3],0,2),substr($lnearray[3],3,2),substr($lnearray[3],6,2),substr($lnearray[1],3,2),substr($lnearray[1],0,2),substr($lnearray[1],6,2));
        if ((isset($AllowEmailOnce)) && ($entrytimestamp<=$limitemailtimestamp))
        {
          linklokShowMessage($ErrorTemplate,"This email address has already been used.");
          exit;          
        }
      }
      if (is_integer(strpos($lne,$ipaddr)))
      {
        $lnearray=explode(",",$lne);
        $entrytimestamp=mktime(substr($lnearray[3],0,2),substr($lnearray[3],3,2),substr($lnearray[3],6,2),substr($lnearray[1],3,2),substr($lnearray[1],0,2),substr($lnearray[1],6,2));
        if ((isset($AllowIPOnce)) && ($entrytimestamp<=$limitiptimestamp))
        {
          linklokShowMessage($ErrorTemplate,"This IP address has already been used.");
          exit;          
        }
      }
    }
    fclose($fh);    
  }
}
$hash=md5($tohash);
// If manual order password then override hash check
if ($manualentryused)
{
  $hash=$auth;
  if (isset($_REQUEST['i']))
    $ipaddr=$_REQUEST['i'];
}
if ($hash!=$auth)
{
  linklokShowMessage($ErrorTemplate,"Linklok form authentication failed");
  exit;
}
if ($FormExpire>0)
{
  if (time()>($created+60*$FormExpire))
  {
    linklokShowMessage($ErrorTemplate,"Linklok form has expired");
    exit;
  }
}
// Now send email with download links to client
if ($template!="")
  $template=$Emails.$template;
if (($template=="") && ($EmailTemplate!=""))
  $template=$EmailTemplate;
if ($template=="")
{
  $res=linklokSendEmail($clientemail, $clientemail, $expiry, $ipaddr, $iplevel, $fname, $floc);
  if ($res!=true)
  {
    linklokShowMessage($ErrorTemplate,"Email could not be sent");
    exit;
  }
}
else
{
  $res=linkloklinklokSendEmailUsingTemplate($clientemail, $template, $clientemail, $expiry, $ipaddr, $iplevel, $fname, $floc);
  if ($res!=true)
  {
    linklokShowMessage($ErrorTemplate,"Email could not be sent");
    exit;
  }
}
// If manual form entry then don't send email to site or log entry.
if ($manualentryused==True)
  return;
// Send email to site with form details
if ($NotifyEmail=="")
  $NotifyEmail=$YourEmail;
if ($NotifyEmail!="")
{
  if ($NotifyTemplate=="")
  {
    $subject = "Website download request";
    $mailBody="The following files were requested.\n\n";
    for($k=0;$k<count($fname);$k++)
    {
      $mailBody.=$fname[$k];
      if ($floc[$k]!="")
        $mailBody.=" from ".$floc[$k];
      $mailBody.="\n";
    }
    $mailBody.="\nData from other form fields:-\n\n";
    if (!empty($_GET))
    {
      reset($_GET);
      while(list($namepair, $valuepair) = each($_GET))
      {
        $$namepair = $valuepair;
        if ((strlen($namepair)>2) && ($namepair!="linklokform") && ($namepair!="turing"))
          $mailBody.=$namepair." : ".$valuepair."\n";
      }
    }
    if (!empty($_POST))
    {
      reset($_POST);
      while(list($namepair, $valuepair) = each($_POST))
      {
        $$namepair = $valuepair;
        if ((strlen($namepair)>2) && ($namepair!="linklokform") && ($namepair!="turing"))
          $mailBody.=$namepair." : ".$valuepair."\n";
      }
    }
    $mailBody.="IP : ".$ipaddr."\n";
    $mailBody.="\n";
     linklokSendEmailOut($NotifyEmail,$NotifyEmail,$YourCompany,$subject,$mailBody,"N");
  }
  else
  {
    $res=linkloklinklokSendEmailUsingTemplate($NotifyEmail, $NotifyTemplate, $clientemail, $expiry, $ipaddr, $iplevel, $fname, $floc);
    if ($res!=true)
    {
      linklokShowMessage($ErrorTemplate,"Email could not be sent");
      exit;
    }
  }
}
// if Logfile required add a line to it containing details of this request
if ($LinklokLog!="")
{
  if (is_writeable($LinklokLog))
  {
    $fh=@fopen($LinklokLog,"a");
    if ($fh)
    {
      $logstr="Date,".date("d/m/y").",Time,".date("H:i:s").",IP,".$ipaddr; // Date,time,IP
      // Add filenames File0,test.zip,File1,demo.pdf etc
      for($k=0;$k<count($fname);$k++)
        $logstr.=",File".$k.",".$fname[$k];
      // Add other form fields Name,Adrian,Email,test@mysite.com etc
      if (!empty($_GET))
      {
        reset($_GET);
        while(list($namepair, $valuepair) = each($_GET))
        {
          $$namepair = $valuepair;
          if ((strlen($namepair)>2) && ($namepair!="linklokform") && ($namepair!="turing"))
            $logstr.=",".$namepair.",".$valuepair;
        }
      }
      if (!empty($_POST))
      {
        reset($_POST);
        while(list($namepair, $valuepair) = each($_POST))
        {
          $$namepair = $valuepair;
          if ((strlen($namepair)>2) && ($namepair!="linklokform") && ($namepair!="turing"))
            $logstr.=",".$namepair.",".$valuepair;
        }
      }
      $logstr.="\n";
      fputs($fh,$logstr);
      fclose($fh);
    }
  }
}
if ($goto!="")
{
  header("Location: ".$goto);
}
}

function linkloklinklokSendEmailUsingTemplate($toemail,$template,$clientemail, $expiry, $ipaddr, $iplevel, $fname,$floc)
{
  global $thisurl,$LinklokLocation,$LinklokLocations,$EmailHeaderNoSlashR,$LinklokKey;
  global $YourCompany,$YourEmail,$DownloadBackground;
  $usehtmlformat="Y";
  // See if template exists as a file. If not assume it is a buffer
  if (is_file($template))
  {
    $ext=linklokfileextension($template);
    if ($ext == ".php")
    {
      ob_start();
      include $template;
      $mailBody = ob_get_contents(); 
      ob_end_clean();    
    }
    else
    {
      if (!($fh = @fopen($template, "r")))
        return(false);
      $mailBody = fread ($fh, 200000);
      fclose($fh);
    }
    if ($ext==".txt")
      $usehtmlformat="N";
  }
  else
  {
    $mailBody=$template;
    if ((!is_integer(strpos($mailBody,"<html"))) && (!is_integer(strpos($mailBody,"<HTML"))))
      $usehtmlformat="N"; 
  }
  if ($expiry != 0)
  {
    if (strlen($expiry) == 12)
      $expirytime = mktime(substr($expiry, 8, 2), substr($expiry, 10, 2), 0, substr($expiry, 4, 2), substr($expiry, 6, 2), substr($expiry, 0, 4), -1);
    else
      $expirytime = time() + ($expiry * 60);
  }
  else
    $expirytime = 0;
  // Create secure links and get size and filename for each file
  for ($k=0;$k<count($fname);$k++)
  {
    $ProdLink[$k]=linkokGetSecureLink($fname[$k], $floc[$k], $expirytime, $clientemail, $ipaddr, $iplevel, $LinklokKey, "1", $thisurl);
    $ProdFile[$k]=linklokfilename($fname[$k]);
    if ($floc[$k]=="")
      $reallocation=$LinklokLocation.$fname[$k];
    else
      $reallocation=$LinklokLocations[$floc[$k]].$fname[$k];
    // See if link is local path or URL
    $pos=strpos(strtolower($reallocation),"http://");
    if (!is_integer($pos))
      $fsize=@filesize($reallocation);
    else
      $fsize=linklokfilesize_remote($reallocation);      
    $ProdSize[$k]=$fsize;
  }
  $max=30;
  if (count($fname)>$max)
    $max=count($fname);
  // First deal with any !!!link_n!!! that is part of hyperlink
  $start=0;
  do
  {
    $pos=strpos($mailBody,"<a",$start);
    if (!is_integer($pos))
      $pos=strpos($mailBody,"<A",$start);
    $pos2=strpos($mailBody,"</a>",$pos);
    if (!is_integer($pos2))
      $pos2=strpos($mailBody,"</A>",$pos);
    $found=0;
    if ((is_integer($pos)) && (is_integer($pos2)))
    {
      $found=1;
      for ($k=1; $k<=$max; $k++)
      {
        if ($ProdLink[$k-1]=="")
        {
          // See if !!!link_k!!! is within the hyperlink
          $hl=substr($mailBody,$pos,$pos2-$pos);
          $pos3=strpos($hl,"!!!link_".$k."!!!");
          if (!is_integer($pos3))
            $pos3=strpos($hl,"!!!link_".$k."!!!");
          if (is_integer($pos3))
          {
            $start=$pos;
            $mailBody=substr_replace($mailBody,"",$pos,$pos2-$pos);
            break;
          }
          else
            $start=$pos2;
        }
        else
          $start=$pos2;
      }
    }
  }
  while($found==1);
  // Now replace all other variables
  for ($k=1; $k<=$max; $k++)
  {
    if ($ProdLink[$k-1]!="")
    {
      $mailBody=eregi_replace("!!!filename_".$k."!!!",$ProdFile[$k-1],$mailBody);
      $mailBody=eregi_replace("!!!link_".$k."!!!",$ProdLink[$k-1],$mailBody);
      $mailBody=eregi_replace("!!!size_".$k."!!!",linklokFriendlyFileSize($ProdSize[$k-1]),$mailBody);
      $mailBody=eregi_replace("!!!expires_".$k."!!!",linklokFriendlyExpiryTime($expiry),$mailBody);
      if($usehtmlformat=="Y")
      {
        $tot="To download ".$ProdFile[$k-1]." click the link below:<BR>";
        $tot.="<a href=\"".$ProdLink[$k-1]."\">".$ProdFile[$k-1]."</a>";
        if ($ProdSize[$k-1]!="0")
          $tot.=" (".linklokFriendlyFileSize($ProdSize[$k-1]).")";
        if ($expiry!="0")
          $tot.=" ~ Download link will expire in ".linklokFriendlyExpiryTime($expiry);
      }
      else
      {
        $tot="To download ".$ProdFile[$k-1]." click the link below:\n".$ProdLink[$k-1]."\n";
        $tot.=$ProdFile[$k-1];
        if ($ProdSize[$k-1]!="0")
          $tot.=" (".linklokFriendlyFileSize($ProdSize[$k-1]).")";
        if ($expiry!="0")
          $tot.=" ~ Download link will expire in ".linklokFriendlyExpiryTime($expiry);
      }
      $mailBody=eregi_replace("!!!download_".$k."!!!",$tot,$mailBody);
    }
    else
    {
      $mailBody=eregi_replace("!!!filename_".$k."!!!","",$mailBody);
      $mailBody=eregi_replace("!!!size_".$k."!!!","",$mailBody);
      $mailBody=eregi_replace("!!!expires_".$k."!!!","",$mailBody);
      $mailBody=eregi_replace("!!!download_".$k."!!!","",$mailBody);
      $mailBody=eregi_replace("!!!link_".$k."!!!","",$mailBody);
    }
  }
  // Replace form variables
  if (!empty($_GET))
  {
    reset($_GET);
    while(list($namepair, $valuepair) = each($_GET))
    {
      $$namepair = $valuepair;
      if ((strlen($namepair)>2) && ($namepair!="linklokform") && ($namepair!="turing"))
        $mailBody=eregi_replace("!!!".$namepair."!!!",$valuepair,$mailBody);
    }
  }
  if (!empty($_POST))
  {
    reset($_POST);
    while(list($namepair, $valuepair) = each($_POST))
    {
      $$namepair = $valuepair;
      if ((strlen($namepair)>2) && ($namepair!="linklokform"))
        $mailBody=eregi_replace("!!!".$namepair."!!!",$valuepair,$mailBody);
    }
  }
  $mailBody=eregi_replace("!!!ip!!!",$ipaddr,$mailBody);
  // Now we should see if !!!eachfilestart!!! sections exists
  $start=0;
  do
  {
    $found=0;
    $pos=strpos($mailBody,"<!--eachfilestart-->");
    $pos2=strpos($mailBody,"<!--eachfileend-->");
    if ((is_integer($pos)) && (is_integer($pos2)))
    {
      $found=1;
      $buf=substr($mailBody,$pos+20,$pos2-$pos-20);
      // Now remove this section
      $mailBody1=substr($mailBody,0,$pos);
      $mailBody2=substr($mailBody,$pos2+18,strlen($mailBody)-$pos2-18);
      $mailBody=$mailBody1;
      for ($k=1; $k<=count($ProdLink); $k++)
      {
        $repeatbuf=$buf;
        $repeatbuf=eregi_replace("!!!filename!!!",$ProdFile[$k-1],$repeatbuf);
        $repeatbuf=eregi_replace("!!!link!!!",$ProdLink[$k-1],$repeatbuf);
        $repeatbuf=eregi_replace("!!!size!!!",linklokFriendlyFileSize($ProdSize[$k-1]),$repeatbuf);
        $repeatbuf=eregi_replace("!!!expires!!!",linklokFriendlyExpiryTime($expiry),$repeatbuf);
        if($usehtmlformat=="Y")
        {
          $tot="To download ".$ProdFile[$k-1]." click the link below:<BR>";
          $tot.="<a href=\"".$ProdLink[$k-1]."\">".$ProdFile[$k-1]."</a>";
          if ($ProdSize[$k-1]!="0")
            $tot.=" (".linklokFriendlyFileSize($ProdSize[$k-1]).")";
          if ($expiry!="0")
            $tot.=" ~ Download link will expire in ".linklokFriendlyExpiryTime($expiry);
        }
        else
        {
          $tot="To download ".$ProdFile[$k-1]." click the link below:\n".$ProdLink[$k-1]."\n";
          $tot.=$ProdFile[$k-1];
          if ($ProdSize[$k-1]!="0")
            $tot.=" (".linklokFriendlyFileSize($ProdSize[$k-1]).")";
          if ($expiry!="0")
            $tot.=" ~ Download link will expire in ".linklokFriendlyExpiryTime($expiry);
        }
        $repeatbuf=eregi_replace("!!!download!!!",$tot,$repeatbuf);
        $mailBody.=$repeatbuf;
      }
      $mailBody.=$mailBody2;
    }
  }
  while($found==1);
  // Now handle any !!!link(filename,expiry)!!! template variables
  $itemids=linklokgetitemvars($mailBody,"link");
  $items=explode("|",$itemids);
  for ($k=0;$k<count($items);$k++)
  {
    // Split item into filename and expiry time.
    $filename=strtok($items[$k],",");
    $exp=strtok(",");
    // Now split filename and file location if used
    $filename=strtok($filename,":");
    $flocation=strtok(":");
    if ($exp != 0)
    {
      if (strlen($exp)==12)
        $expiry=mktime(substr($exp,8,2),substr($exp,10,2),0,substr($exp,4,2),substr($exp,6,2),substr($exp,0,4),-1);
      else
        $expiry = time() + ($exp * 60);
    }
    $plink=linkokGetSecureLink($filename, $flocation, $expiry, $clientemail, $ipaddr, $iplevel, $LinklokKey, "1", $thisurl);
    $mailBody = str_replace("!!!link(".$items[$k].")!!!",$plink, $mailBody);
  }
  // Now handle any !!!size(filename)!!! template variables
  $itemids=linklokgetitemvars($mailBody,"size");
  $items=explode("|",$itemids);
  for ($k=0;$k<count($items);$k++)
  {
    $filename=strtok($items[$k],":");
    $flocation=strtok(":");
    if ($flocation=="")
      $fullpath=$LinklokLocation.$filename;
    else
      $fullpath=$LinklokLocations[$flocation].$filename;
    $pos = strpos(strtolower($fullpath), "http://");
    if (is_integer($pos))
    {
      $s=linklokfilesize_remote($fullpath);
      if (is_integer($s))
        $size=$s;
    }
    else
      $size = @filesize($fullpath);
    $mailBody = str_replace("!!!size(".$items[$k].")!!!",linklokFriendlyFileSize($size), $mailBody);
  }
  // Get subject for email
  if ($usehtmlformat!="Y")
  {
    $pos=strpos($mailBody,"\n");
    $subject=substr($mailBody,0,$pos);
    $mailBody=substr($mailBody,$pos+1,strlen($mailBody)-$pos-1);
  }
  else
  {
    $subject="Download Links";
    $pos=strpos($mailBody,"<TITLE>");
    if (!is_integer($pos))
      $pos=strpos($mailBody,"<title>");
    $pos2=strpos($mailBody,"</TITLE>");
    if (!is_integer($pos2))
      $pos2=strpos($mailBody,"</title>");
    if ((is_integer($pos)) &&  (is_integer($pos2)))
    {
      $subject=substr($mailBody,$pos+7,$pos2-$pos-7);
    }
  }  
  // If using a download background page replace auth with authe
  if ($DownloadBackground!="")
    $mailBody = str_replace("?linklokauth=", "?linklokauthe=", $mailBody);        
  if($usehtmlformat=="Y")
    $mailBody="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD W3 HTML//EN\">\n".$mailBody;  
  $result=linklokSendEmailOut($toemail,$YourEmail,$YourCompany,$subject,$mailBody,$usehtmlformat);
  return($result);
}

function linklokgetitemvars($buf,$n)
{
  $start = 0;
  $itemids="";
  do
  {
    $pos = strpos($buf, "!!!".$n."(", $start);
    $found = 0;
    if (is_integer($pos))
    {
      $found = 1;
      $pos2=strpos($buf, ")!!!", $pos);
      if (is_integer($pos2))
      {
        if ($itemids!="")
          $itemids.="|";
        $itemids.=substr($buf,$pos+strlen($n)+4,$pos2-($pos+strlen($n)+4));
      }
      $start=$pos2;
    }
  }
  while ($found==1);
  return($itemids);
}

function linklokSendEmail($toemail,$clientemail, $expiry, $ipaddr, $iplevel, $fname,$floc)
{
  global $thisurl,$LinklokLocation,$LinklokLocations,$EmailHeaderNoSlashR,$LinklokKey,$HTMLEmail;
  global $YourCompany,$YourEmail,$DownloadBackground;
  if ($expiry != 0)
  {
    if (strlen($expiry) == 12)
      $expirytime = mktime(substr($expiry, 8, 2), substr($expiry, 10, 2), 0, substr($expiry, 4, 2), substr($expiry, 6, 2), substr($expiry, 0, 4), -1);
    else
      $expirytime = time() + ($expiry * 60);
  }
  else
    $expirytime = 0;
  $subject = "Download Links from ".$YourCompany;
  $mailBody="Please use the link(s) below to begin downloading.\n\n";
  for ($k=0;$k<count($fname);$k++)
  {
    $plink=linkokGetSecureLink($fname[$k], $floc[$k], $expirytime, $clientemail, $ipaddr, $iplevel, $LinklokKey, "1", $thisurl);
    $fnameonly=linklokfilename($fname[$k]);
    if ($floc[$k]=="")
      $reallocation=$LinklokLocation.$fname[$k];
    else
      $reallocation=$LinklokLocations[$floc[$k]].$fname[$k];
    // See if link is local path or URL
    $pos=strpos(strtolower($reallocation),"http://");
    if (!is_integer($pos))
      $fsize=@filesize($reallocation);
    else
        $fsize=linklokfilesize_remote($reallocation);  
    if($HTMLEmail == "Y")
    {
      $mailBody.="To download ".$fnameonly." click the link below:\n";
      $mailBody.="<a href=\"".$plink."\">".$fnameonly."</a>";
      if ($fsize!=0)
        $mailBody.=" (".linklokFriendlyFileSize($fsize).")";
      if ($expiry!="0")
        $mailBody.=" ~ Download link will expire in ".linklokFriendlyExpiryTime($expiry).".\n";
      else
        $mailBody.=" \n";
      $mailBody.=" \n";
    }
    else
    {
      $mailBody.="To download ".$fnameonly." click the link below:\n".$plink."\n";
      $mailBody.=$fnameonly;
      if ($fsize!=0)
        $mailBody.=" (".linklokFriendlyFileSize($fsize).")";
      if ($expiry!="0")
        $mailBody.=" ~ Download link will expire in ".linklokFriendlyExpiryTime($expiry).".\n";
      else
        $mailBody.=" \n";
      $mailBody.=" \n";
    }
  }
  $mailBody.="\n";
  $mailBody.=$YourCompany."\n";
  $mailBody.=$YourEmail."\n";
  // If using a download background page replace auth with authe
  if ($DownloadBackground!="")
    $mailBody = str_replace("?linklokauth=", "?linklokauthe=", $mailBody);          
  if($HTMLEmail == "Y")
  {
    $mailBody = eregi_replace("\n","<br>\n",$mailBody);
    $mailBody="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD W3 HTML//EN\">\n<HTML>\n<HEAD>\n<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">\n<TITLE>Download Information</TITLE>\n</HEAD\n<BODY>\n".$mailBody;
    $mailBody.="</BODY>\n</HTML>\n";
  }
  $result=linklokSendEmailOut($toemail,$YourEmail,$YourCompany,$subject,$mailBody,$HTMLEmail);
  return($result);
}

function linklokgetmimetype($fn)
{
  global $mt;
  $ext=linklokfileextension($fn);
  if (isset($mt[$ext]))
    $mimetype=$mt[$ext];
  else
    $mimetype="";
  return("$mimetype");
}

function linklokFriendlyExpiryTime($exp)
{
  if ($exp==0)
    return("");
  if (($exp>=1) && ($exp<=59))
  {
    if ($exp==1)
      return("$exp minute");
    else
      return("$exp minutes");
  }
  if (($exp>=60) && ($exp<=1440))
  {
    $hours=intval($exp/60);
    $mins=$exp % 60;
    if ($hours==1)
      $ret=$hours." hour";
    else
      $ret=$hours." hours";
    if ($mins>0)
    {
      if ($mins==1)
        $ret.=" & ".$mins." minute";
      else
        $ret.=" & ".$mins." minutes";
    }
    return($ret);
  }
  if ($exp>=1441)
  {
    $days=intval($exp/1440);
    $exp=$exp-($days*1440);
    $hours=intval($exp/60);
    $mins=$exp % 60;
    if ($days==1)
      $ret=$days." day";
    else
      $ret=$days." days";
    if ($hours>0)
    {
      if ($mins==0)
        $ret.=" &";
      if ($hours==1)
        $ret.=" ".$hours." hour";
      else
        $ret.=" ".$hours." hours";
    }
    if ($mins>0)
    {
      if ($mins==1)
        $ret.=" & ".$mins." minute";
      else
        $ret.=" & ".$mins." minutes";
    }
    return($ret);
  }
}

function linklokFriendlyFileSize($sz)
{
  if ($sz<=1023)
    return($sz." Bytes");
  if (($sz>=1024) && ($sz<=1048575))
  {
    $sz=intval($sz/1024);
    return($sz." KB");
  }
  if ($sz>=1048576)
  {
    $sz=$sz/1048576;
    $sz=intval($sz*100)/100;
    return($sz." MB");
  }
}

function linklokfileextension($fname)
{
  if ($fname == "")
    return("");
  $pos = strrpos($fname, ".");
  if (is_integer($pos))
    return(strtolower(substr($fname, $pos)));
  return("");
}

function linklokfilename($fname)
{
  if ($fname == "")
    return("");
  $pos1 = strrpos($fname, "/");
  $pos2 = strrpos($fname, "\\");
  if ($pos1 === false)
    $pos1 = -1;
  if ($pos2 === false)
    $pos2 = -1;
  if ($pos1 > $pos2)
    $pos = $pos1;
  else
    $pos = $pos2;
  if ($pos > -1)
  {
    $name = substr($fname, $pos + 1);
    return($name);
  }
  return($fname);
}

function linklokCustomMessage($Template,$msg)
{
  if ($Template == "")
    return(0);
  $ext = linklokfileextension($Template);
  if ($ext == ".php")
  {
    ob_start();
    include $Template;
    $page = ob_get_contents(); 
    ob_end_clean();    
  }
  else
  {
    if (!($fh = @fopen($Template, "r")))
      return(0);
    $page = fread ($fh, 200000);
    fclose($fh);
  }
  $page = eregi_replace("!!!message!!!", $msg, $page);
  print $page;
  return(1);
}

function linklokShowMessage($Template,$msg)
{
  if (0==linklokCustomMessage($Template,$msg))
  {
    print ("<HTML>\n");
    print ("<HEAD>\n");
    print ("<TITLE>Linklok URL</TITLE>\n");
    print ("</HEAD>\n");
    print ("<BODY>\n");
    print("$msg<BR>");
    print ("</BODY>\n");
    print ("</HTML>\n");
  }
}

function linklokvalidemail($email)
{
  // Create the syntactical validation regular expression
  $regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
  // Presume that the email is invalid
  $valid =false;
  // Validate the syntax
  if (eregi($regexp, $email))
    $valid=true;
  return $valid;
}

function linklokxgetallheaders()
{
 global $_SERVER;
 $headers = array();
  while (list($key, $value) = each ($_SERVER))
  {
    if (strncmp($key, "HTTP_", 5) == 0)
    {
      $key = strtr(ucwords(strtolower(strtr(substr($key, 5), "_", " "))), " ", "-");
      $headers[$key] = $value;
    }
  }
  return $headers;
}

function linklokSendEmailOut($toemail, $fromemail, $fromname, $subject, $mailBody, $htmlformat)
{
  global $EmailHeaderNoSlashR, $ExtraMailParam, $ErrorTemplate, $ErrorEmail, $UsePHPmailer;
  // Remove any comma in from name
  $fromname = str_replace(",", " ", $fromname);
  // Handle multiple email addresses
  $sendtoemail=explode(",",$toemail);  
  // If phpmailer setup then use it otherwise handle with PHP mail() function
  if ($UsePHPmailer == 1)
  {
    global $EmailUsername, $EmailPassword, $EmailServer;
    require_once("class.phpmailer.php");
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->Host = $EmailServer;
    $mail->SMTPAuth = true; // This line is important for smtp authentication
    $mail->Username = $EmailUsername;
    $mail->Password = $EmailPassword;
    $mail->From = $fromemail;
    $mail->FromName = $fromname;
    for ($k=0; $k<count($sendtoemail); $k++)
      $mail->AddAddress($sendtoemail[$k]);
    if ($htmlformat == "Y")
      $mail->IsHTML(true);
    else
      $mail->IsHTML(false);
    $mail->Subject = $subject;
    $mail->Body = $mailBody;
    $mail->Send();
    if ($mail->isError())
      return(false);
    return(true);  
  }
  else
  {
    $headers = "From: " . $fromname . " <" . $fromemail . ">\r\n";
    $headers.= "Reply-To: " . $fromname . " <" . $fromemail . ">\r\n";
    $headers.= "MIME-Version: 1.0\r\n";
    if ($htmlformat=="Y")
    {
      $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
      $headers .= "Content-Transfer-Encoding: base64\r\n";      
      $mailBody=chunk_split(base64_encode($mailBody));
    }
    else
      $headers .= "Content-type: text/plain\r\n";
    if ($EmailHeaderNoSlashR == 1)
      $headers = eregi_replace("\r", "", $headers);
    if ($EmailHeaderNoSlashR == 1)
      $headers = eregi_replace("\r", "", $headers);
    for ($k=0; $k<count($sendtoemail); $k++)
    {
      if ($ExtraMailParam != "")
        $sent = mail($sendtoemail[$k], $subject, $mailBody, $headers, $ExtraMailParam);
      else
        $sent = mail($sendtoemail[$k], $subject, $mailBody, $headers);
      if ($sent==false)
        return(false);  
    }
    return(true);
  }
}

function linklokxfpassthru($file)
{
 global $downloadbuffer;
 if ($downloadbuffer>0)
 {
   while(!feof($file))
   {
      print(fread($file, $downloadbuffer));
      ob_flush();
      flush();
      sleep(1);
   }
   fclose($file);
 }
 else
   @fpassthru($file);
}

function linklokfilesize_remote($url, $timeout=2)
{
  $url = parse_url($url);
  if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout))
  {
    fwrite($fp, 'HEAD '.$url['path'].$url['query']." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
    @stream_set_timeout($fp, $timeout);
    while (!feof($fp))
    {
      $size = fgets($fp, 4096);
      if (stristr($size, 'Content-Length') !== false)
      {
        $size = trim(substr($size, 16));
        break;
      }
    }
    fclose ($fp);
  }
  return is_numeric($size) ? intval($size) : false;
}

function linkloklogdownload($logfile,$fname,$email)
{
  global $ipaddr;
  if (is_writeable($logfile))
  {
    $fh=@fopen($logfile,"a");
    if ($fh)
    {
      $logstr=date("d/m/y").",".date("H:i:s").",".$fname.",".$email.",".$ipaddr; // date,time,filename,email,IP
      $logstr.="\n";
      fputs($fh,$logstr);
      fclose($fh);
    }
  }
}
function linklokEmailDownloadNotify($fname, $id, $ipaddr, $expiry)
{
  global $NotifyDownloadEmail, $YourCompany, $YourEmail;
  $subject = "Linklok URL Download of $fname";
  $mailBody = "Download notification.\n\n";
  $mailBody .= "Filename : " . $fname . "\n";
  $mailBody .= "ID : " . $id . "\n";
  $mailBody .= "IP : " . $ipaddr . "\n";
  $mailBody .= "Download time : " . date("d M Y H:i:s") . "\n";
  $mailBody .= "Expiry time : " . date("d M Y H:i:s", $expiry) . "\n";
  $mailBody .= "User agent : " . $_SERVER['HTTP_USER_AGENT'] . "\n";
  $mailBody .= "\n";
  linklokSendEmailOut($NotifyDownloadEmail, $YourEmail, $YourCompany, $subject, $mailBody, "N");
  return;
}

?>