Home > Backend Development > PHP Tutorial > PHP code used to automatically compress js files

PHP code used to automatically compress js files

WBOY
Release: 2016-07-25 09:02:58
Original
1146 people have browsed it
  1. /* 9 April 2008. version 1.1
  2. *
  3. * This is the php version of the Dean Edwards JavaScript's Packer,
  4. * Based on :
  5. *
  6. * ParseMaster, version 1.0.2 (2005-08-19) Copyright 2005, Dean Edwards
  7. * a multi-pattern parser.
  8. * KNOWN BUG: erroneous behavior when using escapeChar with a replacement
  9. * value that is a function
  10. *
  11. * packer, version 2.0.2 (2005-08-19) Copyright 2004-2005, Dean Edwards
  12. *
  13. * License: http://creativecommons.org/licenses/LGPL/2.1/
  14. *
  15. * Ported to PHP by Nicolas Martin.
  16. *
  17. * ----------------------------------------------------------------------
  18. * changelog:
  19. * 1.1 : correct a bug, '/0' packed then unpacked becomes '/'.
  20. * ----------------------------------------------------------------------
  21. *
  22. * examples of usage :
  23. * $myPacker = new JavaScriptPacker($script, 62, true, false);
  24. * $packed = $myPacker->pack();
  25. *
  26. * or
  27. *
  28. * $myPacker = new JavaScriptPacker($script, 'Normal', true, false);
  29. * $packed = $myPacker->pack();
  30. *
  31. * or (default values)
  32. *
  33. * $myPacker = new JavaScriptPacker($script);
  34. * $packed = $myPacker->pack();
  35. *
  36. *
  37. * params of the constructor :
  38. * $script: the JavaScript to pack, string.
  39. * $encoding: level of encoding, int or string :
  40. * 0,10,62,95 or 'None', 'Numeric', 'Normal', 'High ASCII'.
  41. * default: 62.
  42. * $fastDecode: include the fast decoder in the packed result, boolean.
  43. * default : true.
  44. * $specialChars: if you are flagged your private and local variables
  45. * in the script, boolean.
  46. * default: false.
  47. *
  48. * The pack() method return the compressed JavasScript, as a string.
  49. *
  50. * see http://dean.edwards.name/packer/usage/ for more information.
  51. *
  52. * Notes :
  53. * # need PHP 5 . Tested with PHP 5.1.2, 5.1.3, 5.1.4, 5.2.3
  54. *
  55. * # The packed result may be different than with the Dean Edwards
  56. * version, but with the same length. The reason is that the PHP
  57. * function usort to sort array don't necessarily preserve the
  58. * original order of two equal member. The Javascript sort function
  59. * in fact preserve this order (but that's not require by the
  60. * ECMAScript standard). So the encoded keywords order can be
  61. * different in the two results.
  62. *
  63. * # Be careful with the 'High ASCII' Level encoding if you use
  64. * UTF-8 in your files...
  65. */
  66. class JavaScriptPacker {
  67. // constants
  68. const IGNORE = '$1';
  69. // validate parameters
  70. private $_script = '';
  71. private $_encoding = 62;
  72. private $_fastDecode = true;
  73. private $_specialChars = false;
  74. private $LITERAL_ENCODING = array(
  75. 'None' => 0,
  76. 'Numeric' => 10,
  77. 'Normal' => 62,
  78. 'High ASCII' => 95
  79. );
  80. public function __construct($_script, $_encoding = 62, $_fastDecode = true, $_specialChars = false)
  81. {
  82. $this->_script = $_script . "/n";
  83. if (array_key_exists($_encoding, $this->LITERAL_ENCODING))
  84. $_encoding = $this->LITERAL_ENCODING[$_encoding];
  85. $this->_encoding = min((int)$_encoding, 95);
  86. $this->_fastDecode = $_fastDecode;
  87. $this->_specialChars = $_specialChars;
  88. }
  89. public function pack() {
  90. $this->_addParser('_basicCompression');
  91. if ($this->_specialChars)
  92. $this->_addParser('_encodeSpecialChars');
  93. if ($this->_encoding)
  94. $this->_addParser('_encodeKeywords');
  95. // go!
  96. return $this->_pack($this->_script);
  97. }
  98. // apply all parsing routines
  99. private function _pack($script) {
  100. for ($i = 0; isset($this->_parsers[$i]); $i++) {
  101. $script = call_user_func(array(&$this,$this->_parsers[$i]), $script);
  102. }
  103. return $script;
  104. }
  105. // keep a list of parsing functions, they'll be executed all at once
  106. private $_parsers = array();
  107. private function _addParser($parser) {
  108. $this->_parsers[] = $parser;
  109. }
  110. // zero encoding - just removal of white space and comments
  111. private function _basicCompression($script) {
  112. $parser = new ParseMaster();
  113. // make safe
  114. $parser->escapeChar = '//';
  115. // protect strings
  116. $parser->add('//'[^/'//n//r]*/'/', self::IGNORE);
  117. $parser->add('/"[^"//n//r]*"/', self::IGNORE);
  118. // remove comments
  119. $parser->add('///////[^//n//r]*[//n//r]/', ' ');
  120. $parser->add('//////*[^*]*//*+([^///][^*]*//*+)*////', ' ');
  121. // protect regular expressions
  122. $parser->add('///s+(///[^/////n//r//*][^/////n//r]*///g?i?)/', '$2'); // IGNORE
  123. $parser->add('/[^//w//x24////'"*)//?:]///[^/////n//r//*][^/////n//r]*///g?i?/', self::IGNORE);
  124. // remove: ;;; doSomething();
  125. if ($this->_specialChars) $parser->add('/;;;[^//n//r]+[//n//r]/');
  126. // remove redundant semi-colons
  127. $parser->add('///(;;//)/', self::IGNORE); // protect for (;;) loops
  128. $parser->add('/;+//s*([};])/', '$2');
  129. // apply the above
  130. $script = $parser->exec($script);
  131. // remove white-space
  132. $parser->add('/(//b|//x24)//s+(//b|//x24)/', '$2 $3');
  133. $parser->add('/([+//-])//s+([+//-])/', '$2 $3');
  134. $parser->add('///s+/', '');
  135. // done
  136. return $parser->exec($script);
  137. }
  138. private function _encodeSpecialChars($script) {
  139. $parser = new ParseMaster();
  140. // replace: $name -> n, $$name -> na
  141. $parser->add('/((//x24+)([a-zA-Z$_]+))(//d*)/',
  142. array('fn' => '_replace_name')
  143. );
  144. // replace: _name -> _0, double-underscore (__name) is ignored
  145. $regexp = '///b_[A-Za-z//d]//w*/';
  146. // build the word list
  147. $keywords = $this->_analyze($script, $regexp, '_encodePrivate');
  148. // quick ref
  149. $encoded = $keywords['encoded'];
  150. $parser->add($regexp,
  151. array(
  152. 'fn' => '_replace_encoded',
  153. 'data' => $encoded
  154. )
  155. );
  156. return $parser->exec($script);
  157. }
  158. private function _encodeKeywords($script) {
  159. // escape high-ascii values already in the script (i.e. in strings)
  160. if ($this->_encoding > 62)
  161. $script = $this->_escape95($script);
  162. // create the parser
  163. $parser = new ParseMaster();
  164. $encode = $this->_getEncoder($this->_encoding);
  165. // for high-ascii, don't encode single character low-ascii
  166. $regexp = ($this->_encoding > 62) ? '///w//w+/' : '///w+/';
  167. // build the word list
  168. $keywords = $this->_analyze($script, $regexp, $encode);
  169. $encoded = $keywords['encoded'];
  170. // encode
  171. $parser->add($regexp,
  172. array(
  173. 'fn' => '_replace_encoded',
  174. 'data' => $encoded
  175. )
  176. );
  177. if (emptyempty($script)) return $script;
  178. else {
  179. //$res = $parser->exec($script);
  180. //$res = $this->_bootStrap($res, $keywords);
  181. //return $res;
  182. return $this->_bootStrap($parser->exec($script), $keywords);
  183. }
  184. }
  185. private function _analyze($script, $regexp, $encode) {
  186. // analyse
  187. // retreive all words in the script
  188. $all = array();
  189. preg_match_all($regexp, $script, $all);
  190. $_sorted = array(); // list of words sorted by frequency
  191. $_encoded = array(); // dictionary of word->encoding
  192. $_protected = array(); // instances of "protected" words
  193. $all = $all[0]; // simulate the javascript comportement of global match
  194. if (!emptyempty($all)) {
  195. $unsorted = array(); // same list, not sorted
  196. $protected = array(); // "protected" words (dictionary of word->"word")
  197. $value = array(); // dictionary of charCode->encoding (eg. 256->ff)
  198. $this->_count = array(); // word->count
  199. $i = count($all); $j = 0; //$word = null;
  200. // count the occurrences - used for sorting later
  201. do {
  202. --$i;
  203. $word = '$' . $all[$i];
  204. if (!isset($this->_count[$word])) {
  205. $this->_count[$word] = 0;
  206. $unsorted[$j] = $word;
  207. // make a dictionary of all of the protected words in this script
  208. // these are words that might be mistaken for encoding
  209. //if (is_string($encode) && method_exists($this, $encode))
  210. $values[$j] = call_user_func(array(&$this, $encode), $j);
  211. $protected['$' . $values[$j]] = $j++;
  212. }
  213. // increment the word counter
  214. $this->_count[$word]++;
  215. } while ($i > 0);
  216. // prepare to sort the word list, first we must protect
  217. // words that are also used as codes. we assign them a code
  218. // equivalent to the word itself.
  219. // e.g. if "do" falls within our encoding range
  220. // then we store keywords["do"] = "do";
  221. // this avoids problems when decoding
  222. $i = count($unsorted);
  223. do {
  224. $word = $unsorted[--$i];
  225. if (isset($protected[$word]) /*!= null*/) {
  226. $_sorted[$protected[$word]] = substr($word, 1);
  227. $_protected[$protected[$word]] = true;
  228. $this->_count[$word] = 0;
  229. }
  230. } while ($i);
  231. // sort the words by frequency
  232. // Note: the javascript and php version of sort can be different :
  233. // in php manual, usort :
  234. // " If two members compare as equal,
  235. // their order in the sorted array is undefined."
  236. // so the final packed script is different of the Dean's javascript version
  237. // but equivalent.
  238. // the ECMAscript standard does not guarantee this behaviour,
  239. // and thus not all browsers (e.g. Mozilla versions dating back to at
  240. // least 2003) respect this.
  241. usort($unsorted, array(&$this, '_sortWords'));
  242. $j = 0;
  243. // because there are "protected" words in the list
  244. // we must add the sorted words around them
  245. do {
  246. if (!isset($_sorted[$i]))
  247. $_sorted[$i] = substr($unsorted[$j++], 1);
  248. $_encoded[$_sorted[$i]] = $values[$i];
  249. } while (++$i < count($unsorted));
  250. }
  251. return array(
  252. 'sorted' => $_sorted,
  253. 'encoded' => $_encoded,
  254. 'protected' => $_protected);
  255. }
  256. private $_count = array();
  257. private function _sortWords($match1, $match2) {
  258. return $this->_count[$match2] - $this->_count[$match1];
  259. }
  260. // build the boot function used for loading and decoding
  261. private function _bootStrap($packed, $keywords) {
  262. $ENCODE = $this->_safeRegExp('$encode//($count//)');
  263. // $packed: the packed script
  264. $packed = "'" . $this->_escape($packed) . "'";
  265. // $ascii: base for encoding
  266. $ascii = min(count($keywords['sorted']), $this->_encoding);
  267. if ($ascii == 0) $ascii = 1;
  268. // $count: number of words contained in the script
  269. $count = count($keywords['sorted']);
  270. // $keywords: list of words contained in the script
  271. foreach ($keywords['protected'] as $i=>$value) {
  272. $keywords['sorted'][$i] = '';
  273. }
  274. // convert from a string to an array
  275. ksort($keywords['sorted']);
  276. $keywords = "'" . implode('|',$keywords['sorted']) . "'.split('|')";
  277. $encode = ($this->_encoding > 62) ? '_encode95' : $this->_getEncoder($ascii);
  278. $encode = $this->_getJSFunction($encode);
  279. $encode = preg_replace('/_encoding/','$ascii', $encode);
  280. $encode = preg_replace('/arguments//.callee/','$encode', $encode);
  281. $inline = '//$count' . ($ascii > 10 ? '.toString(//$ascii)' : '');
  282. // $decode: code snippet to speed up decoding
  283. if ($this->_fastDecode) {
  284. // create the decoder
  285. $decode = $this->_getJSFunction('_decodeBody');
  286. if ($this->_encoding > 62)
  287. $decode = preg_replace('/////w/', '[//xa1-//xff]', $decode);
  288. // perform the encoding inline for lower ascii values
  289. elseif ($ascii < 36)
  290. $decode = preg_replace($ENCODE, $inline, $decode);
  291. // special case: when $count==0 there are no keywords. I want to keep
  292. // the basic shape of the unpacking funcion so i'll frig the code...
  293. if ($count == 0)
  294. $decode = preg_replace($this->_safeRegExp('($count)//s*=//s*1'), '$1=0', $decode, 1);
  295. }
  296. // boot function
  297. $unpack = $this->_getJSFunction('_unpack');
  298. if ($this->_fastDecode) {
  299. // insert the decoder
  300. $this->buffer = $decode;
  301. $unpack = preg_replace_callback('///{/', array(&$this, '_insertFastDecode'), $unpack, 1);
  302. }
  303. $unpack = preg_replace('/"/', "'", $unpack);
  304. if ($this->_encoding > 62) { // high-ascii
  305. // get rid of the word-boundaries for regexp matches
  306. $unpack = preg_replace('//'////////b/'/s*//+|//+/s*/'////////b/'/', '', $unpack);
  307. }
  308. if ($ascii > 36 || $this->_encoding > 62 || $this->_fastDecode) {
  309. // insert the encode function
  310. $this->buffer = $encode;
  311. $unpack = preg_replace_callback('///{/', array(&$this, '_insertFastEncode'), $unpack, 1);
  312. } else {
  313. // perform the encoding inline
  314. $unpack = preg_replace($ENCODE, $inline, $unpack);
  315. }
  316. // pack the boot function too
  317. $unpackPacker = new JavaScriptPacker($unpack, 0, false, true);
  318. $unpack = $unpackPacker->pack();
  319. // arguments
  320. $params = array($packed, $ascii, $count, $keywords);
  321. if ($this->_fastDecode) {
  322. $params[] = 0;
  323. $params[] = '{}';
  324. }
  325. $params = implode(',', $params);
  326. // the whole thing
  327. return 'eval(' . $unpack . '(' . $params . "))/n";
  328. }
  329. private $buffer;
  330. private function _insertFastDecode($match) {
  331. return '{' . $this->buffer . ';';
  332. }
  333. private function _insertFastEncode($match) {
  334. return '{$encode=' . $this->buffer . ';';
  335. }
  336. // mmm.. ..which one do i need ??
  337. private function _getEncoder($ascii) {
  338. return $ascii > 10 ? $ascii > 36 ? $ascii > 62 ?
  339. '_encode95' : '_encode62' : '_encode36' : '_encode10';
  340. }
  341. // zero encoding
  342. // characters: 0123456789
  343. private function _encode10($charCode) {
  344. return $charCode;
  345. }
  346. // inherent base36 support
  347. // characters: 0123456789abcdefghijklmnopqrstuvwxyz
  348. private function _encode36($charCode) {
  349. return base_convert($charCode, 10, 36);
  350. }
  351. // hitch a ride on base36 and add the upper case alpha characters
  352. // characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  353. private function _encode62($charCode) {
  354. $res = '';
  355. if ($charCode >= $this->_encoding) {
  356. $res = $this->_encode62((int)($charCode / $this->_encoding));
  357. }
  358. $charCode = $charCode % $this->_encoding;
  359. if ($charCode > 35)
  360. return $res . chr($charCode + 29);
  361. else
  362. return $res . base_convert($charCode, 10, 36);
  363. }
  364. // use high-ascii values
  365. // characters: ?¢£¤¥|§¨?a??-?ˉ°±23′μ?·?1o?????àá??????èéê?ìí??D?òó???×?ùú?üYT?àáa?????èéê?ìí??e?òó???÷?ùú?üyt
  366. private function _encode95($charCode) {
  367. $res = '';
  368. if ($charCode >= $this->_encoding)
  369. $res = $this->_encode95($charCode / $this->_encoding);
  370. return $res . chr(($charCode % $this->_encoding) + 161);
  371. }
  372. private function _safeRegExp($string) {
  373. return '/'.preg_replace('//$/', '///$', $string).'/';
  374. }
  375. private function _encodePrivate($charCode) {
  376. return "_" . $charCode;
  377. }
  378. // protect characters used by the parser
  379. private function _escape($script) {
  380. return preg_replace('/([/////'])/', '///$1', $script);
  381. }
  382. // protect high-ascii characters already in the script
  383. private function _escape95($script) {
  384. return preg_replace_callback(
  385. '/[//xa1-//xff]/',
  386. array(&$this, '_escape95Bis'),
  387. $script
  388. );
  389. }
  390. private function _escape95Bis($match) {
  391. return '/x'.((string)dechex(ord($match)));
  392. }
  393. private function _getJSFunction($aName) {
  394. if (defined('self::JSFUNCTION'.$aName))
  395. return constant('self::JSFUNCTION'.$aName);
  396. else
  397. return '';
  398. }
  399. // JavaScript Functions used.
  400. // Note : In Dean's version, these functions are converted
  401. // with 'String(aFunctionName);'.
  402. // This internal conversion complete the original code, ex :
  403. // 'while (aBool) anAction();' is converted to
  404. // 'while (aBool) { anAction(); }'.
  405. // The JavaScript functions below are corrected.
  406. // unpacking function - this is the boot strap function
  407. // data extracted from this packing routine is passed to
  408. // this function when decoded in the target
  409. // NOTE ! : without the ';' final.
  410. const JSFUNCTION_unpack =
  411. 'function($packed, $ascii, $count, $keywords, $encode, $decode) {
  412. while ($count--) {
  413. if ($keywords[$count]) {
  414. $packed = $packed.replace(new RegExp(/'////b/' + $encode($count) + /'////b/', /'g/'), $keywords[$count]);
  415. }
  416. }
  417. return $packed;
  418. }';
  419. /*
  420. 'function($packed, $ascii, $count, $keywords, $encode, $decode) {
  421. while ($count--)
  422. if ($keywords[$count])
  423. $packed = $packed.replace(new RegExp(/'////b/' + $encode($count) + /'////b/', /'g/'), $keywords[$count]);
  424. return $packed;
  425. }';
  426. */
  427. // code-snippet inserted into the unpacker to speed up decoding
  428. const JSFUNCTION_decodeBody =
  429. //_decode = function() {
  430. // does the browser support String.replace where the
  431. // replacement value is a function?
  432. ' if (!/'/'.replace(/^/, String)) {
  433. // decode all the values we need
  434. while ($count--) {
  435. $decode[$encode($count)] = $keywords[$count] || $encode($count);
  436. }
  437. // global replacement function
  438. $keywords = [function ($encoded) {return $decode[$encoded]}];
  439. // generic match
  440. $encode = function () {return /'////w+/'};
  441. // reset the loop counter - we are now doing a global replace
  442. $count = 1;
  443. }
  444. ';
  445. //};
  446. /*
  447. ' if (!/'/'.replace(/^/, String)) {
  448. // decode all the values we need
  449. while ($count--) $decode[$encode($count)] = $keywords[$count] || $encode($count);
  450. // global replacement function
  451. $keywords = [function ($encoded) {return $decode[$encoded]}];
  452. // generic match
  453. $encode = function () {return/'////w+/'};
  454. // reset the loop counter - we are now doing a global replace
  455. $count = 1;
  456. }';
  457. */
  458. // zero encoding
  459. // characters: 0123456789
  460. const JSFUNCTION_encode10 =
  461. 'function($charCode) {
  462. return $charCode;
  463. }';//;';
  464. // inherent base36 support
  465. // characters: 0123456789abcdefghijklmnopqrstuvwxyz
  466. const JSFUNCTION_encode36 =
  467. 'function($charCode) {
  468. return $charCode.toString(36);
  469. }';//;';
  470. // hitch a ride on base36 and add the upper case alpha characters
  471. // characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  472. const JSFUNCTION_encode62 =
  473. 'function($charCode) {
  474. return ($charCode < _encoding ? /'/' : arguments.callee(parseInt($charCode / _encoding))) +
  475. (($charCode = $charCode % _encoding) > 35 ? String.fromCharCode($charCode + 29) : $charCode.toString(36));
  476. }';
  477. // use high-ascii values
  478. // characters: ?¢£¤¥|§¨?a??-?ˉ°±23′μ?·?1o?????àá??????èéê?ìí??D?òó???×?ùú?üYT?àáa?????èéê?ìí??e?òó???÷?ùú?üyt
  479. const JSFUNCTION_encode95 =
  480. 'function($charCode) {
  481. return ($charCode < _encoding ? /'/' : arguments.callee($charCode / _encoding)) +
  482. String.fromCharCode($charCode % _encoding + 161);
  483. }';
  484. }
  485. class ParseMaster {
  486. public $ignoreCase = false;
  487. public $escapeChar = '';
  488. // constants
  489. const EXPRESSION = 0;
  490. const REPLACEMENT = 1;
  491. const LENGTH = 2;
  492. // used to determine nesting levels
  493. private $GROUPS = '///(/';//g
  494. private $SUB_REPLACE = '///$//d/';
  495. private $INDEXED = '/^//$//d+$/';
  496. private $TRIM = '/([/'"])//1//.(.*)//.//1//1$/';
  497. private $ESCAPE = '////./';//g
  498. private $QUOTE = '//'/';
  499. private $DELETED = '///x01[^//x01]*//x01/';//g
  500. public function add($expression, $replacement = '') {
  501. // count the number of sub-expressions
  502. // - add one because each pattern is itself a sub-expression
  503. $length = 1 + preg_match_all($this->GROUPS, $this->_internalEscape((string)$expression), $out);
  504. // treat only strings $replacement
  505. if (is_string($replacement)) {
  506. // does the pattern deal with sub-expressions?
  507. if (preg_match($this->SUB_REPLACE, $replacement)) {
  508. // a simple lookup? (e.g. "$2")
  509. if (preg_match($this->INDEXED, $replacement)) {
  510. // store the index (used for fast retrieval of matched strings)
  511. $replacement = (int)(substr($replacement, 1)) - 1;
  512. } else { // a complicated lookup (e.g. "Hello $2 $1")
  513. // build a function to do the lookup
  514. $quote = preg_match($this->QUOTE, $this->_internalEscape($replacement))
  515. ? '"' : "'";
  516. $replacement = array(
  517. 'fn' => '_backReferences',
  518. 'data' => array(
  519. 'replacement' => $replacement,
  520. 'length' => $length,
  521. 'quote' => $quote
  522. )
  523. );
  524. }
  525. }
  526. }
  527. // pass the modified arguments
  528. if (!emptyempty($expression)) $this->_add($expression, $replacement, $length);
  529. else $this->_add('/^$/', $replacement, $length);
  530. }
  531. public function exec($string) {
  532. // execute the global replacement
  533. $this->_escaped = array();
  534. // simulate the _patterns.toSTring of Dean
  535. $regexp = '/';
  536. foreach ($this->_patterns as $reg) {
  537. $regexp .= '(' . substr($reg[self::EXPRESSION], 1, -1) . ')|';
  538. }
  539. $regexp = substr($regexp, 0, -1) . '/';
  540. $regexp .= ($this->ignoreCase) ? 'i' : '';
  541. $string = $this->_escape($string, $this->escapeChar);
  542. $string = preg_replace_callback(
  543. $regexp,
  544. array(
  545. &$this,
  546. '_replacement'
  547. ),
  548. $string
  549. );
  550. $string = $this->_unescape($string, $this->escapeChar);
  551. return preg_replace($this->DELETED, '', $string);
  552. }
  553. public function reset() {
  554. // clear the patterns collection so that this object may be re-used
  555. $this->_patterns = array();
  556. }
  557. // private
  558. private $_escaped = array(); // escaped characters
  559. private $_patterns = array(); // patterns stored by index
  560. // create and add a new pattern to the patterns collection
  561. private function _add() {
  562. $arguments = func_get_args();
  563. $this->_patterns[] = $arguments;
  564. }
  565. // this is the global replace function (it's quite complicated)
  566. private function _replacement($arguments) {
  567. if (emptyempty($arguments)) return '';
  568. $i = 1; $j = 0;
  569. // loop through the patterns
  570. while (isset($this->_patterns[$j])) {
  571. $pattern = $this->_patterns[$j++];
  572. // do we have a result?
  573. if (isset($arguments[$i]) && ($arguments[$i] != '')) {
  574. $replacement = $pattern[self::REPLACEMENT];
  575. if (is_array($replacement) && isset($replacement['fn'])) {
  576. if (isset($replacement['data'])) $this->buffer = $replacement['data'];
  577. return call_user_func(array(&$this, $replacement['fn']), $arguments, $i);
  578. } elseif (is_int($replacement)) {
  579. return $arguments[$replacement + $i];
  580. }
  581. $delete = ($this->escapeChar == '' ||
  582. strpos($arguments[$i], $this->escapeChar) === false)
  583. ? '' : "/x01" . $arguments[$i] . "/x01";
  584. return $delete . $replacement;
  585. // skip over references to sub-expressions
  586. } else {
  587. $i += $pattern[self::LENGTH];
  588. }
  589. }
  590. }
  591. private function _backReferences($match, $offset) {
  592. $replacement = $this->buffer['replacement'];
  593. $quote = $this->buffer['quote'];
  594. $i = $this->buffer['length'];
  595. while ($i) {
  596. $replacement = str_replace('$'.$i--, $match[$offset + $i], $replacement);
  597. }
  598. return $replacement;
  599. }
  600. private function _replace_name($match, $offset){
  601. $length = strlen($match[$offset + 2]);
  602. $start = $length - max($length - strlen($match[$offset + 3]), 0);
  603. return substr($match[$offset + 1], $start, $length) . $match[$offset + 4];
  604. }
  605. private function _replace_encoded($match, $offset) {
  606. return $this->buffer[$match[$offset]];
  607. }
  608. // php : we cannot pass additional data to preg_replace_callback,
  609. // and we cannot use &$this in create_function, so let's go to lower level
  610. private $buffer;
  611. // encode escaped characters
  612. private function _escape($string, $escapeChar) {
  613. if ($escapeChar) {
  614. $this->buffer = $escapeChar;
  615. return preg_replace_callback(
  616. '///' . $escapeChar . '(.)' .'/',
  617. array(&$this, '_escapeBis'),
  618. $string
  619. );
  620. } else {
  621. return $string;
  622. }
  623. }
  624. private function _escapeBis($match) {
  625. $this->_escaped[] = $match[1];
  626. return $this->buffer;
  627. }
  628. // decode escaped characters
  629. private function _unescape($string, $escapeChar) {
  630. if ($escapeChar) {
  631. $regexp = '/'.'//'.$escapeChar.'/';
  632. $this->buffer = array('escapeChar'=> $escapeChar, 'i' => 0);
  633. return preg_replace_callback
  634. (
  635. $regexp,
  636. array(&$this, '_unescapeBis'),
  637. $string
  638. );
  639. } else {
  640. return $string;
  641. }
  642. }
  643. private function _unescapeBis() {
  644. if (isset($this->_escaped[$this->buffer['i']])
  645. && $this->_escaped[$this->buffer['i']] != '')
  646. {
  647. $temp = $this->_escaped[$this->buffer['i']];
  648. } else {
  649. $temp = '';
  650. }
  651. $this->buffer['i']++;
  652. return $this->buffer['escapeChar'] . $temp;
  653. }
  654. private function _internalEscape($string) {
  655. return preg_replace($this->ESCAPE, '', $string);
  656. }
  657. }
  658. ?>
