#!/usr/bin/php5 # Visit http://www.carlissongaldino.com.br/ # It needs: php5-cli, php-xml-parser, DataURI */ require("DataUri.php"); if (defined('STDIN')) { for ($i = 1; $i < sizeof($argv); $i++) { $f = $argv[$i]; if (file_exists($f)) { print "I will transform $f.\n"; unify($f); } else { print "File $f don't exists.\n"; } } } function unify($f) { $fpath = dirname(realpath($f)); $dom = new DomDocument(); $dom->loadHTML(file_get_contents($f)); $dom->preserveWhiteSpace = false; $images = $dom->getElementsByTagName('img'); foreach ($images as $img) { $imgfile = $img->getAttribute('src'); if (preg_match("/^http(s?):/i", $imgfile)) { $img->setAttribute('src', image_to_html($imgfile)); } elseif (preg_match("/^file:/", $imgfile)) { $rimgfile = preg_replace('/^file:(\/+)/', '/', $imgfile); $img->setAttribute('src', image_to_html($rimgfile)); } else { $rimgfile = "$fpath/$imgfile"; $img->setAttribute('src', image_to_html($rimgfile)); } } $f2 = $fpath . "/" . basename($f, ".html") . "-u.html"; $dom->save($f2); #fix_doctype($f2); } function image_to_html($imagefile) { if (preg_match("/.jp(e?)g$/i", $imagefile)) { $filetype = "image/jpg"; } elseif (preg_match("/.png$/i", $imagefile)) { $filetype = "image/png"; } else { return $imagefile; } $fileContents = file_get_contents($imagefile); if($fileContents != false) { $dataUri = new DataUri( $filetype, $fileContents, DataUri::ENCODING_BASE64 ); return $dataUri->toString(); } } function fix_doctype($f) { $af = file($f); print "fix\n"; $sf = "\n" . ""; foreach ($af as $s) { if (preg_match("/^\<\?xml/i", $s)) { print "achei xml\n"; } elseif (preg_match("/^\<\!DOCTYPE/i", $s)) { print "achei doctype\n"; } else { $sf .= "\n$s"; } } file_put_contents($f, $sf); } ?>