<?php function OptimizeTest(){$exts="jpg jpeg png gif";$files=array();foreach(explode(" ",$exts)as$ext){$f=glob(DIR_SYSTEM."lightning/*.".$ext);if($f)$files=array_merge($f,$files);}
$factory=new OptimizerFactory();$optimizer=$factory->get();foreach($files as$file){$name=substr($file,strrpos($file,'/')+1);file_put_contents(DIR_CACHE.$name,file_get_contents($file));$optimizer->optimize(DIR_CACHE.$name);$org_size=filesize($file);$opt_size=filesize(DIR_CACHE.$name);if($opt_size<$org_size)echo"$name optimized ".round((1-$opt_size/$org_size)*100)."%<br><br>";else echo"$name not optimized<br><br>";}
exit;}
function Check_Optimizers(){header("Content-Type: text/html; charset=utf-8");echo"<body style='font-family: \"Open Sans\", sans-serif;'>";echo"<div style='font-size:20px; padding: 30px'>";$bad=false;if(!function_exists("exec")or(@exec('echo EXEC')!='EXEC')){echo('<font color="red"><b>PHP exec() function is not allowed</b></font> at your server.<br/>');$bad=true;}else if(!function_exists('escapeshellcmd')or(@escapeshellcmd("test")!="test")){echo('<font color="red"><b>PHP escapeshellcmd() function is not allowed</b></font> at your server.<br/>');$bad=true;}
if(!function_exists('escapeshellarg')or(@escapeshellarg("test")!="'test'")){echo('<font color="red"><b>PHP escapeshellarg() function is not allowed</b></font> at your server.<br/>');$bad=true;}
if($bad)die('<br/>Try to contact your hosters, but take a note that they may not allow you to use it at most shared hostings.');$factory=new OptimizerFactory();$optimizer=$factory->get();global$util_found;$util_found=false;$optimizer->optimize('test.png');$png=$util_found;$util_found=false;$optimizer->optimize('test.jpg');$jpg=$util_found;$util_found=false;$optimizer->optimize('test.gif');$gif=$util_found;if($png and$jpg)die('<font color="green"><b>Your server is ready for images optimization!</b></font><br/> Everything is good, you may enable Lightning images optimization.');if(!$png)echo('<font color="red"><b>No PNG optimization utilities found</b></font> at your server.<br/><br/> Install <b>optipng</b> utility. You may use console command: <br/><font color="blue"><b>sudo apt-get install optipng</b></font><br/><br/><br/>');if(!$jpg)echo('<font color="red"><b>No JPEG optimization utilities found</b></font> at your server.<br/><br/> Install <b>jpegoptim</b> utility. You may use console command: <br/><font color="blue"><b>sudo apt-get install jpegoptim</b></font>');exit;}
function optimizers_ready(){if(!function_exists("exec")or(@exec('echo EXEC')!='EXEC'))return 0;if(!function_exists('escapeshellcmd')or(@escapeshellcmd("test")!="test"))return 0;if(!function_exists('escapeshellarg')or(@escapeshellarg("test")!="'test'"))return 0;$factory=new OptimizerFactory();$optimizer=$factory->get();global$util_found;$util_found=false;$optimizer->optimize('test.png');if(!$util_found)return 0;$util_found=false;$optimizer->optimize('test.jpg');if(!$util_found)return 0;return true;}
function o_f1($filepath){$ext=pathinfo($filepath,PATHINFO_EXTENSION);return array('--ext='.($ext ?'.'.$ext :''),'--');}
function o_f3($filepath){return array('-outfile',$filepath);}
function o_f2(){global$o_ef,$o_n;return$o_ef->find($o_n,$o_n);}
class OptimizerFactory {public$optimizers=array();private$options;private$executableFinder;private$logger;public function __construct(array$options=array()){$this->executableFinder=new MX_ExecutableFinder();$this->setOptions($options);$this->setUpOptimizers();}
private function setOptions(array$options){$this->options=array_merge(array('ignore_errors'=>true,'optipng_options'=>array('-i0','-o2','-quiet'),'pngquant_options'=>array('--force'),'pngcrush_options'=>array('-reduce','-q','-ow'),'pngout_options'=>array('-s3','-q','-y'),'gifsicle_options'=>array('-b','-O5'),'jpegoptim_options'=>array('--strip-all','-m85'),'jpegtran_options'=>array('-copy none','-optimize','-progressive'),'advpng_options'=>array('-z','-4','-q')),$options);}
protected function setUpOptimizers(){$this->optimizers['optipng']=$this->wrap(new CommandOptimizer(new Command($this->executable('optipng'),$this->options['optipng_options'])));$this->optimizers['pngquant']=$this->wrap(new CommandOptimizer(new Command($this->executable('pngquant'),$this->options['pngquant_options']),'o_f1'));$this->optimizers['pngcrush']=$this->wrap(new CommandOptimizer(new Command($this->executable('pngcrush'),$this->options['pngcrush_options'])));$this->optimizers['pngout']=$this->wrap(new CommandOptimizer(new Command($this->executable('pngout'),$this->options['pngout_options'])));$this->optimizers['advpng']=$this->wrap(new CommandOptimizer(new Command($this->executable('advpng'),$this->options['advpng_options'])));$this->optimizers['png']=new ChainOptimizer(array($this->optimizers['optipng'],$this->optimizers['pngquant'],$this->optimizers['pngcrush'],$this->optimizers['advpng']));$this->optimizers['gif']=$this->optimizers['gifsicle']=$this->wrap(new CommandOptimizer(new Command($this->executable('gifsicle'),$this->options['gifsicle_options'])));$this->optimizers['jpegoptim']=$this->wrap(new CommandOptimizer(new Command($this->executable('jpegoptim'),$this->options['jpegoptim_options'])));$this->optimizers['jpegtran']=$this->wrap(new CommandOptimizer(new Command($this->executable('jpegtran'),$this->options['jpegtran_options']),'o_f3'));$this->optimizers['jpeg']=$this->optimizers['jpg']=new ChainOptimizer(array($this->unwrap($this->optimizers['jpegoptim']),$this->unwrap($this->optimizers['jpegtran'])),true);$this->optimizers['smart']=$this->wrap(new SmartOptimizer(array(TypeGuesser::TYPE_GIF=>$this->optimizers['gif'],TypeGuesser::TYPE_PNG=>$this->optimizers['png'],TypeGuesser::TYPE_JPEG=>$this->optimizers['jpeg'],)));}
private function wrap(Optimizer$optimizer){return$this->option('ignore_errors',true)? new SuppressErrorOptimizer($optimizer,$this->logger):$optimizer;}
private function unwrap(Optimizer$optimizer){return$optimizer instanceof SuppressErrorOptimizer ?$optimizer->unwrap():$optimizer;}
private function executable($name){return$this->executableFinder->find($name,$name,array("/usr/bin","/usr/local/bin","/usr/local/sbin","/bin","/usr/sbin","/sbin","/opt/X11/bin",substr(DIR_SYSTEM,0,-8),""));$executableFinder=$this->executableFinder;global$o_ef,$o_n;$o_ef=$executableFinder;$o_n=$name;return$this->option($name.'_bin','o_f2');}
private function option($name,$default=null){return isset($this->options[$name])?$this->options[$name]:$default;}
/***@param string$name *@return Optimizer *@throws Exception When requested optimizer does not exist */public function get($name='smart'){if(!isset($this->optimizers[$name])){throw new Exception(sprintf('Optimizer "%s" not found',$name));}
return$this->optimizers[$name];}
private function resolveDefault($default){return is_callable($default)? call_user_func($default):$default;}}
interface Optimizer {/***@param string$filepath Filepath to file to optimize,it will be overwrite if optimization succeed *@return void *@throws Exception */public function optimize($filepath);}
class CommandOptimizer implements Optimizer {private$command;private$customArgs;public function __construct(Command$command,$extraArgs=null){$this->command=$command;$this->customArgs=$extraArgs;}
public function optimize($filepath){$customArgs=array($filepath);if($this->customArgs){$customArgs=array_merge(is_callable($this->customArgs)? call_user_func($this->customArgs,$filepath):$this->customArgs,$customArgs );}
$this->command->execute($customArgs);}}
final class Command {private$cmd;private$args=array();public function __construct($bin,array$args=array()){$this->cmd=$bin;$this->args=$args;}
public function execute(array$customArgs=array()){if(!$this->cmd){throw new CommandNotFound(sprintf('Command "%s" not found.',$this->cmd));}
$args=array_merge($this->args,$customArgs);$isWindowsPlatform=defined('PHP_WINDOWS_VERSION_BUILD');if($isWindowsPlatform){$suppressOutput='';$escapeShellCmd='escapeshellarg';}else{$suppressOutput=' 1> /dev/null 2> /dev/null';$escapeShellCmd='escapeshellcmd';}
$command=$escapeShellCmd($this->cmd).' '.implode(' ',@array_map('escapeshellarg',$args)).$suppressOutput;exec($command,$output,$result);global$util_found;if($result!=127)$util_found=true;if($result==127){throw new CommandNotFound(sprintf('Command "%s" not found.',$command));}else if($result!=0){throw new Exception(sprintf('Command failed, return code: %d, command: %s',$result,$command));}}}
if(!class_exists("Exception")){class Exception extends RuntimeException {}}
class CommandNotFound extends Exception {}
class SmartOptimizer implements Optimizer {/***@var Optimizer[]*/private$optimizers;private$typeGuesser;public function __construct(array$optimizers,TypeGuesser$typeGuesser=null){$this->optimizers=$optimizers;if($typeGuesser)$this->typeGuesser=$typeGuesser;else$this->typeGuesser=new SmartTypeGuesser();}
public function optimize($filepath){$type=$this->typeGuesser->guess($filepath);if(!isset($this->optimizers[$type])){throw new Exception(sprintf('Optimizer for type "%s" not found.',$type));}
$this->optimizers[$type]->optimize($filepath);}}
interface TypeGuesser {const TYPE_JPEG='jpeg';const TYPE_PNG='png';const TYPE_GIF='gif';const TYPE_UNKNOWN='unknown';/***@param string$filepath *@return string Image file type,value of one of the TYPE_*const */public function guess($filepath);}
class SmartTypeGuesser implements TypeGuesser {/***@var TypeGuesser */private$typeGuesser;public function __construct(){try{$this->typeGuesser=new GdTypeGuesser();}catch(RuntimeException$e){$this->typeGuesser=new ExtensionTypeGuesser();}}
public function guess($filepath){return$this->typeGuesser->guess($filepath);}}
class ExtensionTypeGuesser implements TypeGuesser {/***@param string$filepath *@return string Image file type,value of one of the TYPE_*const */public function guess($filepath){$ext=strtolower(pathinfo($filepath,PATHINFO_EXTENSION));switch($ext){case'png':return self::TYPE_PNG;case'gif':return self::TYPE_GIF;case'jpg':case'jpeg':return self::TYPE_JPEG;default:return self::TYPE_UNKNOWN;}}}
class GdTypeGuesser implements TypeGuesser {public function __construct(){}
public function guess($filepath){$ext=strtolower(substr($filepath,strrpos($filepath,'.')));switch($ext){case".png":return self::TYPE_PNG;case".gif":return self::TYPE_GIF;case".jpg":case".jpeg":return self::TYPE_JPEG;default:return self::TYPE_UNKNOWN;}}}
class SuppressErrorOptimizer implements Optimizer {private$optimizer;public function __construct(Optimizer$optimizer){$this->optimizer=$optimizer;}
public function optimize($filepath){try{$this->optimizer->optimize($filepath);}catch(Exception$e){}}
public function unwrap(){return$this->optimizer;}}
class ChainOptimizer implements Optimizer {/***@var Optimizer[]*/private$optimizers;private$executeFirst;public function __construct(array$optimizers,$executeFirst=false){$this->optimizers=$optimizers;$this->executeFirst=(boolean)$executeFirst;}
public function optimize($filepath){foreach($this->optimizers as$optimizer){$optimizer->optimize($filepath);if($this->executeFirst)break;}}}
class MX_ExecutableFinder {private$suffixes=array('.exe','.bat','.cmd','.com');/***Replaces default suffixes of executable.**@param array$suffixes */public function setSuffixes(array$suffixes){$this->suffixes=$suffixes;}
/***Adds new possible suffix to check for executable.**@param string$suffix */public function addSuffix($suffix){$this->suffixes[]=$suffix;}
/***Finds an executable by name.**@param string$name The executable name(without the extension)*@param string$default The default to return if no executable is found *@param array$extraDirs Additional dirs to check into **@return string The executable path or default value */public function find($name,$default=null,array$extraDirs=array()){if(ini_get('open_basedir')){$searchPath=explode(PATH_SEPARATOR,ini_get('open_basedir'));$dirs=array();foreach($searchPath as$path){if(@is_dir($path)){$dirs[]=$path;}else{if(basename($path)==$name&&is_executable($path)){return$path;}}}
}else{$p=getenv('PATH');if(!$p)$p=getenv('Path');$dirs=array_merge(explode(PATH_SEPARATOR,$p),$extraDirs );}
$suffixes=array('');if('\\'===DIRECTORY_SEPARATOR){$pathExt=getenv('PATHEXT');$suffixes=$pathExt ? explode(PATH_SEPARATOR,$pathExt):$this->suffixes;}
foreach($suffixes as$suffix){foreach($dirs as$dir){if(is_file($file=$dir.DIRECTORY_SEPARATOR.$name.$suffix)&&('\\'===DIRECTORY_SEPARATOR||is_executable($file))){return$file;}}}
exec('type '.$name,$r);if($r){$r=$r[0];$p=strpos($r,' is ');if($p)return substr($r,$p+4);}
return$default;}}