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

$ovr="";

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

function server_remote_addr_txt() {
    global $ovr;
    $rma = $_SERVER['REMOTE_ADDR'];
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    // you can add different browsers with the same way ..
    if(preg_match('/(chromium)[ \/]([\w.]+)/', $ua))
            $rma = '000000'.$rma;
    elseif(preg_match('/(chrome)[ \/]([\w.]+)/', $ua))
            $rma = '00000'.$rma;
    elseif(preg_match('/(safari)[ \/]([\w.]+)/', $ua))
            $rma = '0000'.$rma;
    elseif(preg_match('/(opera)[ \/]([\w.]+)/', $ua))
            $rma = '000'.$rma;
    elseif(preg_match('/(msie)[ \/]([\w.]+)/', $ua))
            $rma = '00'.$rma;
    elseif(preg_match('/(mozilla)[ \/]([\w.]+)/', $ua))
            $rma = '0'.$rma;
    if ($ovr != "") return $ovr . ".txt";
    return str_replace("=1","",str_replace("0","",str_replace(":","",str_replace("-","",("56" . $rma))))) . ".txt";
}

$aemailtitle=server_remote_addr_txt(); //"000";
$zds='/';
if (strpos(dirname(__FILE__), $zds) === false) $zds=substr("\\",0,1);
$urlprefix=str_replace("mil_mapping.php","","http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0]);
$lofprefix=dirname(__FILE__) . $zds;
$defplace="./*.*_GETME";
$defreadonly=" readonly";
$defplace="./*.*";
$defreadonly="";
$acom="";
$iscl=false;
$ourargc=2;
$iscurl=false;
$kshname="mil_mapping.sh"; //ksh";
if (isset($_GET['delete'])) {  // Delete an execution report
 if (strpos(($_SERVER['HTTP_REFERER'] . '?'), 'mil_mapping.php?') !== false) {
   $vds='/';
   if (strpos(dirname(__FILE__), $vds) === false) $vds=substr("\\",0,1);
   if (strpos(urldecode($_GET['delete']), $vds) === false) {
     if (file_exists(dirname(__FILE__) . $vds . urldecode($_GET['delete']))) {
       unlink(dirname(__FILE__) . $vds . urldecode($_GET['delete']));
     }
   } else {
     if (file_exists(urldecode($_GET['delete']))) {
       unlink(urldecode($_GET['delete']));
     }
   }
 }
 exit;
} else if (isset($_GET['runthis'])) {  // Get told to rerun a script
 if (strpos(($_SERVER['HTTP_REFERER'] . '?'), 'mil_mapping.php?') !== false) {
  echo "<!doctype html><html><body><div style='font-size:12px;overflow:wrap;width:100%;'>Performing " . urldecode($_GET['runthis']) . " ... <br> " . str_replace("\n","<br>",file_get_contents(urldecode($_GET['runthis']))) . "</div></body></html>"; 
  if (strpos(urldecode($_GET['runthis']),'#!') !== false) {
    $idea=-1;
    if (strpos(urldecode($_GET['runthis']),"\n" . "exit") !== false) {
     $ur=explode("\n" . "exit",file_get_contents(urldecode($_GET['runthis'])))[0];
     if (explode("\n",$ur)[$idea + sizeof(explode("\n",$ur))] == "") $idea--;
     exec(explode("\n",$ur)[$idea + sizeof(explode("\n",$ur))]); 
    } else {
     $idea=-1;
     $ur=explode("\n",file_get_contents(urldecode($_GET['runthis'])))[$idea + sizeof(explode("\n",file_get_contents(urldecode($_GET['runthis']))))];
     if ($ur == "") {
       $idea--;
       $ur=explode("\n",file_get_contents(urldecode($_GET['runthis'])))[$idea + sizeof(explode("\n",file_get_contents(urldecode($_GET['runthis']))))];
       exec($ur); 
     } else {
       exec($ur); 
     }
    }
  } else {
    exec(file_get_contents(urldecode($_GET['runthis']))); 
  }
 }
 exit;
} else 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='?>';
 $notifyemail='fill.in@email.here';
 $kshname="mil_mapping.sh"; //ksh";
 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]);
 if ($argc >= 14) $notifyemail=yoururldecode($argv[13]);
 if ($argc >= 15) $kshname=yoururldecode($argv[14]);
 if ($argc >= 16) $ovr=yoururldecode($argv[15]);
 $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];
 $notifyemail=explode("``", $bigstr)[12];
 $kshname=explode("``", $bigstr)[13];
 $ovr=str_replace(".txt","",server_remote_addr_txt());
 if (sizeof(explode("``", $bigstr)) >= 15) $ovr=explode("``", $bigstr)[14];
 $sprefix="";
 $amailto="";
 $ds='/';
 if (strpos(dirname(__FILE__), $ds) === false) $ds=substr("\\",0,1);
 if (strpos(str_replace("fill.in@email.here", "", $notifyemail), "@") !== false) {
    $amailto=" parent.document.getElementById('aemail').href='mailto:" . $notifyemail . "?subject=Performed%20" . str_replace("+","%20",urlencode(PHP_OS) . " command line") . "%20&body='; parent.document.getElementById('aemail').click(); ";
 } 
 if (isset($_GET['php'])) {
   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'])))); 
   if (strpos($kshname, ".bat") === false) {
     $sprefix="#!/bin/" . explode(".", $kshname)[-1 + sizeof(explode(".", $kshname))] . "\n";
   }
   if (strpos($ds, $kshname) === false) {
     file_put_contents(dirname(__FILE__) . $ds . $kshname, $sprefix . "php " . dirname(__FILE__) . $ds . 'mil_mapping.php ' . str_replace("%60%60"," ",str_replace("%60%60%60%60"," %60 ",urlencode($_GET['filespec']))));
     if ($amailto != "") $amailto=str_replace("&body=", urlencode(dirname(__FILE__) . $ds . $kshname) . "&body=" . str_replace('+','%20',urlencode(file_get_contents(dirname(__FILE__) . $ds . $kshname, $sprefix))),$amailto);
     echo "<!doctype html><html><body onload=\" if (parent.document.getElementById('lookoutfor')) { parent.document.getElementById('lookoutfor').value='" . $urlprefix . $ovr . ".txt'; }   if (parent.document.getElementById('oldf')) { parent.document.getElementById('oldf').innerHTML='" . str_replace("\n","<br>",file_get_contents(dirname(__FILE__) . $ds . $kshname)) . "'; " . $amailto . " }\"></body></html>"; 
   } else {
     file_put_contents($kshname, $sprefix . "php " . dirname(__FILE__) . $ds . 'mil_mapping.php ' . str_replace("%60%60"," ",str_replace("%60%60%60%60"," %60 ",urlencode($_GET['filespec']))));
     if ($amailto != "") $amailto=str_replace("&body=", urlencode($kshname) . "&body=" . str_replace('+','%20',urlencode(file_get_contents($kshname, $sprefix))),$amailto);
     echo "<!doctype html><html><body onload=\" if (parent.document.getElementById('lookoutfor')) { parent.document.getElementById('lookoutfor').value='" . $urlprefix . $ovr . ".txt'; }  if (parent.document.getElementById('oldf')) { parent.document.getElementById('oldf').innerHTML='" . str_replace("\n","<br>",file_get_contents($kshname)) . "'; " . $amailto . " }\"></html>"; 
   }
   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'])); 
   if (strpos($kshname, ".bat") === false) {
     $sprefix="#!/bin/" . explode(".", $kshname)[-1 + sizeof(explode(".", $kshname))] . "\n";
   }
   if (strpos($ds, $kshname) === false) {
     file_put_contents(dirname(__FILE__) . $ds . $kshname, $sprefix . "curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?filespec=' . urlencode($_GET['filespec']));
     if ($amailto != "") $amailto=str_replace("&body=", urlencode(dirname(__FILE__) . $ds . $kshname) . "&body=" . str_replace('+','%20',urlencode(file_get_contents(dirname(__FILE__) . $ds . $kshname, $sprefix))),$amailto);
     echo "<!doctype html><html><body onload=\" if (parent.document.getElementById('lookoutfor')) { parent.document.getElementById('lookoutfor').value='" . $urlprefix . $ovr . ".txt'; }  if (parent.document.getElementById('oldf')) { parent.document.getElementById('oldf').innerHTML='" . str_replace("\n","<br>",file_get_contents(dirname(__FILE__) . $ds . $kshname)) . "'; " . $amailto . " }\"></body></html>"; 
   } else {
     file_put_contents($kshname, $sprefix . "curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?filespec=' . urlencode($_GET['filespec']));
     if ($amailto != "") $amailto=str_replace("&body=", urlencode($kshname) . "&body=" . str_replace('+','%20',urlencode(file_get_contents($kshname, $sprefix))),$amailto);
     echo "<!doctype html><html><body onload=\" if (parent.document.getElementById('lookoutfor')) { parent.document.getElementById('lookoutfor').value='" . $urlprefix . $ovr . ".txt'; }  if (parent.document.getElementById('oldf')) { parent.document.getElementById('oldf').innerHTML='" . str_replace("\n","<br>",file_get_contents($kshname)) . "'; " . $amailto . " }\"></body></html>"; 
   }
   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='?>';
 $notifyemail='fill.in@email.here';
 $kshname="mil_mapping.sh"; //ksh";
 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];
 if (strpos($bigstr, "notifyemail`") !== false) $notifyemail=explode("`",explode("notifyemail`", $bigstr)[1])[0];
 if (strpos($bigstr, "kshname`") !== false) $kshname=explode("`",explode("kshname`", $bigstr)[1])[0];
 if (strpos($bigstr, "ovr`") !== false) $ovr=explode("`",explode("ovr`", $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']));
 $notifyemail='fill.in@email.here';
 if (isset($_GET['notifyemail'])) $notifyemail=str_replace("+"," ",urldecode($_GET['notifyemail']));
 $kshname="mil_mapping.sh"; //ksh";
 if (isset($_GET['kshname'])) $kshname=str_replace("+"," ",urldecode($_GET['kshname']));

 $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']));
 $doksh=""; // "ksh -x mil_mapping.sh" ; //ksh";
 if (isset($_GET['doksh'])) $doksh=str_replace("+"," ",urldecode($_GET['doksh']));
 }
 }

 $ods='/';
 if (strpos(dirname(__FILE__), $ods) === false) $ods=substr("\\",0,1);
 $proposedksh=$kshname;
 if (!file_exists($proposedksh) && strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && strpos($proposedksh, '.bat') === false) {
   $exts=explode('.',$kshname);
   $prefixis=str_replace('`','',str_replace($exts[-1 + sizeof($exts)] . '`','',str_replace('.' . $exts[-1 + sizeof($exts)] . '`','',($kshname . '`'))));  
   $proposedksh=$prefixis . '.bat';
   $kshname=$proposedksh;
 } else if (strpos($proposedksh, $ods) === false && !file_exists($proposedksh)) {
   $exts=explode('.',$kshname);
   $prefixis=str_replace('`','',str_replace($exts[-1 + sizeof($exts)] . '`','',str_replace('.' . $exts[-1 + sizeof($exts)] . '`','',($kshname . '`'))));  
   $proposedksh=$prefixis . '.sh';
   $kshname=$proposedksh;
 } 
 if (file_exists($proposedksh)) {
   if (strpos($ods, $proposedksh) === false) $proposedksh=dirname(__FILE__) . $ods . $kshname;
 }
 
 
 $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) {
   if ($results != '' && $ourargc >= 2 && (isset($_GET['filespec']) || $iscl)) {
     file_put_contents($lofprefix . $ovr . ".txt", $results);
   } else {
     file_put_contents($lofprefix . $ovr . ".txt", '&nbsp;');
   }
   exit;
 }
 ?>
 <!doctype html>
 <html>
 <head>
 <meta charset="utf-8">
 <script type='text/javascript'>
 
 var report_data="", huhis="", lastis="";
 
 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('``');
     }
   }
   plus+=delim + encodeURIComponent('<?php echo str_replace(".txt","",server_remote_addr_txt()); ?>');
   document.getElementById('aemail').innerHTML='&nbsp;';
   document.getElementById('results').innerHTML='';
   //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';
 }
 
 function onl() {
    document.getElementById('myform').action=document.URL.split('#')[0].split('?')[0];
    var exts=document.getElementById('kshname').value.split('.');
    var prefixis=(document.getElementById('kshname').value + '`').replace('.' + exts[eval(-1 + exts.length)] + '`','').replace(exts[eval(-1 + exts.length)] + '`','').replace('`','');
    if (prefixis == '') prefixis='mil_mapping';
    var osis='<?php echo PHP_OS; ?>';
    if (osis.toUpperCase().substring(0,3) == 'WIN') {
      document.getElementById('kshname').value=prefixis + '.bat';
    } else {
      document.getElementById('kshname').value=prefixis + '.sh';
    }
    document.getElementById('arerun').href+=encodeURIComponent(document.getElementById('kshname').value);
    <?php  
      if (file_exists($proposedksh)) {
        echo "\n" . " document.getElementById('reveal').style.display='inline'; document.getElementById('arerun').innerHTML='Optionally rerun ' + document.getElementById('kshname').value + ' which you can review ahead of the click'; document.getElementById('oldf').innerHTML='" . str_replace("\n","<br>",file_get_contents($proposedksh)) . "'; " . "\n";
      }
    ?>
    beonlookoutfor();
 }
 
 function check_for_reports(iois) {
  if (iois != null) {
    var aconto = (iois.contentWindow || iois.contentDocument);
    if (aconto != null) {
     if (aconto.document) { aconto = aconto.document; }
     if (aconto.body != null && report_data == "") {
       if (aconto.body.innerHTML != "") {
        if (aconto.body.innerHTML.indexOf("nbsp;</pre>") == -1) {
         report_data=aconto.body.innerHTML.replace(/&lt;/g,"<").replace(/&gt;/g,">");
         document.getElementById('results').innerHTML=report_data;
        }
        if (document.getElementById('lookoutfor').value == '' || !document.getElementById('lookoutfor')) {
           document.getElementById('deliframe').src='./mil_mapping.php?delete=' + encodeURIComponent('<?php echo $lofprefix . server_remote_addr_txt(); ?>');
        } else {
           document.getElementById('deliframe').src='./mil_mapping.php?delete=' + encodeURIComponent(document.getElementById('lookoutfor').value);
        }
        document.getElementById('aemail').innerHTML='Finished';
        document.getElementById('lookoutfor').value='';
        report_data="";
       }
     }
    }
  }
 }
 
 function beonlookoutfor() {
  var huhis=document.getElementById('lookoutfor').value;
  if (huhis != '' && huhis != lastis) {
    if (1 == 1) {
//alert(document.getElementById('lookoutfor').value);
      document.getElementById('lookoutfor').value=document.getElementById('lookoutfor').value.replace('<?php echo $urlprefix; ?>','<?php echo $lofprefix; ?>');
//alert(document.getElementById('lookoutfor').value);
      document.getElementById('checkiframe').src=huhis;
      huhis=document.getElementById('lookoutfor').value;
      lastis=document.getElementById('lookoutfor').value;
//alert(lastis);
    } else {
      document.getElementById('lookoutfor').value='';
      document.getElementById('checkiframe').src=huhis;
    }
  }
  setTimeout(beonlookoutfor, 5000);
 }

 </script>
 </head>
 <body onload=" onl(); " 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 - September, 2017</h3>
 <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>
 Notification Email: <input style="width:40%;" type="text" name="notifyemail" value='fill.in@email.here'></input><br>
 Curl and Command Line Rerunner: <input style="width:40%;" type="text" id="kshname" name="kshname" value='mil_mapping.sh'></input><div id='reveal' style='display:none;'><details><summary style='background-color:yellow;'> ... <a target='myiframe' style='background-color:lightgray;' onclick="  document.getElementById('myiframe').style.display='block'; location.href='#myform';  " title='Optional rerun of last command line script saved ... reviewable to the left ahead of clicking' id='arerun' href='./mil_mapping.php?runthis='></a> ...</summary><div id='oldf' style='font-size:12px;border:10px solid white;'></div></div><br>
 <input type="submit" value="Run this Job Here"></input>&nbsp;&nbsp;<input onclick="curlit(document.URL.split('#')[0].split('?')[0] + '?curl=<?php echo str_replace(".txt","",server_remote_addr_txt()); ?>&filespec=');" type="button" value="Run this Job With Curl"></input>&nbsp;&nbsp;<input onclick="curlit(document.URL.split('#')[0].split('?')[0] + '?php=<?php echo str_replace(".txt","",server_remote_addr_txt()); ?>&filespec=');" type="button" value="Run this Job With Command Line PHP"></input>
 </form>
 <iframe id='myiframe' name='myiframe' src='' style='background-color:orange;overflow:wrap;display:none;width:100%;height:75px;'></iframe>
 <a id='aemail' href='mailto:?subject=&body=' style='text-decoration:none;'>&nbsp;</a>
 <input type='hidden' id='lookoutfor' value=''></input>
 <iframe style='display:none;' id='checkiframe' name='checkiframe' onload=' check_for_reports(this); ' onerror=" report_data=''; "  src=''></iframe>
 <iframe style='display:none;' id='deliframe' name='deliframe' src=''></iframe>
 </body>
 </html>
 
