<?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);
}

 $results="";
 $csvout="";
 $kshout="#!/bin/ksh\n";
 $delim="";
 
 $filespec="COMM.MIL*.xml";
 if (isset($_GET['filespec'])) $filespec=str_replace("+"," ",urldecode($_GET['filespec']));
 $indexfilecalled="COMM.MIL~INDEX.xml";
 if (isset($_GET['index'])) $indexfilecalled=str_replace("+"," ",urldecode($_GET['index']));
 $startfind="<section ";
 if (isset($_GET['startfind'])) $startfind=str_replace("+"," ",urldecode($_GET['startfind']));
 $endfind=">";
 if (isset($_GET['endfind'])) $endfind=str_replace("+"," ",urldecode($_GET['endfind']));
 $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']));
 $findthis='role="annot_cont"';
 if (isset($_GET['findthis'])) $findthis=str_replace("+"," ",urldecode($_GET['findthis']));
 $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']));
 $donotfindthisstart='<?';
 if (isset($_GET['donotfindthisstart'])) $donotfindthisstart=str_replace("+"," ",urldecode($_GET['donotfindthisstart']));
 $donotfindthisend='?>';
 if (isset($_GET['donotfindthisend'])) $donotfindthisend=str_replace("+"," ",urldecode($_GET['donotfindthisend']));
 $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 (isset($_GET['filespec'])) {
 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=[];
   }
   
 }
 }
 
 ?>
 <!doctype html>
 <html>
 <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"></input>
 </form>
 </body>
 </html>
 
