<?php
// send_over.php
// RJM Programming
// March, 2022
// Populate a localhost filename in user's HOME directory, as default, with (perhaps chunked) content

 function oururldecode($inenc) {
   $outenc=str_replace('+',' ',urldecode($inenc));
   
   for ($ik=0; $ik<=9; $ik++) {
     $outenc=str_replace('' . $ik . '   ', '' . $ik . ' + ', $outenc);
     $outenc=str_replace('   ' . $ik, ' + ' . $ik, $outenc);
   } 
    
   return $outenc;
 }

$dirbit="";
$xdirbit="";
$porttry=":8888";
$autohotkeythere="";
$autohotkeycompiler="";
$opdesc="";
$latestda="localhost";
$initc="";

if (PHP_OS == "Darwin") { 
    $dirbit.=getenv("HOME") . DIRECTORY_SEPARATOR;
    $opdesc="macOS ";
} else if (PHP_OS =='WINNT' || PHP_OS =='WIN32' || PHP_OS =='Windows') {
    $opdesc="Windows ";
    $dirbit.=getenv("USERPROFILE") . DIRECTORY_SEPARATOR;
    $porttry="";
    if (file_exists("C:\progra~1\AutoHotKey\Compiler\Ahk2Exe.exe")) {
      $autohotkeythere='"C:\Program Files\AutoHotKey\Compiler\Ahk2Exe.exe"';
    }
    if (file_exists($dirbit . "compileahk.exe")) {
      $autohotkeycompiler=$dirbit . "compileahk.exe";
    }
} else {
    $sugu="_";
    while (file_exists('send_over.php' . $sugu . 'GETME')) {
      $latestda='<a title="Latest send_over.php PHP code downloadable here and you should copy into (an up and running MAMP) Document Root place if you have not already done so or you need to update it and you want this web application to be of much practical use for a macOS or Windows MAMP based environment" download=send_over.php target=_blank href=' . 'send_over.php' . $sugu . 'GETME>localhost</a>';
      if ($sugu == '_') {
        $sugu='-';
      } else {
        $sugu.='-';
      }
    }
}

