<?php
 // mil_mapping.php
 // RJM Programming
 // September, 2017
 // XML subtractions and additions 


function str_replace_first($from, $to, $subject) {  // thanks to https://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on-the-first-match
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $subject, 1);
}

function yoururldecode($ins) {
  return str_replace('`','',str_replace('+',' ',urldecode($ins)));
}

$defplace="./*.*_GETME";
$defreadonly=" readonly";
$defplace="./*.*";
$defreadonly="";
$acom="";
$iscl=false;
$ourargc=2;
$iscurl=false;

if ($argc >= 1) {  // PHP command line
 $filespec="COMM.MIL*.xml";
 $startfind="<section ";
 $findthis='role="annot_cont"';
 $endfind=">";
 $findthisafter='<leg-history ';
 $findthisaftertwo='<notes';
 $deletedlabelfindstart=' href="';
 $deletedlabelfindend='"';
 $addedlabelfindstart='<title arch="online">Note</title>';
 $addedlabelfindend='"';
 $donotfindthisstart='<?';
 $donotfindthisend='?>';
 if ($argc >= 2) $filespec=yoururldecode($argv[1]);
 if ($argc >= 3) $startfind=yoururldecode($argv[2]);
 if ($argc >= 4) $findthis=yoururldecode($argv[3]);
 if ($argc >= 5) $endfind=yoururldecode($argv[4]);
 if ($argc >= 6) $findthisafter=yoururldecode($argv[5]);
 if ($argc >= 7) $findthisaftertwo=yoururldecode($argv[6]);
 if ($argc >= 8) $deletedlabelfindstart=yoururldecode($argv[7]);
 if ($argc >= 9) $deletedlabelfindend=yoururldecode($argv[8]);
 if ($argc >= 10) $addedlabelfindstart=yoururldecode($argv[9]);
 if ($argc >= 11) $addedlabelfindend=yoururldecode($argv[10]);
 if ($argc >= 12) $donotfindthisstart=yoururldecode($argv[11]);
 if ($argc >= 13) $donotfindthisend=yoururldecode($argv[12]);
 $iscl=true;
 $ourargc=$argc;
} else {   // Non PHP command line ...
 $filespec="COMM.MIL*.xml";
 if (isset($_GET['filespec'])) $filespec=str_replace("+"," ",urldecode($_GET['filespec']));
 if (!isset($_GET['startfind']) && strpos($filespec, '`') !== false) {
 $bigstr=$filespec;
 $filespec=explode("`", $bigstr)[0];
 if (strpos($bigstr, ($filespec . '``')) !== false) {   // Curl ordered
 $startfind=explode("``", $bigstr)[1];
 $findthis=explode("``", $bigstr)[2];
 $endfind=explode("``", $bigstr)[3];
 $findthisafter=explode("``", $bigstr)[4];
 $findthisaftertwo=explode("``", $bigstr)[5];
 $deletedlabelfindstart=explode("``", $bigstr)[6];
 $deletedlabelfindend=explode("``", $bigstr)[7];
 $addedlabelfindstart=explode("``", $bigstr)[8];
 $addedlabelfindend=explode("``", $bigstr)[9];
 $donotfindthisstart=explode("``", $bigstr)[10];
 $donotfindthisend=explode("``", $bigstr)[11];
 if (isset($_GET['php'])) {
   $ds='/';
   if (strpos(dirname(__FILE__), $ds) === false) $ds=substr("\\",0,1);
   echo "<!doctype html><html><body><div style='font-size:12px;overflow:wrap;width:100%;'>Performing <br> " . str_replace(">","&gt;",str_replace("<","&lt;","php " . dirname(__FILE__) . $ds . 'mil_mapping.php ' . str_replace("%60%60"," ",str_replace("%60%60%60%60"," %60 ",urlencode($_GET['filespec']))))) . "</div></body></html>"; 
   exec("php " . dirname(__FILE__) . $ds . 'mil_mapping.php ' . str_replace("%60%60"," ",str_replace("%60%60%60%60"," %60 ",urlencode($_GET['filespec'])))); 
   exit;
 } else if (isset($_GET['curl'])) {
   echo "<!doctype html><html><body><div style='font-size:12px;overflow:wrap;width:100%;'>Performing <br> " . str_replace(">","&gt;",str_replace("<","&lt;","curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?filespec=' . urlencode($_GET['filespec']))) . "</div></body></html>"; 
   exec("curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?filespec=' . urlencode($_GET['filespec'])); 
   exit;
 } else {
   $iscurl=true;
 }
 } else { // Curl long winded
 $iscurl=true;
 $startfind="<section ";
 $findthis='role="annot_cont"';
 $endfind=">";
 $findthisafter='<leg-history ';
 $findthisaftertwo='<notes';
 $deletedlabelfindstart=' href="';
 $deletedlabelfindend='"';
 $addedlabelfindstart='<title arch="online">Note</title>';
 $addedlabelfindend='"';
 $donotfindthisstart='<?';
 $donotfindthisend='?>';
 if (strpos($bigstr, "startfind`") !== false) $startfind=explode("`",explode("startfind`", $bigstr)[1])[0];
 if (strpos($bigstr, "findthis`") !== false) $findthis=explode("`",explode("findthis`", $bigstr)[1])[0];
 if (strpos($bigstr, "endfind`") !== false) $startfind=explode("`",explode("endfind`", $bigstr)[1])[0];
 if (strpos($bigstr, "findthisafter`") !== false) $findthisafter=explode("`",explode("findthisafter`", $bigstr)[1])[0];
 if (strpos($bigstr, "findthisaftertwo`") !== false) $findthisaftertwo=explode("`",explode("findthisaftertwo`", $bigstr)[1])[0];
 if (strpos($bigstr, "deletedlabelfindstart`") !== false) $deletedlabelfindstart=explode("`",explode("deletedlabelfindstart`", $bigstr)[1])[0];
 if (strpos($bigstr, "deletedlabelfindend`") !== false) $deletedlabelfindend=explode("`",explode("deletedlabelfindend`", $bigstr)[1])[0];
 if (strpos($bigstr, "addedlabelfindstart`") !== false) $addedlabelfindstart=explode("`",explode("addedlabelfindstart`", $bigstr)[1])[0];
 if (strpos($bigstr, "addedlabelfindend`") !== false) $addedlabelfindend=explode("`",explode("addedlabelfindend`", $bigstr)[1])[0];
 if (strpos($bigstr, "donotfindthisstart`") !== false) $donotfindthisstart=explode("`",explode("donotfindthisstart`", $bigstr)[1])[0];
 if (strpos($bigstr, "donotfindthisend`") !== false) $donotfindthisend=explode("`",explode("donotfindthisend`", $bigstr)[1])[0];
 }
 } else {    // Surfing the net 
 $startfind="<section ";
 if (isset($_GET['startfind'])) $startfind=str_replace("+"," ",urldecode($_GET['startfind']));
 $findthis='role="annot_cont"';
 if (isset($_GET['findthis'])) $findthis=str_replace("+"," ",urldecode($_GET['findthis']));
 $endfind=">";
 if (isset($_GET['endfind'])) $endfind=str_replace("+"," ",urldecode($_GET['endfind']));
 $findthisafter='<leg-history ';
 if (isset($_GET['findthisafter'])) $findthisafter=str_replace("+"," ",urldecode($_GET['findthisafter']));
 $findthisaftertwo='<notes';
 if (isset($_GET['findthisaftertwo'])) $findthisaftertwo=str_replace("+"," ",urldecode($_GET['findthisaftertwo']));
 $deletedlabelfindstart=' href="';
 if (isset($_GET['deletedlabelfindstart'])) $deletedlabelfindstart=str_replace("+"," ",urldecode($_GET['deletedlabelfindstart']));
 $deletedlabelfindend='"';
 if (isset($_GET['deletedlabelfindend'])) $deletedlabelfindend=str_replace("+"," ",urldecode($_GET['deletedlabelfindend']));
 $addedlabelfindstart='<title arch="online">Note</title>';
 if (isset($_GET['addedlabelfindstart'])) $addedlabelfindstart=str_replace("+"," ",urldecode($_GET['addedlabelfindstart']));
 $addedlabelfindend='"';
 if (isset($_GET['addedlabelfindend'])) $addedlabelfindend=str_replace("+"," ",urldecode($_GET['addedlabelfindend']));
 $donotfindthisstart='<?';
 if (isset($_GET['donotfindthisstart'])) $donotfindthisstart=str_replace("+"," ",urldecode($_GET['donotfindthisstart']));
 $donotfindthisend='?>';
 if (isset($_GET['donotfindthisend'])) $donotfindthisend=str_replace("+"," ",urldecode($_GET['donotfindthisend']));

 $indexfilecalled="COMM.MIL~INDEX.xml";
 if (isset($_GET['index'])) $indexfilecalled=str_replace("+"," ",urldecode($_GET['index']));
 $csvname="mil_mapping.csv"; 
 if (isset($_GET['csvname'])) $csvname=str_replace("+"," ",urldecode($_GET['csvname']));
 $kshname="mil_mapping.ksh";
 if (isset($_GET['kshname'])) $kshname=str_replace("+"," ",urldecode($_GET['kshname']));
 $doksh=""; // "ksh -x mil_mapping.ksh";
 if (isset($_GET['doksh'])) $doksh=str_replace("+"," ",urldecode($_GET['doksh']));
 }
 }
 
 $uext=".XML";
 $lext=".xml";
 $ualt=".XXX";
 $lalt=".xxx";
 $extis=explode(".", $indexfilecalled);
 if (sizeof($extis) > 1) {
   $uext=strtoupper("." . $extis[-1 + sizeof($extis)]);
   $lext=strtolower("." . $extis[-1 + sizeof($extis)]);
   if ($lext == ".xxx") {
     $lalt=".xzz";
     $ualt=".XZZ";
   } else {
     $lalt=substr($lext,0,2) . "xx";
     $ualt=substr($uext,0,2) . "XX";
   }
 }


// </title><section role="annot_cont”
 //$findthis='role="annot_cont"';
 $sf1="<";
 $sf2="section";
 if ($startfind != "") {
   $sf1=substr($startfind,0,1);
   $sf2=explode(" ",substr($startfind,1))[0];
 }
 $dnft1="<title";
 $dnft2=" ";
 if ($addedlabelfindstart != "") {
   $dnft1=explode(" ",$addedlabelfindstart)[0];
   $dnft2=" ";
 }
 
 
 if ($ourargc >= 2 && (isset($_GET['filespec']) || $iscl)) {
 foreach (glob($filespec) as $filename) {
   $precont=@file_get_contents($filename);
   //file_put_contents($filename . ".001", $precont); 
   $thisresult=$precont;
   $cont=$precont;
   $first=true;
   $sections=explode($findthis, $cont);
   $rsections=explode($findthis, $thisresult);
   for ($ii=1; $ii<sizeof($sections); $ii++) { // Additional bits
     $i=$ii;
     // check that "<section " preceded
     if (explode(" ",explode($sf1, $sections[-1 + $i])[-1 + sizeof(explode($sf1, $sections[-1 + $i]))])[0] == $sf2) {
       // before that last end tag should be </title>
       if (explode($endfind,explode($sf1, str_replace($donotfindthisstart,"  ",str_replace($startfind,"        ",$sections[-1 + $i])))[-1 + sizeof(explode($sf1, str_replace($donotfindthisstart,"  ",str_replace($startfind,"        ",$sections[-1 + $i]))))])[0] == ("/" . substr($dnft1,1))) {
          // after that will be "<leg-history " ... or ...
          if ($findthisafter != "" && strpos($sections[$i], $findthisafter) !== false && strpos(explode($findthisafter, str_replace($donotfindthisstart,"        ",$section[$i]))[0], "<") === false) {
            // and in between will be no already done <title></title> or other type of tag actually
            if (strpos(explode($findthisafter, $section[$i])[0], $dnft1) === false && strpos(explode($findthisafter, $section[$i])[0], substr($findthisafter,0,1)) === false && strpos(explode($findthisafter, $section[$i])[0], "</" . $dnft1 . ">") === false) {
              $bits=explode($findthisafter, $sections[$i]);
              $rbits=explode($findthisafter, $rsections[$i]);
              if (sizeof($bits) > 1 && strpos(str_replace($donotfindthisstart,"        ",$bits[0]),"<") === false) {
                $newsectionone=str_replace($bits[0] . $findthisafter . $bits[1], $bits[0] . $addedlabelfindstart . $addedlabelfindend . $findthisafter . $bits[1], $sections[$i]);

                $newsectionr=str_replace($rbits[0] . $findthisafter . $rbits[1], $rbits[0] . "<font color=green>" . ($addedlabelfindstart . $addedlabelfindend) . "</font>" . $findthisafter . $rbits[1], $rsections[$i]);

                $cont=str_replace($findthis . $sections[$i], $findthis . $newsectionone, $cont);
                $sections=explode($findthis, $cont);
                $thisresult=str_replace($findthis . $rsections[$i], $findthis . $newsectionr, $thisresult);
                //if ($first && strpos($rsections[$i],$rbits[0] . $findthisafter . $rbits[1]) !== false) { echo " <b>findthisafter</b>=" . str_replace("<","&lt;",$findthisafter) . " <b>rbits[0]+</b>=" . str_replace(">","&gt;",str_replace("<","&lt;",$rbits[0] . $findthisafter)) . " <b>nEwSectionr</b>=" . str_replace(">","&gt;",str_replace("<","&lt;",$newsectionr)) . " <b>thisresult</b>=<div>" . str_replace("&lt;/strike&gt;","</strike>",str_replace("&lt;strike&gt;","<strike>",str_replace("&lt;/font&gt;","</font>",str_replace("&lt;font color=green&gt;","<font color=green>",str_replace(">","&gt;",str_replace("<","&lt;",str_replace($rbits[1],"",$thisresult))))))) . "</div>"; $first=false; }
                $rsections=explode($findthis, $thisresult);
              }
            }
            // after that will be "<history-note "
          } else if ($findthisaftertwo != "" && strpos($sections[$i], $findthisaftertwo) !== false && strpos(explode($findthisaftertwo, str_replace($donotfindthisstart,"        ",$section[$i]))[0], "<") === false) {
            // and in between will be no already done <title></title> or other type of tag actually
            if (strpos(explode($findthisaftertwo, $section[$i])[0], $dnft1) === false && strpos(explode($findthisaftertwo, $section[$i])[0], substr($findthisaftertwo,0,1)) === false && strpos(explode($findthisaftertwo, $section[$i])[0], "</" . $dnft1 . ">") === false) {
              $bits=explode($findthisaftertwo, $sections[$i]);
              $rbits=explode($findthisaftertwo, $rsections[$i]);
              if (sizeof($bits) > 1 && strpos(str_replace($donotfindthisstart,"        ",$bits[0]),"<") === false) {
                $newsectionone=str_replace($bits[0] . $findthisaftertwo . $bits[1], $bits[0] . $addedlabelfindstart . $addedlabelfindend . $findthisaftertwo . $bits[1], $sections[$i]);

                $newsectionr=str_replace($rbits[0] . $findthisaftertwo . $rbits[1], $rbits[0] . "<font color=green>" . ($addedlabelfindstart . $addedlabelfindend) . "</font>" . $findthisaftertwo . $rbits[1], $rsections[$i]);
                //if ($first) { echo " newSectionR=" . $newsectionr; $first=false; }

                $cont=str_replace($findthis . $sections[$i], $findthis . $newsectionone, $cont);
                $sections=explode($findthis, $cont);
                $thisresult=str_replace($findthis . $rsections[$i], $findthis . $newsectionr, $thisresult);
                $rsections=explode($findthis, $thisresult);
              }
            }
          }
       }
     }
   }
   //file_put_contents($filename . ".002", $cont); 
   $sections=explode($findthis, $cont);
   $rsections=explode($findthis, $thisresult);
   for ($ii=0; $ii<sizeof($sections); $ii++) { // Deletable bits
     $was=$sections[$ii];
     $is=$sections[$ii];
     $ris=$rsections[$ii];
     while (strpos($is, $deletedlabelfindstart) !== false) {
       $innards=explode($deletedlabelfindend,explode($deletedlabelfindstart, $is)[1])[0];
       $is=str_replace($deletedlabelfindstart . $innards . $deletedlabelfindend, "", $is);
       $ris=str_replace($deletedlabelfindstart . $innards . $deletedlabelfindend, "<strike>" . strtoupper($deletedlabelfindstart) . $innards . $deletedlabelfindend . "</strike>", $ris);
     }
     if ($was != $is) {
       $cont=str_replace($sections[$ii],$is,$cont); //$sections[$ii]=$ris;
       $thisresult=str_replace($rsections[$ii],str_replace(strtoupper($deletedlabelfindstart),$deletedlabelfindstart,$ris),$thisresult); //$rsections[$ii]=$ris;
     }
   }
   
   if ($cont != $precont) {
    //file_put_contents($filename . ".003", $cont); 
    //$uc=str_replace(">","&gt;",str_replace("<","&lt;",strtoupper($addedlabelfindstart . $addedlabelfindend)));
    $aresult=str_replace(">","&gt;",str_replace("<","&lt;",$thisresult));
    //$aresult=str_replace($uc,"<b>" . $addedlabelfindstart . $addedlabelfindend . "</b>",$aresult);
    $bresult=str_replace("&lt;/strike&gt;","</strike>",str_replace("&lt;strike&gt;","<strike style=color:red;>",str_replace("&lt;/font&gt;","</div>",str_replace("&lt;font color=green&gt;","<div style=display:inline;font-color:blue;background-color:yellow;>",$aresult))));
    $results.="<details><summary style='background-color:yellow;'>" . $filename . " changed ...</summary><div style='border:10px solid white;'>" . $bresult . "</div></details><br><br>";
    if (!file_exists($filename . "_original_backup")) copy($filename, $filename . "_original_backup");
    file_put_contents($filename, $cont); 
    $precont=$cont;
    $sections=[];
    $rsections=[];
   }
   
 }
 }
 
 if ($iscl || $iscurl) exit;
 ?>
 <!doctype html>
 <html>
 <head>
 <script type='text/javascript'>
 function curlit(via) {
   var plus='', delim='';
   var inps=document.getElementsByTagName('input');
   for (var jps=0; jps<inps.length; jps++) {
     if (('' + inps[jps].type).toLowerCase() == 'text') {
       plus+=delim + encodeURIComponent(inps[jps].value.replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
       delim=encodeURIComponent('``');
     }
   }
   //alert('' + via + decodeURIComponent(plus));
   if (1 == 2) {
   //alert(via + plus);
   window.open(('' + via + plus), '_blank');
   } else {
   document.getElementById('myiframe').style.display='block';
   document.getElementById('myiframe').src=('' + via + plus);
   }
   location.href='#myform';
 }
 </script>
 </head>
 <body onload=" document.getElementById('myform').action=document.URL.split('#')[0].split('?')[0]; " style="background-color:lightblue;">
 <h1>Adder Innerer of XML <i>&lt;title arch="online"&gt;Note&lt;/title&gt;</i></h1>
 <h2>Deleter of XML <i>href="hrefvalue"</i></h2>
 <h3>RJM Programming</h3>
 <h3>September, 2017</h3>
 <br>
 <div id='results'><?php echo $results; ?></div>
 <form style="width:80%;" id="myform" action="#" method="GET">
 XML file specification for input data: <input style="width:40%;" type="text" name="filespec" value="COMM.MIL*.xml"></input><br>
 Start delimitation of tags of interest: <input style="width:40%;" type="text" name="startfind" value='&lt;section '></input><br>
 Find this within: <input style="width:40%;" type="text" name="findthis" value='role="annot_cont"'></input><br>
 End delimitation of tags of interest: <input style="width:40%;" type="text" name="endfind" value=">"></input><br>
 Find this after 1 of 2: <input style="width:40%;" type="text" name="findthisafter" value='&lt;leg-history '></input><br>
 Find this after 2 of 2: <input style="width:40%;" type="text" name="findthisaftertwo" value='&lt;notes'></input><br>
 Deleted label regarding global substitutions start delimitation: <input style="width:40%;" type="text" name="deletedlabelfindstart" value=' href="'></input><br>
 Deleted label regarding global substitutions end delimitation: <input style="width:40%;" type="text" name="deletedlabelfindend" value='"'></input><br>
 New label regarding global substitutions start content prefix: <input style="width:40%;" type="text" name="addedlabelfindstart" value='<title arch="online">Note</title>'></input><br>
 New label regarding global substitutions end content suffix: <input style="width:40%;" type="text" name="addedlabelfindend" value=''></input><br>
 Ignore this start delimitation: <input style="width:40%;" type="text" name="donotfindthisstart" value='&lt;?'></input><br>
 Ignore this end delimitation: <input style="width:40%;" type="text" name="donotfindthisend" value='?&gt;'></input><br>
 <input type="submit" value="Run this Job Here"></input>&nbsp;&nbsp;<input onclick="curlit(document.URL.split('#')[0].split('?')[0] + '?curl=y&filespec=');" type="button" value="Run this Job With Curl"></input>&nbsp;&nbsp;<input onclick="curlit(document.URL.split('#')[0].split('?')[0] + '?php=y&filespec=');" type="button" value="Run this Job With Command Line PHP"></input>
 </form>
 <iframe id='myiframe' name='iframe' src='' style='background-color:orange;overflow:wrap;display:none;width:100%;height:100px;'></iframe>
 </body>
 </html>
 
