<?php
// rename_to_aid_sorting.php
// RJM Programming
// April, 2018

function qi($incis) {
  if (strpos($incis, " ") !== false) {
    return '"' . $incis . '"';
  }
  return $incis;
}

$htmlis="";
$putthisback="";
$dprefix="./";
$candidate=false;
if (isset($_GET['dirone']) && isset($_GET['dirtwo'])) {
  $dprefix=urldecode($_GET['dirone']) . urldecode($_GET['dirtwo']);
  if (substr($dprefix, -1) != "/" && substr($dprefix, -1) != "\\") {
    if (strpos($dprefix, "/") !== false) {
      $putthisback=explode("/",$dprefix)[-1 + sizeof(explode("/",$dprefix))];
    } else if (strpos($dprefix, "\\") !== false) {
      $putthisback=explode("\\",$dprefix)[-1 + sizeof(explode("\\",$dprefix))];
    }
  }
} else if (isset($_POST['dirone']) && isset($_POST['dirtwo'])) {
  $dprefix=urldecode($_POST['dirone']) . urldecode($_POST['dirtwo']);
  if (substr($dprefix, -1) != "/" && substr($dprefix, -1) != "\\") {
    if (strpos($dprefix, "/") !== false) {
      $putthisback=explode("/",$dprefix)[-1 + sizeof(explode("/",$dprefix))];
    } else if (strpos($dprefix, "\\") !== false) {
      $putthisback=explode("\\",$dprefix)[-1 + sizeof(explode("\\",$dprefix))];
    }
  }
}

$cnt=0;
$recnt=0;
$extarr=[];
$extarrlongestnumerical=[];

$changesfrom=[];
$changesto=[];
$fileis=[];
$categoryis=[];
$numcis=[];

$extlist=",";
$ext_nl_list=",";
$ext_nf_list=",";
$ext_dl_list=",";
$ext_fo_list=",";

$asteriskybit="[0123456789]*.*";
//$asteriskybit="[0123456789]*_[0123456789]*.png";
if (isset($_GET['asteriskybit'])) {
  $asteriskybit=urldecode($_GET['asteriskybit']);
} else if (isset($_POST['asteriskybit'])) {
  $asteriskybit=urldecode($_POST['asteriskybit']);
}

if (isset($_POST['donothing']) || isset($_GET['donothing'])) {  // Do nothing
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p></p></body></html>";
} else if (isset($_POST['cmd']) && isset($_POST['infile']) && isset($_POST['outfile'])) {  // Perform rename
        if (strpos(strtoupper(('' . PHP_OS)), "WINDOW") !== false && strpos($_SERVER['SERVER_NAME'],"rjmprogramming.com.au") === false) {

          if (file_exists(urldecode($_POST['infile']))) {
          if (!file_exists(urldecode($_POST['outfile']))) {
          if (strpos("~" . str_replace("mv ", "rename ",urldecode($_POST['cmd'])), "~rename " . urldecode($_POST['infile']) . " ") !== false) {
          exec(urldecode($_POST['cmd']));
          if (file_exists(urldecode($_POST['outfile']))) {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>" . urldecode($_POST['cmd']) ."<br>rem Command successful</p></body></html>";
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but the following command does  not work ... " . urldecode($_POST['cmd']) ."</p></body></html>";
          }
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but cannot do " . urldecode($_POST['cmd']) . "</p></body></html>";
          }
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but " . urldecode($_POST['outfile']) . " already exists.</p></body></html>";
          }
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, btt " . urldecode($_POST['infile']) . " does not exist.</p></body></html>";
          }

        } else if (strpos(strtoupper(('' . PHP_OS)), "WINDOW") !== false) {
          exit;
        } else if (strpos($_SERVER['SERVER_NAME'],"rjmprogramming.com.au") === false) {

          if (file_exists(urldecode($_POST['infile']))) {
          if (!file_exists(urldecode($_POST['outfile']))) {
          if (strpos("~" . str_replace("mv ", "rename ",urldecode($_POST['cmd'])), "~rename " . urldecode($_POST['infile']) . " ") !== false) {
          exec(urldecode($_POST['cmd']));
          if (file_exists(urldecode($_POST['outfile']))) {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>" . urldecode($_POST['cmd']) ." # Command successful</p></body></html>";
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but the following command does not work ... " . urldecode($_POST['cmd']) ."</p></body></html>";
          }
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but cannot do " . urldecode($_POST['cmd']) . "</p></body></html>";
          }
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but " . urldecode($_POST['outfile']) . " already exists.</p></body></html>";
          }
          } else {
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title></head>
<body style=background-color:yellow;><p>Sorry, but " . urldecode($_POST['infile']) . " does not exist. after " . urldecode($_POST['cmd']) . "</p></body></html>";
          }

        } else {
          exit;
        }
 
}

