<?php
// macos_textutil_convert.php
// Supervise macOS (via PHP exec) textutil (command line) conversions
/* 
textutil: [command_option] [other_options] file...
Command options are (-help is the default):
 -help          show this message and exit
 -info          display information about each file
 -convert fmt   convert each input file to format (txt, rtf, rtfd,
                html, doc, docx, odt, wordml, or webarchive)
 -cat fmt       concatenate input files into one output file
There are some additional optional arguments:
 -extension ext alternate extension for all output files
 -output path   alternate file name for first output file
 -stdin         read from stdin instead of files
 -stdout        send first output file to stdout
 -encoding IANA_name|NSStringEncoding
                encoding used for plain text or html output files
                (default encoding is UTF-8)
 -inputencoding IANA_name|NSStringEncoding
                encoding used to interpret plain text input files
                (by default encoding will be detected from BOM)
 -format fmt    force input files to be interpreted in this format
 -font font     specify font used for converting plain to rich text
 -fontsize size specify font size for converting plain to rich text
 --             specifies that all further arguments are file names

 -noload        do not load subsidiary resources for html files
 -nostore       do not write out subsidiary resources for html files
 -baseurl url   base URL for subsidiary resources in html files
 -timeout t     time in seconds to wait for html resources to load
 -textsizemultiplier x
                factor to apply to font sizes in html files
 -excludedelements "(tag1, tag2, ...)"
                html elements to exclude from html output files
 -prefixspaces n
                number of spaces to indent nested html output

 -strip         do not copy metadata attributes to output files
 -title val     title metadata attribute for output files
 -author val    author metadata attribute for output files
 -subject val   subject metadata attribute for output files
 -keywords "(val1, val2, ...)"
                keywords metadata attribute for output files
 -comment val   comment metadata attribute for output files
 -editor val    last editor metadata attribute for output files
 -company val   company metadata attribute for output files
 -creationtime yyyy-mm-ddThh:mm:ssZ
                creation time metadata attribute for output files
 -modificationtime yyyy-mm-ddThh:mm:ssZ
                modification time metadata attribute for output files
*/

$thecontent="";
$tastuff="";
$doutput="";
$outfileis="";
$sufext="_0";
$iext=0;

