PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/includes/js/edit_area/edit_area/edit_area_compressor.php

https://github.com/KenBoyer/CompactCMS
PHP | 631 lines | 485 code | 37 blank | 109 comment | 40 complexity | 1fd037f9a3d7a6b110a2087b0fc2eee2 MD5 | raw file
  1. <?php #! /usr/bin/php
  2. //; /usr/bin/php $0 $@ ; exit 0;
  3. /* ^ can't use the shebang trick here as that would produce one more line
  4. of output when this file is run from a webserver, so we take the second-best
  5. approach, which is to favor the webserver and tolerate a few sh/bash error
  6. reports while it'll start the PHP CLI for us after all.
  7. Execute from the commandline (bash) like this, for example:
  8. $ ./edit_area_compressor.php plugins=1 compress=1
  9. Don't bother about these error reports then:
  10. ./edit_area_compressor.php: line 1: ?php: No such file or directory
  11. ./edit_area_compressor.php: line 2: //: is a directory
  12. PHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/idn.ini on line 1 in Unknown on line 0
  13. The latter shows up on Ubuntu 10.04 installs; again not to bother. The first two
  14. errors are due to our hack to help bash/sh kickstart the PHP interpreter after all,
  15. which is a bit convoluted as the shebang trick cannot happen for it would output
  16. the shebang line with the generated JavaScript when the script is executed by
  17. a web server. We don't that to happen, so we tolerate the error reports when running
  18. in a UNIX shell environment.
  19. */
  20. /******
  21. *
  22. * EditArea PHP compressor
  23. * Developed by Christophe Dolivet
  24. * Released under LGPL, Apache and BSD licenses
  25. * v1.1.3 (2007/01/18)
  26. *
  27. ******/
  28. if (0) // if (1) when you need to diagnose your environment
  29. {
  30. echo "_SERVER:\n";
  31. var_dump($_SERVER);
  32. echo "_ENV:\n";
  33. var_dump($_ENV);
  34. echo "ours:\n";
  35. echo "\n argv[0] = " . (empty($argv[0]) ? "(NULL)" : $argv[0]);
  36. echo "\n SHELL = " . (!array_key_exists('SHELL', $_ENV) ? "(NULL)" : $_ENV['SHELL']);
  37. echo "\n SESSIONNAME = " . (!array_key_exists('SESSIONNAME', $_SERVER) ? "(NULL)" : $_SERVER['SESSIONNAME']);
  38. echo "\n HTTP_HOST = " . (!array_key_exists('HTTP_HOST', $_SERVER) ? "(NULL)" : $_SERVER['HTTP_HOST']);
  39. echo "\n QUERY_STRING = " . (!array_key_exists('QUERY_STRING', $_SERVER) ? "(NULL)" : $_SERVER['QUERY_STRING']);
  40. echo "\n REQUEST_METHOD = " . (!array_key_exists('REQUEST_METHOD', $_SERVER) ? "(NULL)" : $_SERVER['REQUEST_METHOD']);
  41. die();
  42. }
  43. /*
  44. only run the compressor in here when executed from the commandline; otherwise we'll only
  45. define the compressor class and wait for the other code out there to call us:
  46. Tests turn out that $_SERVER['SESSIONNAME'] == 'Console' only on Windows machines, while
  47. UNIX boxes don't need to present $_ENV['SHELL']. Hence this check to see whether we're
  48. running from a console or crontab:
  49. - argv[0] WILL be set when run from the command line (it should list our PHP file)
  50. - $_SERVER['HTTP_HOST'] does NOT EXIST when run from the console
  51. - $_SERVER['QUERY_STRING'] does NOT EXIST when run from the console (it may very well be EMPTY when run by the web server!)
  52. - $_SERVER['REQUEST_METHOD'] does NOT EXIST when run from the console
  53. Supported arguments when run from the commandline:
  54. plugins - generate the 'full_with_plugins' version instead of the 'full' one
  55. you can also override any of the $param[] items like so, for example:
  56. debug=0 - equals $params['debug'] = false;
  57. debug=1 - equals $params['debug'] = true;
  58. */
  59. if (!empty($argv[0]) && stristr($argv[0], '.php') !== false &&
  60. !array_key_exists('HTTP_HOST', $_SERVER) &&
  61. !array_key_exists('QUERY_STRING', $_SERVER) &&
  62. !array_key_exists('REQUEST_METHOD', $_SERVER))
  63. {
  64. // CONFIG
  65. $param['cache_duration'] = 3600 * 24 * 10; // 10 days util client cache expires
  66. $param['compress'] = false; // Enable the code compression, should be activated but it can be useful to deactivate it for easier error diagnostics (true or false)
  67. $param['debug'] = false; // Enable this option if you need debugging info
  68. $param['use_disk_cache'] = true; // If you enable this option gzip files will be cached on disk.
  69. $param['use_gzip']= false; // Enable gzip compression
  70. $param['plugins'] = true; // isset($_GET['plugins']); Include plugins in the compressed/flattened JS output.
  71. $param['echo2stdout'] = false; // Output generated JS to stdout; alternative is to store it in the object for later retrieval.
  72. $param['include_langs_and_syntaxes'] = true; // Set to FALSE for backwards compatibility: do not include the language files and syntax definitions in the flattened output.
  73. // END CONFIG
  74. for ($i = 1; $i < $argc; $i++)
  75. {
  76. $arg = explode('=', $argv[$i], 2);
  77. $param[$arg[0]] = (isset($arg[1]) ? intval($arg[1]) : true);
  78. }
  79. $param['running_from_commandline'] = true; // UNSET or FALSE when executed from a web server
  80. $param['verbose2stdout'] = !$param['echo2stdout']; // UNSET or FALSE when executed from a web server
  81. if (!empty($param['verbose2stdout']))
  82. {
  83. echo "\nEditArea Compressor:\n";
  84. echo "Settings:\n";
  85. foreach($param as $key => $value)
  86. {
  87. echo sprintf(" %30s: %d\n", $key, $value);
  88. }
  89. }
  90. $compressor = new Compressor($param);
  91. }
  92. class Compressor
  93. {
  94. //function compressor($param)
  95. //{
  96. // $this->__construct($param);
  97. //}
  98. //
  99. //--> Strict Standards: Redefining already defined constructor for class Compressor
  100. function __construct($param)
  101. {
  102. $this->datas = false;
  103. $this->gzip_datas = false;
  104. $this->generated_headers = array();
  105. $this->start_time= $this->get_microtime();
  106. $this->file_loaded_size=0;
  107. $this->param= $param;
  108. $this->script_list="";
  109. $this->path= str_replace('\\','/',dirname(__FILE__)).'/';
  110. if($this->param['plugins'])
  111. {
  112. if (!empty($this->param['verbose2stdout'])) echo "\n\n\nGenerating output with plugins included\n";
  113. $this->load_all_plugins= true;
  114. $this->full_cache_file= $this->path."edit_area_full_with_plugins.js";
  115. $this->gzip_cache_file= $this->path."edit_area_full_with_plugins.gz";
  116. }
  117. else
  118. {
  119. if (!empty($this->param['verbose2stdout'])) echo "\n\n\nGenrating output WITHOUT plugins\n";
  120. $this->load_all_plugins= false;
  121. $this->full_cache_file= $this->path."edit_area_full.js";
  122. $this->gzip_cache_file= $this->path."edit_area_full.gz";
  123. }
  124. $this->check_gzip_use();
  125. $this->send_headers();
  126. $this->check_cache();
  127. $this->load_files();
  128. $this->send_datas();
  129. }
  130. /**
  131. * Return the HTTP headers associated with the compressed/flattened output file as an array of header lines.
  132. */
  133. public function get_headers()
  134. {
  135. return $this->generated_headers;
  136. }
  137. /**
  138. * Return the generated flattened JavaScript as a string.
  139. *
  140. * Return FALSE on error.
  141. */
  142. public function get_flattened()
  143. {
  144. return $this->datas;
  145. }
  146. /**
  147. * Return the generated flattened and GZIPped JavaScript (as output by gzencode()).
  148. *
  149. * Return FALSE on error or when GZIPped JavaScript has not been generated.
  150. */
  151. public function get_flattened_gzipped()
  152. {
  153. return $this->gzip_datas;
  154. }
  155. private function send_header1($headerline)
  156. {
  157. $this->generated_headers[] = $headerline;
  158. if ($this->param['echo2stdout'] && !headers_sent())
  159. {
  160. header($headerline);
  161. }
  162. }
  163. private function send_headers()
  164. {
  165. $this->send_header1("Content-type: text/javascript; charset: UTF-8");
  166. $this->send_header1("Vary: Accept-Encoding"); // Handle proxies
  167. $this->send_header1(sprintf("Expires: %s GMT", gmdate("D, d M Y H:i:s", time() + intval($this->param['cache_duration']))) );
  168. if($this->use_gzip)
  169. {
  170. $this->send_header1("Content-Encoding: ".$this->gzip_enc_header);
  171. }
  172. }
  173. private function check_gzip_use()
  174. {
  175. $encodings = array();
  176. $desactivate_gzip=false;
  177. if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
  178. {
  179. $encodings = explode(',', strtolower(preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_ENCODING'])));
  180. }
  181. // deactivate gzip for IE version < 7
  182. if (!isset($_SERVER['HTTP_USER_AGENT']))
  183. {
  184. // run from the commandline: do NOT use gzip
  185. $desactivate_gzip=true;
  186. }
  187. else if(preg_match("/(?:msie )([0-9.]+)/i", $_SERVER['HTTP_USER_AGENT'], $ie))
  188. {
  189. if($ie[1]<7)
  190. $desactivate_gzip=true;
  191. }
  192. // Check for gzip header or northon internet securities
  193. if (!$desactivate_gzip && $this->param['use_gzip'] && (in_array('gzip', $encodings) || in_array('x-gzip', $encodings) || isset($_SERVER['---------------'])) && function_exists('ob_gzhandler') && !ini_get('zlib.output_compression')) {
  194. $this->gzip_enc_header= in_array('x-gzip', $encodings) ? "x-gzip" : "gzip";
  195. $this->use_gzip=true;
  196. $this->cache_file=$this->gzip_cache_file;
  197. }else{
  198. $this->use_gzip=false;
  199. $this->cache_file=$this->full_cache_file;
  200. }
  201. }
  202. private function check_cache()
  203. {
  204. // Only gzip the contents if clients and server support it
  205. if ($this->param['use_disk_cache'] && file_exists($this->cache_file) && empty($this->param['running_from_commandline'])) {
  206. // check if cache file must be updated
  207. $cache_date=0;
  208. if ($dir = opendir($this->path)) {
  209. while (($file = readdir($dir)) !== false) {
  210. if(is_file($this->path.$file) && $file!="." && $file!="..")
  211. $cache_date= max($cache_date, filemtime($this->path.$file));
  212. }
  213. closedir($dir);
  214. }
  215. if($this->load_all_plugins){
  216. $plug_path= $this->path."plugins/";
  217. if (($dir = @opendir($plug_path)) !== false)
  218. {
  219. while (($file = readdir($dir)) !== false)
  220. {
  221. if ($file !== "." && $file !== "..")
  222. {
  223. if(is_dir($plug_path.$file) && file_exists($plug_path.$file."/".$file.".js"))
  224. $cache_date= max($cache_date, filemtime($plug_path.$file."/".$file.".js")); // fix for: http://sourceforge.net/tracker/?func=detail&aid=2932086&group_id=164008&atid=829999
  225. }
  226. }
  227. closedir($dir);
  228. }
  229. }
  230. if(filemtime($this->cache_file) >= $cache_date){
  231. // if cache file is up to date
  232. $last_modified = gmdate("D, d M Y H:i:s",filemtime($this->cache_file))." GMT";
  233. if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"]) && strcasecmp($_SERVER["HTTP_IF_MODIFIED_SINCE"], $last_modified) === 0)
  234. {
  235. header("HTTP/1.1 304 Not Modified");
  236. header("Last-modified: ".$last_modified);
  237. header("Cache-Control: Public"); // Tells HTTP 1.1 clients to cache
  238. header("Pragma:"); // Tells HTTP 1.0 clients to cache
  239. }
  240. else
  241. {
  242. header("Last-modified: ".$last_modified);
  243. header("Cache-Control: Public"); // Tells HTTP 1.1 clients to cache
  244. header("Pragma:"); // Tells HTTP 1.0 clients to cache
  245. header('Content-Length: '.filesize($this->cache_file));
  246. echo file_get_contents($this->cache_file);
  247. }
  248. die;
  249. }
  250. }
  251. return false;
  252. }
  253. private function load_files()
  254. {
  255. $loader= $this->get_content("edit_area_loader.js")."\n";
  256. // get the list of other files to load
  257. $loader= preg_replace("/(t\.scripts_to_load=\s*)\[([^\]]*)\];/e"
  258. , "\$this->replace_scripts('script_list', '\\1', '\\2')"
  259. , $loader);
  260. $loader= preg_replace("/(t\.sub_scripts_to_load=\s*)\[([^\]]*)\];/e"
  261. , "\$this->replace_scripts('sub_script_list', '\\1', '\\2')"
  262. , $loader);
  263. // [i_a] the fix for various browsers' show issues is to flatten EVERYTHING into a single file, i.e. also the language and reg_syntax files: the load_script() and other lazyload-ing bits of code in edit_area are somehow buggy and thus circumvented.
  264. // replace syntax definition names
  265. $syntax_defs = '';
  266. $reg_path= $this->path."reg_syntax/";
  267. $a_displayName = array();
  268. $a_Name = array();
  269. if (($dir = @opendir($reg_path)) !== false)
  270. {
  271. while (($file = readdir($dir)) !== false)
  272. {
  273. if( $file !== "." && $file !== ".." && substr($file, -3) == '.js' )
  274. {
  275. $jsContent = $this->file_get_contents( $reg_path.$file );
  276. if( preg_match( '@(\'|")DISPLAY_NAME\1\s*:\s*(\'|")(.*)\2@', $jsContent, $match ) )
  277. {
  278. $a_displayName[] = "'". substr($file, 0, strlen($file) - 3) ."':'". htmlspecialchars( $match[3], ENT_QUOTES, 'UTF-8') ."'";
  279. }
  280. if( preg_match( '@editAreaLoader\.load_syntax\[(\'|")([^\'"]+)\1\]\s*=@', $jsContent, $match ) )
  281. {
  282. $a_Name[] = htmlspecialchars( $match[2], ENT_QUOTES, 'UTF-8');
  283. }
  284. $syntax_defs .= $jsContent . "\n";
  285. // and add 'marked as loaded' code to that as well:
  286. $syntax_defs .= "editAreaLoader.loadedFiles[editAreaLoader.baseURL + 'reg_syntax/' + '" . $file . "'] = true;\n\n\n";
  287. }
  288. }
  289. closedir($dir);
  290. }
  291. $loader = str_replace( '/*syntax_display_name_AUTO-FILL-BY-COMPRESSOR*/', implode( ",", $a_displayName ), $loader );
  292. $loader = str_replace( '/*syntax_name_AUTO-FILL-BY-COMPRESSOR*/', implode( ",", $a_Name ), $loader );
  293. // collect languages
  294. $language_defs = '';
  295. $lang_path= $this->path."langs/";
  296. if (($dir = @opendir($lang_path)) !== false)
  297. {
  298. while (($file = readdir($dir)) !== false)
  299. {
  300. if( $file !== "." && $file !== ".." && substr($file, -3) == '.js' )
  301. {
  302. $jsContent = $this->file_get_contents( $lang_path.$file );
  303. $language_defs .= $jsContent . "\n";
  304. // and add 'marked as loaded' code to that as well:
  305. $language_defs .= "editAreaLoader.loadedFiles[editAreaLoader.baseURL + 'langs/' + '" . $file . "'] = true;\n\n\n";
  306. }
  307. }
  308. closedir($dir);
  309. }
  310. $this->datas= $loader;
  311. $this->compress_javascript($this->datas);
  312. // load other scripts needed for the loader
  313. preg_match_all('/"([^"]*)"/', $this->script_list, $match);
  314. foreach($match[1] as $key => $value)
  315. {
  316. $content= $this->get_content(preg_replace("/\\|\//i", "", $value).".js");
  317. $this->compress_javascript($content);
  318. $this->datas.= $content."\n";
  319. }
  320. //$this->datas);
  321. //$this->datas= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', "", $this->datas);
  322. // improved compression step 1/2
  323. if($this->param['compress'])
  324. {
  325. $this->datas= preg_replace(array("/(\b)EditAreaLoader(\b)/", "/(\b)editAreaLoader(\b)/", "/(\b)editAreas(\b)/"), array("EAL", "eAL", "eAs"), $this->datas);
  326. //$this->datas= str_replace(array("EditAreaLoader", "editAreaLoader", "editAreas"), array("EAL", "eAL", "eAs"), $this->datas);
  327. $this->datas.= "var editAreaLoader= eAL;var editAreas=eAs;EditAreaLoader=EAL;";
  328. }
  329. // load sub scripts
  330. $sub_scripts="";
  331. $sub_scripts_list= array();
  332. preg_match_all('/"([^"]*)"/', $this->sub_script_list, $match);
  333. foreach($match[1] as $value){
  334. $sub_scripts_list[]= preg_replace("/\\|\//i", "", $value).".js";
  335. }
  336. if($this->load_all_plugins){
  337. // load plugins scripts
  338. $plug_path= $this->path."plugins/";
  339. if (($dir = @opendir($plug_path)) !== false)
  340. {
  341. while (($file = readdir($dir)) !== false)
  342. {
  343. if ($file !== "." && $file !== "..")
  344. {
  345. if(is_dir($plug_path.$file) && file_exists($plug_path.$file."/".$file.".js"))
  346. $sub_scripts_list[]= "plugins/".$file."/".$file.".js";
  347. }
  348. }
  349. closedir($dir);
  350. }
  351. }
  352. foreach($sub_scripts_list as $value){
  353. $sub_scripts.= $this->get_javascript_content($value);
  354. }
  355. // improved compression step 2/2
  356. if($this->param['compress'])
  357. {
  358. $sub_scripts= preg_replace(array("/(\b)editAreaLoader(\b)/", "/(\b)editAreas(\b)/", "/(\b)editArea(\b)/", "/(\b)EditArea(\b)/"), array("eAL", "eAs", "eA", "EA"), $sub_scripts);
  359. // $sub_scripts= str_replace(array("editAreaLoader", "editAreas", "editArea", "EditArea"), array("eAL", "eAs", "eA", "EA"), $sub_scripts);
  360. $sub_scripts.= "var editArea= eA;EditArea=EA;";
  361. }
  362. // add the scripts
  363. // $this->datas.= sprintf("editAreaLoader.iframe_script= \"<script type='text/javascript'>%s</script>\";\n", $sub_scripts);
  364. // add the script and use a last compression
  365. if( $this->param['compress'] )
  366. {
  367. $last_comp = array( 'Á' => 'this',
  368. 'Â' => 'textarea',
  369. 'Ã' => 'function',
  370. 'Ä' => 'prototype',
  371. 'Å' => 'settings',
  372. 'Æ' => 'length',
  373. 'Ç' => 'style',
  374. 'È' => 'parent',
  375. 'É' => 'last_selection',
  376. 'Ê' => 'value',
  377. 'Ë' => 'true',
  378. 'Ì' => 'false'
  379. /*,
  380. 'Î' => '"',
  381. 'Ï' => "\n",
  382. 'À' => "\r"*/);
  383. }
  384. else
  385. {
  386. $last_comp = array();
  387. }
  388. $js_replace= '';
  389. foreach( $last_comp as $key => $val )
  390. $js_replace .= ".replace(/". $key ."/g,'". str_replace( array("\n", "\r"), array('\n','\r'), $val ) ."')";
  391. $this->datas.= sprintf("editAreaLoader.iframe_script= \"<script type='text/javascript'>%s</script>\"%s;\n",
  392. str_replace( array_values($last_comp), array_keys($last_comp), $sub_scripts ),
  393. $js_replace);
  394. if($this->load_all_plugins)
  395. $this->datas.="editAreaLoader.all_plugins_loaded=true;\n";
  396. // load the template
  397. $this->datas.= sprintf("editAreaLoader.template= \"%s\";\n", $this->get_html_content("template.html"));
  398. // load the css
  399. $this->datas.= sprintf("editAreaLoader.iframe_css= \"<style>%s</style>\";\n", $this->get_css_content("edit_area.css"));
  400. // load the syntaxes and languages as well:
  401. if ($this->param['include_langs_and_syntaxes'])
  402. {
  403. // make sure the syntax and/or language files are NOT nuked in the process so act conservatively when compressing:
  404. $this->compress_javascript($syntax_defs, false);
  405. $this->datas.= $syntax_defs;
  406. $this->compress_javascript($language_defs, false);
  407. $this->datas.= $language_defs;
  408. }
  409. // $this->datas= "function editArea(){};editArea.prototype.loader= function(){alert('bouhbouh');} var a= new editArea();a.loader();";
  410. }
  411. private function send_datas()
  412. {
  413. if($this->param['debug']){
  414. $header=sprintf("/* USE PHP COMPRESSION\n");
  415. $header.=sprintf("javascript size: based files: %s => PHP COMPRESSION => %s ", $this->file_loaded_size, strlen($this->datas));
  416. if($this->use_gzip){
  417. $gzip_datas= gzencode($this->datas, 9, FORCE_GZIP);
  418. $header.=sprintf("=> GZIP COMPRESSION => %s", strlen($gzip_datas));
  419. $ratio = round(100 - strlen($gzip_datas) / $this->file_loaded_size * 100.0);
  420. }else{
  421. $ratio = round(100 - strlen($this->datas) / $this->file_loaded_size * 100.0);
  422. }
  423. $header.=sprintf(", reduced by %s%%\n", $ratio);
  424. $header.=sprintf("compression time: %s\n", $this->get_microtime()-$this->start_time);
  425. $header.=sprintf("%s\n", implode("\n", $this->infos));
  426. $header.=sprintf("*/\n");
  427. $this->datas= $header.$this->datas;
  428. }
  429. $mtime= time(); // ensure that the 2 disk files will have the same update time
  430. // generate gzip file and cache it if using disk cache
  431. if($this->use_gzip){
  432. $this->gzip_datas= gzencode($this->datas, 9, FORCE_GZIP);
  433. if($this->param['use_disk_cache'])
  434. $this->file_put_contents($this->gzip_cache_file, $this->gzip_datas, $mtime);
  435. }
  436. // generate full js file and cache it if using disk cache
  437. if($this->param['use_disk_cache'])
  438. {
  439. if (!empty($this->param['verbose2stdout'])) echo "written to file: " . $this->full_cache_file . "\n";
  440. $this->file_put_contents($this->full_cache_file, $this->datas, $mtime);
  441. }
  442. // generate output
  443. if ($this->param['echo2stdout'])
  444. {
  445. if($this->use_gzip)
  446. echo $this->gzip_datas;
  447. else
  448. echo $this->datas;
  449. }
  450. // die;
  451. }
  452. private function get_content($end_uri)
  453. {
  454. $end_uri=preg_replace("/\.\./", "", $end_uri); // Remove any .. (security)
  455. $file= $this->path.$end_uri;
  456. if(file_exists($file)){
  457. $this->infos[]=sprintf("'%s' loaded", $end_uri);
  458. /*$fd = fopen($file, 'rb');
  459. $content = fread($fd, filesize($file));
  460. fclose($fd);
  461. return $content;*/
  462. return $this->file_get_contents($file);
  463. }else{
  464. $this->infos[]=sprintf("'%s' not loaded", $end_uri);
  465. return "";
  466. }
  467. }
  468. private function get_javascript_content($end_uri)
  469. {
  470. $val=$this->get_content($end_uri);
  471. $this->compress_javascript($val);
  472. $this->prepare_string_for_quotes($val);
  473. return $val;
  474. }
  475. private function compress_javascript(&$code, $apply_optimistic_rules = true)
  476. {
  477. if($this->param['compress'])
  478. {
  479. // remove all comments
  480. // (\"(?:[^\"\\]*(?:\\\\)*(?:\\\"?)?)*(?:\"|$))|(\'(?:[^\'\\]*(?:\\\\)*(?:\\'?)?)*(?:\'|$))|(?:\/\/(?:.|\r|\t)*?(\n|$))|(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))
  481. $code= preg_replace("/(\"(?:[^\"\\\\]*(?:\\\\\\\\)*(?:\\\\\"?)?)*(?:\"|$))|(\'(?:[^\'\\\\]*(?:\\\\\\\\)*(?:\\\\\'?)?)*(?:\'|$))|(?:\/\/(?:.|\r|\t)*?(\n|$))|(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))/s", "$1$2$3", $code);
  482. // remove line return, empty line and tabulation
  483. $code= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', " ", $code);
  484. // add line break before "else" otherwise navigators can't manage to parse the file
  485. if ($apply_optimistic_rules)
  486. {
  487. $code= preg_replace('/(\b(else)\b)/', "\n$1", $code);
  488. }
  489. // remove unnecessary spaces
  490. $code= preg_replace('/( |\t|\r)*(;|\{|\}|=|==|\-|\+|,|\(|\)|\|\||&\&|\:)( |\t|\r)*/', "$2", $code);
  491. }
  492. }
  493. private function get_css_content($end_uri){
  494. $code=$this->get_content($end_uri);
  495. // remove comments
  496. $code= preg_replace("/(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))/s", "", $code);
  497. // remove spaces
  498. $code= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', "", $code);
  499. // remove spaces
  500. $code= preg_replace('/( |\t|\r)?(\:|,|\{|\})( |\t|\r)+/', "$2", $code);
  501. $this->prepare_string_for_quotes($code);
  502. return $code;
  503. }
  504. private function get_html_content($end_uri){
  505. $code=$this->get_content($end_uri);
  506. //$code= preg_replace('/(\"(?:\\\"|[^\"])*(?:\"|$))|' . "(\'(?:\\\'|[^\'])*(?:\'|$))|(?:\/\/(?:.|\r|\t)*?(\n|$))|(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))/s", "$1$2$3", $code);
  507. $code= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', " ", $code);
  508. $this->prepare_string_for_quotes($code);
  509. return $code;
  510. }
  511. private function prepare_string_for_quotes(&$str){
  512. // prepare the code to be putted into quotes
  513. /*$pattern= array("/(\\\\)?\"/", '/\\\n/' , '/\\\r/' , "/(\r?\n)/");
  514. $replace= array('$1$1\\"', '\\\\\\n', '\\\\\\r' , '\\\n"$1+"');*/
  515. $pattern= array("/(\\\\)?\"/", '/\\\n/' , '/\\\r/' , "/(\r?\n)/");
  516. if($this->param['compress'])
  517. $replace= array('$1$1\\"', '\\\\\\n', '\\\\\\r' , '\n');
  518. else
  519. $replace= array('$1$1\\"', '\\\\\\n', '\\\\\\r' , "\\n\"\n+\"");
  520. $str= preg_replace($pattern, $replace, $str);
  521. }
  522. private function replace_scripts($var, $param1, $param2)
  523. {
  524. $this->$var=stripslashes($param2);
  525. return $param1."[];";
  526. }
  527. /* for php version that have not thoses functions */
  528. private function file_get_contents($file)
  529. {
  530. $fd = fopen($file, 'rb');
  531. $content = fread($fd, filesize($file));
  532. fclose($fd);
  533. $this->file_loaded_size+= strlen($content);
  534. return $content;
  535. }
  536. private function file_put_contents($file, &$content, $mtime=-1)
  537. {
  538. if($mtime==-1)
  539. $mtime=time();
  540. $fp = @fopen($file, "wb");
  541. if ($fp) {
  542. fwrite($fp, $content);
  543. fclose($fp);
  544. touch($file, $mtime);
  545. return true;
  546. }
  547. return false;
  548. }
  549. private function get_microtime()
  550. {
  551. list($usec, $sec) = explode(" ", microtime());
  552. return ((float)$usec + (float)$sec);
  553. }
  554. }
  555. ?>