if (isset($_GET['initc'])) {
   $initc=oururldecode($_GET['initc']);
} else {
   $initc="EnvGet, vUserProfile, USERPROFILE

param := \"\"
paramtwo := \"x.ahk\"
paramthree := \"x.exe\"
yeslf := \"\"
dq := Chr(34)

Loop, %0%  ; For each parameter:
{
  if A_Index = 1
    ZZ_Index = \"%1%\"
  else
    if A_Index = 2
      ZZ_Index = \"%2%\"
    else
      if A_Index = 3
        ZZ_Index = \"%3%\"

  If ZZ_Index contains \".ahk\" 
  {
    paramtwo = \"%ZZ_Index%\"
    paramthree := StrReplace(paramtwo, \".ahk\", \".exe\")  
  }
  else 
  {
    If ZZ_Index contains \".AHK\" 
    {
       paramtwo = \"%ZZ_Index%\"
       paramthree := StrReplace(paramtwo, \".AHK\", \".exe\")  
    }
    else 
    {
       yeslf := StrReplace(ZZ_Index, \"(])\", \"`r`n\")  
       If StrLen(\"%yeslf%\") = StrLen(\"%ZZ_Index%\") 
       {

         If ZZ_Index contains \".\" 
         {
           FileDelete, %vUserProfile%\%paramtwo%
           FileCopy, %ZZ_Index%, %vUserProfile%\%paramtwo%         
         }
         else
         {
           If SubStr(yeslf, 1, 1) = Chr(34)
             yeslf := SubStr(yeslf, 2, (Strlen(yeslf) - 2))

           param := \"yes\"
         }
       }
       else 
         If SubStr(yeslf, 1, 1) = Chr(34)     
           yeslf := SubStr(yeslf, 2, (Strlen(yeslf) - 2))

         param := \"yes\"  ; Fetch the contents of the variable whose name is contained in A_Index.
    }
  }
}

If StrLen(param) != 0 
{
  FileDelete, %vUserProfile%\%paramtwo%
  FileAppend, %yeslf%, %vUserProfile%\%paramtwo%
}

IfWinExist Ahk2Exe.exe for AutoHotKey
  WinActivate
else 
{
  Run c:\Program Files\AutoHotkey\Compiler\Ahk2Exe.exe /in %vUserProfile%\%paramtwo% /out %vUserProfile%\%paramthree%
  WinActivate Ahk2Exe.exe for AutoHotKey
}

Run %vUserProfile%\%paramthree%

return";
}

if (isset($_GET['ahkthere'])) {
 if (strpos($_SERVER['SERVER_NAME'], 'localhost') !== false) {
   if ($autohotkeythere != "") {
    echo "<html><body onload=\"window.close();\">&nbsp;</body></html>";
   } else {
    echo "<html><body>&nbsp;</body></html>";
   }
   exit;
 }
}

if (isset($_GET['porttry'])) {
  if (strlen($_GET['porttry']) == 0) {
    $porttry="";
  } else {
    $porttry=':' . str_replace(':','',str_replace('+',' ',urldecode($_GET['porttry'])));
    if ($porttry == ":80") { $porttry="";  }
  }
}

if (isset($_GET['dirbit'])) {
    if (strlen($_GET['dirbit']) > 0) {
      $dirbit=str_replace('+',' ',urldecode($_GET['dirbit']));  
      if (strpos($dirbit . '`', DIRECTORY_SEPARATOR . '`') === false) {
        $dirbit.=DIRECTORY_SEPARATOR;
      }
    }
}

if (isset($_GET['ahkcommand']) && !isset($_GET['partcode'])) {
  if ($autohotkeycompiler != "") {
    exec($autohotkeycompiler . ' "' . str_replace(' ', '" "',trim(str_replace("\n", "(])", str_replace("\r\n", "(])", str_replace('+',' ',urldecode($_GET['ahkcommand'])))), '"')) . '"');
  }
  exit;
}

if (isset($_GET['partcode']) && isset($_GET['filecontent']) && isset($_GET['filename']) && strpos($_SERVER['SERVER_NAME'], 'localhost') !== false) {
  $dirbit="";
  $filebit=basename(str_replace('+',' ',urldecode($_GET['filename'])));  
  if (PHP_OS == "Darwin") { 
    $dirbit.=getenv("HOME") . DIRECTORY_SEPARATOR;
  } else if (PHP_OS =='WINNT' || PHP_OS =='WIN32' || PHP_OS =='Windows') {
    $dirbit.=getenv("USERPROFILE") . DIRECTORY_SEPARATOR;
  }
  if (isset($_GET['dirbit'])) {
    if (strlen($_GET['dirbit']) > 0) {
      $dirbit=str_replace('+',' ',urldecode($_GET['dirbit']));  
      if (strpos($dirbit . '`', DIRECTORY_SEPARATOR . '`') === false) {
        $dirbit.=DIRECTORY_SEPARATOR;
      }
    }
  }
  if ($dirbit == "") {
    $xdirbit=dirname(__FILE__) . DIRECTORY_SEPARATOR;
  }
  if (strlen($_GET['partcode']) > 0) {
    $isfinal=false;
    if (strpos($_GET['partcode'], 'of') !== false) {
      if (explode('of', $_GET['partcode'])[0] == explode('of', $_GET['partcode'])[1]) {
        $isfinal=true;
        if (strpos('`' . str_replace('+',' ',urldecode($_GET['partcode'])), '`1of') !== false) {
      if (file_exists($dirbit . $filebit)) {
        unlink($dirbit . $filebit);
      }
        }
      }
    }
    if (!$isfinal && strpos('`' . str_replace('+',' ',urldecode($_GET['partcode'])), '`1of') !== false) {
      file_put_contents($dirbit . $filebit, oururldecode($_GET['filecontent']));
    } else {
      $sofar="";
      if (file_exists($dirbit . $filebit)) {
        $sofar=file_get_contents($dirbit . $filebit);
      }
      //file_put_contents($dirbit . $filebit, $sofar . oururldecode($_GET['filecontent']));
      if (strpos($_GET['partcode'], 'of') !== false) {
      if (explode('of', $_GET['partcode'])[0] == explode('of', $_GET['partcode'])[1]) {
      file_put_contents($dirbit . $filebit, $sofar . oururldecode($_GET['filecontent']));
      if (strpos(strtolower($filebit), "compileahk.ahk") !== false) {
        if ($autohotkeythere != "") {
          if ($autohotkeycompiler != "") {
            unlink($autohotkeycompiler);
            exec($autohotkeythere . " /in " . $dirbit . $filebit . " /out " . $autohotkeycompiler);
          } else {
            $autohotkeycompiler=str_replace('.AHK','.exe',str_replace('.ahk','.exe',$dirbit . $filebit));
            exec($autohotkeythere . " /in " . $dirbit . $filebit . " /out " . $autohotkeycompiler);
          }        
        }
      } else if (strpos(strtolower($filebit), ".ahk") !== false) {
        if ($autohotkeythere != "") {
          if ($autohotkeycompiler != "" || 1 == 1) {
            $acompiler=str_replace('.AHK','.exe',str_replace('.ahk','.exe',$dirbit . $filebit));
            if (file_exists($acompiler)) { unlink($acompiler); }
            exec($autohotkeythere . " /in " . $dirbit . $filebit . " /out " . $acompiler);
          } 
 if (isset($_GET['ahkargs'])) {
  if ($autohotkeycompiler != "" || 1 == 1) {
    if (strlen($_GET['ahkargs']) == 0) {
      exec($acompiler);
    } else {
      exec($acompiler . ' "' . str_replace(' ', '" "',trim(str_replace("\n", "(])", str_replace("\r\n", "(])", str_replace('+',' ',urldecode($_GET['ahkargs'])))), '"')) . '"');
    }
  }
  //exit;
 }
        }
      }
      echo "<html><head><title>" . $dirbit . $filebit . "</title></head><body><textarea title='" . $dirbit . $filebit . "' rows=80 cols=120>" . file_get_contents($dirbit . $filebit) . "</textarea></body></html>";
      exit;
      } else {
      file_put_contents($dirbit . $filebit, $sofar . oururldecode($_GET['filecontent']));
      }
      } else {
      file_put_contents($dirbit . $filebit, $sofar . oururldecode($_GET['filecontent']));
      }
    }
  } else {
    file_put_contents($dirbit . $filebit, oururldecode($_GET['filecontent']));
    echo "<html><body onload=\"window.close();\"></body></html>";
    //echo "<html><body onload=\"window.close();\"></body></html>";
    exit;
  }
  echo "<html><body onload=\"window.close();\"></body></html>";
  exit;
}

echo "<html><head><title> Populate a localhost filename in user's HOME directory, as default, with (perhaps chunked) content</title>
<scr" . "ipt type=text/javascript>
 var wois=null;
 var porttry='" . $porttry . "';
 var found=false;
 var lasturl='', nexturl='';
 var urls=[];
 var lastnum=1;
 var sixhundred=500;
 var sixhund=600;
 var minusone=-1;
 var myleft=eval(eval('' + screen.width) - 100);
 var mytop=0;
 var wop=null;
 var initf=location.search.split('initf=')[1] ? decodeURIComponent(location.search.split('initf=')[1].split('&')[0]) : 'compileahk.ahk';
 var pinitc=location.search.split('initc=')[1] ? '1' : '';
 var pahkthere=location.search.split('ahkthere=')[1] ? '1' : '';

 function lengthcheck(invis) {
   if (initf != '') {
     document.getElementById('tfile').value=initf;
     initf='';
   }
   if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) { 
   alert('Suits an underlying macOS or Windows system only.');
   } else {
   lastnum=Math.floor(eval(eval('' + encodeURIComponent(invis).length) / sixhundred));
   if (lastnum == 0) { lastnum=1; }
   document.getElementById('tpart').value='1of' + lastnum;
   sixhund=Math.floor(eval(eval('' + invis.length) / lastnum));
   if (document.getElementById('mymeter')) {
     var rect=document.getElementById('mymeter').getBoundingClientRect();
     myleft=eval(20 + eval('' + rect.right));
     //alert('rect.top=' + rect.top + ' and x=' + eval(-60 + eval('' + rect.top)));
     mytop=eval(-60 + eval('' + rect.top));
   }
   if (pinitc != '') {
    pinitc='';
    document.getElementById('tbut').click();
   }
   if (pahkthere != '') {
    pahkthere='';
    wop=window.open('HTTP://localhost/send_over.php?ahkthere=y','_blank','left=' + eval(-100 + eval('' + screen.width)) + ',top=100,width=100,height=100' );
    setTimeout(wopcheck, 5000);
   }
   }
 }
 
 function wopcheck() {
  if (wop.closed) {
    wop=null;
    window.close();
  } else {
    wop.close();
    wop=null;
  }
 }
 
 function wisclosed() {
  if (wois.closed) {
   //alert('found');
   found=true;
   wois=null;
   document.getElementById('mymeter').value='' + minusone;
   if (nexturl != '') {
     //alert('more');
     createfile();
   }
  } else {
   if (porttry != '') {
    wois.close();
    wois=null;
    if (found) {
   document.getElementById('mymeter').value='' + minusone;
   if (nexturl != '') {
     //alert('more');
     createfile();
   }
    } else {
    lasturl=lasturl.replace(porttry, '');
    for (var jj=0; jj<urls.length; jj++) {
      urls[jj]=urls[jj].replace(porttry, '');
    }
    porttry='';
    wois=window.open(lasturl, '_blank', 'left=' + myleft + ',top=' + mytop + ',width=100,height=100' );
    setTimeout(wisclosed, 5000);
    }
   } else {
    wois.close();
    wois=null;
    if (found) {  
   document.getElementById('mymeter').value='' + minusone;
   if (nexturl != '') {
     //alert('more');
     createfile();
   }
    }
   }
  }
 }

 function createfile() {
   var startposis=0;
   var endposis=sixhund;
   if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) { 
   alert('Suits an underlying macOS or Windows system only.');
   } else {
   if (minusone >= 0 && minusone >= urls.length) {
     nexturl='';
     minusone=1;
   } else if (minusone >= 0 && minusone < urls.length) {
     lasturl=urls[minusone];
     document.getElementById('tpart').value=document.getElementById('tpart').value.replace('' + minusone + 'of', '' + eval(1 + minusone) + 'of');
     document.getElementById('mymeter').value='' + minusone;
     minusone++;
     if (urls.length > minusone) {
       nexturl=urls[minusone];
     //alert('2:' + lasturl);
     wois=window.open(lasturl, '_blank', 'left=' + myleft + ',top=' + mytop + ',width=100,height=100' );
     setTimeout(wisclosed, 5000);
     } else {
     wois=window.open(lasturl, '_blank', 'left=' + myleft + ',top=' + mytop + ',width=100,height=100' );
     }
   } else if (document.getElementById('tpart').value.replace('1of1','') == '') {
     lasturl='HTTP://localhost' + porttry + '/send_over.php?partcode=1of1&filename=' + encodeURIComponent(document.getElementById('tfile').value) + '&dirbit=' + encodeURIComponent(document.getElementById('tpath').value) + '&filecontent=' + encodeURIComponent(document.getElementById('tcontent').value) + '&ahkargs=' + encodeURIComponent(document.getElementById('tahkargs').value);
     //alert('1:' + lasturl);
     wois=window.open(lasturl, '_blank', 'left=' + myleft + ',top=' + mytop + ',width=100,height=100' );
     setTimeout(wisclosed, 5000);
   } else {
     //alert(lastnum);
     lasturl='HTTP://localhost' + porttry + '/send_over.php?partcode=&filename=' + encodeURIComponent(document.getElementById('tfile').value) + '&dirbit=' + encodeURIComponent(document.getElementById('tpath').value) + '&filecontent=' + encodeURIComponent(document.getElementById('tcontent').value);
     for (var ii=1; ii<=lastnum; ii++) {
       if (ii == lastnum) {
         urls.push('HTTP://localhost' + porttry + '/send_over.php?partcode=' + ii + 'of' + lastnum + '&filename=' + encodeURIComponent(document.getElementById('tfile').value) + '&dirbit=' + encodeURIComponent(document.getElementById('tpath').value) + '&filecontent=' + encodeURIComponent(document.getElementById('tcontent').value.substring(startposis))) + '&ahkargs=' + encodeURIComponent(document.getElementById('tahkargs').value);
       } else {
         urls.push('HTTP://localhost' + porttry + '/send_over.php?partcode=' + ii + 'of' + lastnum + '&filename=' + encodeURIComponent(document.getElementById('tfile').value) + '&dirbit=' + encodeURIComponent(document.getElementById('tpath').value) + '&filecontent=' + encodeURIComponent(document.getElementById('tcontent').value.substring(startposis,endposis)));
       }
       startposis+=sixhund;
       endposis+=sixhund;
     }
     lasturl=urls[0];
     if (urls.length > 1) {
       nexturl=urls[1];
       minusone=1;
     }
     //alert('0:' + lasturl);
     wois=window.open(lasturl, '_blank', 'left=' + myleft + ',top=' + mytop + ',width=100,height=100' );
     setTimeout(wisclosed, 5000);
   }
   }
 }
</scr" . "ipt>
</head><body onload=\" lengthcheck(document.getElementById('tcontent').value); \">
<h1>Populate a " . $latestda . " filename in user's HOME directory, as default, with (perhaps chunked) content</h1>
<h3>RJM Programming - March, 2022</h3>

<table>
<tr><td colspan=2><button style='background-color:yellow;' type=button id=tbut data-value='Create Local File' onclick='createfile();'>Create Local " . $opdesc . "<a onclick='event.stopPropagation();' target=_blank title='MAMP' href='//www.mamp.info'>MAMP</a> File</button></td></tr>
<tr><td>Optional Path (else user home directory)</td><td><input type=text id=tpath value='' placeholder='" . $dirbit . "'></input></td></tr>
<tr><td>Base Filename (eg. <a target=_blank title='AutoHotKey landing page' href='HTTP://www.autohotkey.org'>AutoHotKey</a> compiling script)</td><td><input style=display:inline-block; type=text id=tfile value='compileahk.ahk' title='AutoHotKey scripts have .ahk extension'></input>&nbsp;&nbsp;<input style=display:inline-block;width:40%; type=text id=tahkargs value='' placeholder='Optional derived executable argument(s) can go here'></input></td></tr>
<tr><td>Chunking Start Code</td><td><input style=display:inline-block; readonly type=text id=tpart value='1of5'></input>&nbsp;&nbsp;<meter id=mymeter min=0 max=5 value=0></meter></td></td></tr>
<tr><td style='vertical-align:top;'>Content (maybe chunked)</td><td><textarea style=background-color:#f0f0f0; cols=120 rows=80 onchange='lengthcheck(this.value);' onblur='lengthcheck(this.value);' id=tcontent>
" . $initc . "</textarea></td></tr>
</table>
</body>
</html>
";

?>