if (PHP_OS == "Darwin") {
if (isset($_GET['convertthis']) && isset($_GET['outputname'])) {
  if ($_GET['convertthis'] != "") {
  $thewords=str_replace("+"," ",urldecode($_GET['convertthis']));
  if (file_exists(str_replace("+"," ",urldecode($_GET['outputname'])))) {
    while (file_exists(str_replace("+"," ",urldecode($_GET['outputname'])) . $sufext)) {
      $iext++;
      $sufext="_" . $iext;
    }
    exec("rename " . str_replace("+"," ",urldecode($_GET['outputname'])) . " " . str_replace("+"," ",urldecode($_GET['outputname'])) . $sufext);
  }
  exec("textutil -convert " . explode(".",str_replace("+"," ",urldecode($_GET['outputname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_GET['outputname']))))] . " " . $thewords . " -output " . str_replace("+"," ",urldecode($_GET['outputname'])) . " > x.out 2> x.err");
  exit;
  }
} else if (isset($_POST['convertthis']) && isset($_POST['outputname'])) {
  if ($_POST['convertthis'] != "") {
  $thewords=str_replace("+"," ",urldecode($_POST['convertthis']));
  if (file_exists(str_replace("+"," ",urldecode($_POST['outputname'])))) {
    while (file_exists(str_replace("+"," ",urldecode($_POST['outputname'])) . $sufext)) {
      $iext++;
      $sufext="_" . $iext;
    }
    exec("rename " . str_replace("+"," ",urldecode($_POST['outputname'])) . " " . str_replace("+"," ",urldecode($_POST['outputname'])) . $sufext);
  }
  exec("textutil -convert " . explode(".",str_replace("+"," ",urldecode($_POST['outputname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_POST['outputname']))))] . " " . $thewords . " -output " . str_replace("+"," ",urldecode($_POST['outputname'])) . " > x.out 2> x.err");
  exit;
  }
} else if ((!isset($_GET['convertthis']) && !isset($_POST['convertthis'])) || !isset($_GET['outputname']) || !isset($_POST['outputname'])) {
  $outfileis="";
  if (isset($_GET['outputname'])) {
    $extis=explode(".",str_replace("+"," ",urldecode($_GET['outputname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_GET['outputname']))))];
    if (file_exists(str_replace("+"," ",urldecode($_GET['outputname'])))) {
    if (strtolower("~" . $extis, "~htm") !== false) {
    $thecontent=file_get_contents(str_replace("+"," ",urldecode($_GET['outputname'])));
    } else {
    header('Content-type: application/' . explode(".",str_replace("+"," ",urldecode($_GET['outputname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_GET['outputname']))))]); 
    echo file_get_contents(str_replace("+"," ",urldecode($_GET['outputname'])));
    exit;
    }
    }
  } else if (isset($_POST['outputname'])) {  
    $extis=explode(".",str_replace("+"," ",urldecode($_POST['outputname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_POST['outputname']))))];
    if (file_exists(str_replace("+"," ",urldecode($_POST['outputname'])))) {
    if (strtolower("~" . $extis, "~htm") !== false) {
    $thecontent=file_get_contents(str_replace("+"," ",urldecode($_POST['outputname'])));
    } else {
    header('Content-type: application/' . explode(".",str_replace("+"," ",urldecode($_POST['outputname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_POST['outputname']))))]); 
    echo file_get_contents(str_replace("+"," ",urldecode($_POST['outputname'])));
    exit;
    }
    }
  }
  echo "<html>
<head>
<script type='text/javascript'>
  var wasv='';
  var firstgo=true;

  function thenreload() {
    location.href=document.URL.split('?')[0].split('#')[0] + '?outputname=' + encodeURIComponent(document.getElementById('outputname').value) + '&dummyconvertthis=' + encodeURIComponent(document.getElementById('thewords').value);
  }
  
  function resultchange() {
    if (document.getElementById('result').value == '') {
    setTimeout(resultchange, 2000);
    } else if (firstgo) {
    firstgo=false;
    setTimeout(resultchange, 6000);
    } else if (window.opener) {
    window.opener.document.getElementById('aurl').value=document.getElementById('result').value;
    window.opener.document.getElementById('doutput').innerHTML='" . $doutput . "'; 
    window.opener.atab(window.opener.document.getElementById('aurl'));
    }
  }
</script>
</head>
<body onload='resultchange();'>
<h1>Supervise textutil</h1>
<h3>RJM Programming - July, 2020</h3>
" . $outfileis . "
<form id=myform onsubmit=\"document.getElementById('myform').style.cursor='progress'; document.body.style.cursor='progress'; setTimeout(thenreload,20000); return true;\" target=dothework action=./macos_textutil_convert.php method=POST>
<table border=20>
<tr><th>Input Document File</th><th>Convert to <input placeholder='Output document file' type=text name=outputname id=outputname value=''></input></th></tr>
<tr><td style=vertical-align:top;><input placeholder='Input document file' id=thewords name=convertthis  value=''></input></td><td style=vertical-align:top;><input style='width:100%;height:100px;background-color:yellow;' type=submit value='Convert This Document'></input><br><div id=result>" . $thecontent . "</textarea></td></tr>
</table>
</form>
<iframe name=dothework id=dothework style=display:none; src=macos_textutil_convert.php></iframe>
</body>
</html>";
} 
} else {
 echo "<html><body><p>This PHP web application only works with macOS and its textutil -convert [outextension] [infilename] -output [outfilename] command line Document Conversion functionality.</p></body><html>";
 exit;
}
?>