if ($htmlis == "") {  // Analyze
 $htmlis="<!doctype html><head><title>Rename to Aid Sorting Candidates - RJM Programming - April, 2018</title>
<script type='text/javascript'>
        var cbsare=[], icbsare=[], jcbsare=0, reportstr='', pon=null, dprefix=\"" . $dprefix . "\", putthisback=\"" . $putthisback . "\"; 
        function remention(ij,newren) {
          var spares=[], fixc3=false, fc3from='', fc3to=newren;
          if (document.getElementById('c3_' + ij)) {
                if (document.getElementById('c3_' + ij).innerHTML.replace('mv ','rename ').indexOf('rename ') == 0) fixc3=true;
                if (fixc3) {
                  spares=document.getElementById('c3_' + ij).innerHTML.split(dprefix);
                  if (spares.length == 3) {
                    if (newren.indexOf(' ') != -1) {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + dprefix + (spares[1] + '\"' + dprefix).replace('\"\"','\"') + newren + '\"';
                    } else if (spares[2].indexOf('\"') != -1) {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + dprefix + spares[1] + dprefix + newren + '\"';
                    } else {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + dprefix + spares[1] + dprefix + newren;
                    }
                  } else if (putthisback != '') {
                  spares=document.getElementById('c3_' + ij).innerHTML.split(putthisback);
                  if (spares.length == 3) {
                    if (newren.indexOf(' ') != -1) {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + dprefix + (spares[1] + '\"' + putthisback).replace('\"\"','\"') + newren + '\"';
                    } else if (spares[2].indexOf('\"') != -1) {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + dprefix + spares[1] + putthisback + newren + '\"';
                    } else {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + dprefix + spares[1] + putthisback + newren;
                    }
                  }
                  } else {
                  spares=document.getElementById('c3_' + ij).innerHTML.split(' ');
                  if (spares.length == 3) {
                    if (newren.indexOf(' ') != -1) {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + ' ' + spares[1] + ' \"' + newren + '\"';
                    } else {
                      document.getElementById('c3_' + ij).innerHTML=spares[0] + ' ' + spares[1] + ' ' + newren;
                    }
                  }
                  }
                }
          }
          if (document.getElementById('dc1_' + ij) && document.getElementById('invc2_' + ij)) {
           if (document.getElementById('invc2_' + ij).value != newren) {
            var preredo='', redo=document.getElementById('dc1_' + ij).innerHTML.replace(' checked=\"true\"','').replace(\" checked='true'\",\"\").replace(' checked','');
            if (redo.indexOf('rename \"') != -1) {
              spares=redo.split('rename \"');
              spares[0]+='rename \"' + spares[1].split('\"')[0] + '\" ';
              preredo=redo.substring(0,spares[0].length);
              redo=redo.substring(preredo.length);
            } else if (redo.indexOf('mv \"') != -1) {
              spares=redo.split('mv \"');
              spares[0]+='mv \"' + spares[1].split('\"')[0] + '\" ';
              preredo=redo.substring(0,spares[0].length);
              redo=redo.substring(preredo.length);
            } else if (redo.indexOf('rename ') != -1) {
              spares=redo.split('rename ');
              spares[0]+='rename ' + spares[1].split(' ')[0] + ' ';
              preredo=redo.substring(0,spares[0].length);
              redo=redo.substring(preredo.length);
            } else if (redo.indexOf('mv ') != -1) {
              spares=redo.split('mv ');
              spares[0]+='mv ' + spares[1].split(' ')[0] + ' ';
              preredo=redo.substring(0,spares[0].length);
              redo=redo.substring(preredo.length);
            }
            while (redo.indexOf(document.getElementById('invc2_' + ij).value) != -1) {
              redo=redo.replace(document.getElementById('invc2_' + ij).value, newren);
            }
            document.getElementById('dc1_' + ij).innerHTML=preredo + redo;
            document.getElementById('invc2_' + ij).value=newren;
           }
          }
        }
        function setthemoff() {
          if (jcbsare < icbsare.length) {
           if (icbsare[jcbsare] == '') {
            jcbsare++;
            setTimeout(setthemoff, 50);
           } else {
            document.getElementById(icbsare[jcbsare]).click();
            jcbsare++;
            setTimeout(setthemoff, 5000);
           }
          } else {
           document.getElementById('report').innerHTML=reportstr;
           reportstr='';
           document.getElementById('iall').checked=false;
           document.getElementById('iall').style.cursor='pointer';
          }
        }
        function clickall() {
          reportstr='';
          document.getElementById('report').innerHTML='';
          cbsare=document.getElementsByTagName('input');
          icbsare=[];
          for (var icb=0; icb<cbsare.length; icb++) {
            if (cbsare[icb].id != 'iall' && cbsare[icb].outerHTML.indexOf('checkbox') != -1 && !cbsare[icb].checked) {
              icbsare.push(cbsare[icb].id);
            } else {
              icbsare.push('');
            }
          }
          document.getElementById('iall').style.cursor='progress';
          jcbsare=0;
          setthemoff();
        }
function appendtoreport(iois) {
  if (iois != null) {
  if (iois.src != '') {
    var aconto = (iois.contentWindow || iois.contentDocument);
    if (aconto != null) {
   try {
     if (aconto.document) { aconto = aconto.document; }
     if (aconto.body.innerHTML != '') {
     if (pon != null) {
       if (aconto.body.innerHTML.indexOf('uccessful') == -1) {
         pon.checked=false;
       } else {
         document.getElementById(pon.id.replace('bxc1','2').replace('bxc','')).style.backgroundColor='#e0e0e0';
         document.getElementById(pon.id.replace('bxc1','2').replace('bxc','')).readOnly=true;
         pon.style.display='none';
       }
     }
     reportstr+=aconto.body.innerHTML + '<br>';
     }
   } catch(eee) { }
    }
  }
  }
}
</script>
</head>
<body style=background-color:yellow;>
<h1>Rename to Aid Sorting Candidates</h1>
<h3>RJM Programming - April, 2018</h3>
<iframe onload=appendtoreport(this); style=display:none; name=doit id=doit src=./rename_to_aid_sorting.php?donothing=y></iframe>
<div id=report></div>
<table cellpadding=5 cellspacing=5 border=5><tr><td>
<table cellpadding=5 cellspacing=5 id='mytable' border=20>
<tbody id='mytbody'>
<tr style=background-color:#d0d0d0;><th>Existing Filename <br>in " . str_replace($putthisback,"",$dprefix) . " <br>satisfying " . $putthisback . $asteriskybit . "</th><th>Could Rename to Aid <br>With Numerical File Sorts</th><th>Make That Happen?<br><div id=dall style=display:none;> All? <input id=iall type=checkbox onchange=clickall();></input></th></tr>
</tbody>
</table></td><td style=background-color:#f0f0f0;vertical-align:top;>
<form method=GET action=./rename_to_aid_sorting.php>
Relative to This Program Directory: <input type=text name=dirone id=dirone value='./'></input><br><br>
Filename Prefix (that File Filter does not apply to): <input type=text name=dirtwo id=dirtwo value=''></input><br><br>
File Filter: <input type=text name=asteriskybit id=asteriskybit value='[0123456789]*.*'></input><br><br>
<input style=background-color:pink; type=submit value=Analyze></input>
</form>
</td></tr></table>
<form style=display:none; id=fdoit action=./rename_to_aid_sorting.php method=POST target=doit>
<input type=hidden id=infile name=infile value=''></input>
<input type=hidden id=outfile name=outfile value=''></input>
<input type=hidden id=cmd name=cmd value=''></input>
<input type=submit id=sdoit value=Rename></input>
</form>
</body>
</html>
";



foreach (glob($dprefix . $asteriskybit) as $filename) {
  //echo $filename . "\n";
  //$htmlis=str_replace("</tbody>","\n<tr><td id=c1_" . $cnt . ">" . str_replace($dprefix, "", $filename) . "</td><td id=c2_" . $cnt . "></td><td id=c3_" . $cnt . "></td></tr>\n</tbody>",$htmlis);
  $thisext="." . explode(".", str_replace($dprefix, "", $filename))[-1 + sizeof(explode(".", str_replace($dprefix, "", $filename)))];
  $nfields=1;
  $ncnt=0;
  $delimis=".";
  while (substr(str_replace($dprefix, "", $filename),$ncnt,1) >= '0' && substr(str_replace($dprefix, "", $filename),$ncnt,1) <= '9') {
   $ncnt++;
  }
  if (substr(str_replace($dprefix, "", $filename),$ncnt,1) != '.') {
    $delimis=substr(str_replace($dprefix, "", $filename),$ncnt,1);
    $nfs=explode(substr(str_replace($dprefix, "", $filename),$ncnt,1), str_replace($dprefix, "", $filename));
    $nfields=sizeof($nfs);
  }
    $fileis[sizeof($fileis)]=str_replace($dprefix, "", $filename);
    $categoryis[sizeof($categoryis)]=$thisext . "." . $nfields . ";" . $delimis;
    $numcis[sizeof($numcis)]=$ncnt;
  $extarrlongestnumerical[sizeof($extarrlongestnumerical)]=$ncnt;
  $extarr[sizeof($extarr)]=$thisext;
  if (strpos($extlist, "," . $thisext . "." . $nfields . ";" . $delimis . ",") === false) {
    //echo str_replace($dprefix, "", $filename) . " ... " . $thisext . "." . $nfields . ";" . $delimis;
    //exit;
    $extlist.=$thisext . "." . $nfields . ";" . $delimis . ",";
    $ext_nl_list.="" . $ncnt . ",";     // count of numbers before delimiter happens
    $ext_nf_list.="" . $nfields . ",";  // count of fields of delimiter below
    $ext_dl_list.="" . $delimis . ",";  // delimiter
    $ext_fo_list.="" . str_replace($dprefix, "", $filename) . ",";  // first filename example
    //$fileis[sizeof($fileis)]=str_replace($dprefix, "", $filename);
    //$categoryis[sizeof($categoryis)]=$thisext . "." . $nfields . ";" . $delimis;
    //$numcis[sizeof($numcis)]=$ncnt;
  } else {
    $xxsl=sizeof(explode(",", explode("," . $thisext . "." . $nfields . ";" . $delimis . ",", $extlist)[0]));
    $vsx=explode(",", $ext_nl_list);
    if ($vsx[$xxsl] != $ncnt) {
    //$fileis[sizeof($fileis)]=str_replace($dprefix, "", $filename);
    //$categoryis[sizeof($categoryis)]=$thisext . "." . $nfields . ";" . $delimis;
    //$numcis[sizeof($numcis)]=$ncnt;
      if ($ncnt < $vsx[$xxsl]) {
        $changesfrom[sizeof($changesfrom)]=str_replace($dprefix, "", $filename);
        $prefix="";
        while ($ncnt < $vsx[$xxsl]) {
          $prefix.="0";
          $ncnt++;
        }
        $changesto[sizeof($changesto)]=$prefix . str_replace($dprefix, "", $filename);
      //echo "0 " . $prefix . str_replace($dprefix, "", $filename) . $xxsl . "<br>" . explode(",",$ext_fo_list)[$xxsl] . "<br>" . $thisext . "." . $nfields . ";" . $delimis . "<br>" . str_replace($dprefix, "", $filename) . " \$vsx[\$xxsl]=" . $vsx[$xxsl] . " and \$ncnt=" . $ncnt . " ... " . $ext_fo_list;
      // //$ext_nl_list[$xxsl].=";" . $nfields;
      //exit;
      } else {
        $recon=$vsx[0];
        for ($ivi=1; $ivi<sizeof($vsx); $ivi++) {
          if ($ivi == $xxsl) {
            $recon.="," . $ncnt;
          } else {
            $recon.="," . $vsx[$ivi];
          }
        }
            //if ($ncnt > 3) {
            //echo $thisext . "." . $nfields . ";" . $delimis . " changing from " . $vsx[$ivi] . " to " . $ncnt . "<br>" . $extlist . "<br>" . $ext_nl_list . "<br> to <br>" . $recon;
            //exit;
            //}
        $ext_nl_list=$recon;
    //$fileis[sizeof($fileis)]=str_replace($dprefix, "", $filename);
    //$categoryis[sizeof($categoryis)]=$thisext . "." . $nfields . ";" . $delimis;
    //$numcis[sizeof($numcis)]=$ncnt;
        for ($ii=0; $ii<sizeof($categoryis); $ii++) {
          if ($categoryis[$ii] == ($thisext . "." . $nfields . ";" . $delimis)) {
            $vs=$numcis[$ii];
        $changesfrom[sizeof($changesfrom)]=$fileis[$ii];
            $prefix="";
        while ($vs < $ncnt) {
          $prefix.="0";
          $vs++;
        }
        $changesto[sizeof($changesto)]=$prefix . $fileis[$ii];
          }
        }
      //echo "1 " . $xxsl . "<br>" . explode(",",$ext_fo_list)[$xxsl] . "<br>" . $thisext . "." . $nfields . ";" . $delimis . "<br>" . str_replace($dprefix, "", $filename) . " \$vsx[\$xxsl]=" . $vsx[$xxsl] . " and \$ncnt=" . $ncnt . " ... " . $ext_fo_list;
      // //$ext_nl_list[$xxsl].=";" . $nfields;
      //exit;
      }
    }
  }
  $cnt++;
}


foreach (glob($dprefix . $asteriskybit) as $filename) {
  //$htmlis=str_replace("</tbody>","\n<tr><td id=c1_" . $cnt . ">" . str_replace($dprefix, "", $filename) . "</td><td id=c2_" . $cnt . "></td><td id=c3_" . $cnt . "></td></tr>\n</tbody>",$htmlis);
  $found=false;
  $newf="";
  $newcb="";
  for ($iu=(-1 + sizeof($changesfrom)); $iu>=0; $iu--) {
    if (!$found) {
      if ($fileis[$recnt] == $changesfrom[$iu] && $changesto[$iu] != $fileis[$recnt] && trim($changesto[$iu]) != "" && strpos($changesto[$iu],".") !== false) {
        //$newf=$putthisback . $changesto[$iu];
        $newf="<input style=width:98%; onblur=remention(" . $recnt . ",this.value); type=text id=ic2_" . $recnt . " value='" . $putthisback . $changesto[$iu] . "'></input><input type=hidden id=invc2_" . $recnt . " value='" . $putthisback . $changesto[$iu] . "'></input>";
        if (strpos(strtoupper(('' . PHP_OS)), "WINDOW") !== false && strpos($_SERVER['SERVER_NAME'],"rjmprogramming.com.au") === false) {
          $newcb='<div id=dc1_' . $recnt . '> Rename file at left <br>to name at right <input id=icbxc2_' . $recnt . ' type=checkbox onchange="pon=this; document.getElementById(' . "'" . 'infile' . "'" . ').value=' . "'";
          $newcb.=$dprefix . $fileis[$recnt];
          $newcb.="'" . '; document.getElementById(' . "'" . 'cmd' . "'" . ').value=' . "'";
          $newcb.="rename " . qi($dprefix . $fileis[$recnt]) . " " .  qi($putthisback . $changesto[$iu]);
          $newcb.="'" . '; document.getElementById(' . "'" . 'outfile' . "'" . ').value=' . "'";
          $newcb.=$dprefix . $changesto[$iu];
          $newcb.="'" . '; document.getElementById(' . "'" . 'doit' . "'" . ').style.display=' . "'" . 'block' . "'" . '; document.getElementById(' . "'" . 'sdoit' . "'" . ').click(); "' . "></input></div>";
          $htmlis=str_replace("<body style=", "<body onload=\"document.getElementById('dall').style.display='block';\" style=",$htmlis);
        } else if (strpos(strtoupper(('' . PHP_OS)), "WINDOW") !== false) {
          $newcb="rename " . qi($dprefix . $fileis[$recnt]) . " " . qi($putthisback . $changesto[$iu]);
        } else if (strpos($_SERVER['SERVER_NAME'],"rjmprogramming.com.au") === false) {
          $newcb='<div id=dc1_' . $recnt . '> Rename file at left <br>to name at right <input id=icbxc1_' . $recnt . ' type=checkbox onchange="pon=this; document.getElementById(' . "'" . 'infile' . "'" . ').value=' . "'";
          $newcb.=$dprefix . $fileis[$recnt];
          $newcb.="'" . ';  document.getElementById(' . "'" . 'cmd' . "'" . ').value=' . "'";
          $newcb.="mv " . qi($dprefix . $fileis[$recnt]) . " " .  qi($dprefix . $changesto[$iu]);
          $newcb.="'" . '; document.getElementById(' . "'" . 'outfile' . "'" . ').value=' . "'";
          $newcb.=$dprefix . $changesto[$iu];
          $newcb.="'" . '; document.getElementById(' . "'" . 'doit' . "'" . ').style.display=' . "'" . 'block' . "'" . ';  document.getElementById(' . "'" . 'sdoit' . "'" . ').click(); "' . "></input></div>";
          $htmlis=str_replace("<body style=", "<body onload=\"document.getElementById('dall').style.display='block';\" style=",$htmlis);
        } else {
          $newcb="mv " . qi($dprefix . $fileis[$recnt]) . " " . qi($dprefix . $changesto[$iu]);
        }
      }
    }
  }
  if ($fileis[$recnt] != '') {
  $htmlis=str_replace("</tbody>","\n<tr><td id=c1_" . $recnt . ">" . $putthisback . $fileis[$recnt] . "</td><td id=c2_" . $recnt . ">" . $newf . "</td><td id=c3_" . $recnt . ">" . $newcb . "</td></tr>\n</tbody>",$htmlis);
  $recnt++;
  }
}


}

//echo sizeof($fileis);
echo $htmlis;
?>