复制代码

2、执行压缩的PHP文件 pack_js_file.php

  1. require 'tom-class.JavaScriptPacker.php';
  2. $t1 = microtime(true);
  3. $source_dir = realpath(dirname(__FILE__)."/..")."/common/script_unpacked";
  4. $out_dir = realpath(dirname(__FILE__)."/..")."/common/script";
  5. $d = dir( $source_dir );
  6. //echo "Handle: " . $d->handle . "/n";
  7. //echo "Path: " . $d->path . "/n";
  8. while (false !== ($entry = $d->read())) {
  9. if($entry=='.') continue;
  10. if($entry=='..') continue;
  11. if($entry=='.svn') continue;
  12. echo $entry."/n";
  13. $script = file_get_contents($source_dir. '/'. $entry);
  14. $packer = new JavaScriptPacker($script, 'Normal', true, false);
  15. $packed = $packer->pack();
  16. file_put_contents($out_dir. '/'. $entry, $packed);
  17. }
  18. $d->close();
  19. $t2 = microtime(true);
  20. $time = sprintf('%.4f', ($t2 - $t1) );
  21. echo 'script in ', $time, ' s.', "/n";
  22. die;
  23. ?>
复制代码

3、创建一个自动执行的bat文件。 在文件中输入如下的内容: /usr/local/php/bin/php pack_js_file.php

总结: 只要填好相对路径或者绝对路径,一键加密JS完成,那是相当的方便!!



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template