#!/usr/bin/php
<?php

// reads all files in the current directory that have
// the ending .php and creates corresponding HTML
// files that with the ending .html
// mysql_connect has password stripped for security
// reasons


$top='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<head><title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
</head><body><div><pre>';

$bottom='</pre></div><p>
<a href="http://validator.w3.org/check?uri=referer"><img
    style="border: 0pt"
    src="/valid-xhtml10.png"
    alt="Valid XHTML 1.0!" height="31" width="88" /></a>
</p></body></html>';

function document_file($file) {
  $php=file_get_contents($file);
  // ouch! php seems to use iso-8859-1 internally
  $php=utf8_decode($php);
  $top=$GLOBALS['top'];
  $bottom=$GLOBALS['bottom'];
  // make entities. the standard htmlentities($php) makes entities
  // for non-ascii chars, I did not like that. The order in the
  // substitutions does matter.
  $r=array('-&-','-<-','->-',);
  $s=array('&amp;','&lt;','&gt;',);
  $php=preg_replace($r,$s,$php);
  // remove password in mysql_connect 
  $r="/mysql_connect\( *('[^']+') *, *('[^']+') *, *('[^']+') *\)/";
  $s="mysql_connect($1,$2,'')";
  $php=preg_replace($r,$s,$php);
  // remove password in mysqli_connect 
  $r="/mysqli_connect\( *('[^']+') *, *('[^']+') *, *('[^']+') *\)/";
  $s="mysqli_connect($1,$2,'')";
  $php=preg_replace($r,$s,$php);
  // add a proper <title>
  $r="-<title></title>-";
  $s="<title>documentation for script $file</title>";
  $top=preg_replace($r,$s,$top);
  // final composition
  $doc="$top\n$php\n$bottom\n";
  $doc=utf8_encode($doc);
  $out_file="$file.html";
  $fp=fopen($out_file,'w');
  fwrite($fp,$doc);
}


// do not run on the web
if(isset($_SERVER["SERVER_NAME"])) {
  print $top."</pre><div>This script is not effective on the web.";
  print "</div><pre>".$bottom;
  exit;
}

$dir=opendir(".");
while ($file = readdir($dir)) { 
  if(preg_match('/.php$/',$file) or preg_match('/.js$/',$file) ) {
    document_file($file);
  }
}
?>

Valid XHTML 1.0!