search
HomeBackend DevelopmentPHP TutorialPHP code used to automatically compress js files

  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 }
  250. return array(
  251. 'sorted' => $_sorted,
  252. 'encoded' => $_encoded,
  253. 'protected' => $_protected);
  254. }
  255. private $_count = array();
  256. private function _sortWords($match1, $match2) {
  257. return $this->_count[$match2] - $this->_count[$match1];
  258. }
  259. // build the boot function used for loading and decoding
  260. private function _bootStrap($packed, $keywords) {
  261. $ENCODE = $this->_safeRegExp('$encode//($count//)');
  262. // $packed: the packed script
  263. $packed = "'" . $this->_escape($packed) . "'";
  264. // $ascii: base for encoding
  265. $ascii = min(count($keywords['sorted']), $this->_encoding);
  266. if ($ascii == 0) $ascii = 1;
  267. // $count: number of words contained in the script
  268. $count = count($keywords['sorted']);
  269. // $keywords: list of words contained in the script
  270. foreach ($keywords['protected'] as $i=>$value) {
  271. $keywords['sorted'][$i] = '';
  272. }
  273. // convert from a string to an array
  274. ksort($keywords['sorted']);
  275. $keywords = "'" . implode('|',$keywords['sorted']) . "'.split('|')";
  276. $encode = ($this->_encoding > 62) ? '_encode95' : $this->_getEncoder($ascii);
  277. $encode = $this->_getJSFunction($encode);
  278. $encode = preg_replace('/_encoding/','$ascii', $encode);
  279. $encode = preg_replace('/arguments//.callee/','$encode', $encode);
  280. $inline = '//$count' . ($ascii > 10 ? '.toString(//$ascii)' : '');
  281. // $decode: code snippet to speed up decoding
  282. if ($this->_fastDecode) {
  283. // create the decoder
  284. $decode = $this->_getJSFunction('_decodeBody');
  285. if ($this->_encoding > 62)
  286. $decode = preg_replace('/////w/', '[//xa1-//xff]', $decode);
  287. // perform the encoding inline for lower ascii values
  288. elseif ($ascii $decode = preg_replace($ENCODE, $inline, $decode);
  289. // special case: when $count==0 there are no keywords. I want to keep
  290. // the basic shape of the unpacking funcion so i'll frig the code...
  291. if ($count == 0)
  292. $decode = preg_replace($this->_safeRegExp('($count)//s*=//s*1'), '$1=0', $decode, 1);
  293. }
  294. // boot function
  295. $unpack = $this->_getJSFunction('_unpack');
  296. if ($this->_fastDecode) {
  297. // insert the decoder
  298. $this->buffer = $decode;
  299. $unpack = preg_replace_callback('///{/', array(&$this, '_insertFastDecode'), $unpack, 1);
  300. }
  301. $unpack = preg_replace('/"/', "'", $unpack);
  302. if ($this->_encoding > 62) { // high-ascii
  303. // get rid of the word-boundaries for regexp matches
  304. $unpack = preg_replace('//'////////b/'/s*//+|//+/s*/'////////b/'/', '', $unpack);
  305. }
  306. if ($ascii > 36 || $this->_encoding > 62 || $this->_fastDecode) {
  307. // insert the encode function
  308. $this->buffer = $encode;
  309. $unpack = preg_replace_callback('///{/', array(&$this, '_insertFastEncode'), $unpack, 1);
  310. } else {
  311. // perform the encoding inline
  312. $unpack = preg_replace($ENCODE, $inline, $unpack);
  313. }
  314. // pack the boot function too
  315. $unpackPacker = new JavaScriptPacker($unpack, 0, false, true);
  316. $unpack = $unpackPacker->pack();
  317. // arguments
  318. $params = array($packed, $ascii, $count, $keywords);
  319. if ($this->_fastDecode) {
  320. $params[] = 0;
  321. $params[] = '{}';
  322. }
  323. $params = implode(',', $params);
  324. // the whole thing
  325. return 'eval(' . $unpack . '(' . $params . "))/n";
  326. }
  327. private $buffer;
  328. private function _insertFastDecode($match) {
  329. return '{' . $this->buffer . ';';
  330. }
  331. private function _insertFastEncode($match) {
  332. return '{$encode=' . $this->buffer . ';';
  333. }
  334. // mmm.. ..which one do i need ??
  335. private function _getEncoder($ascii) {
  336. return $ascii > 10 ? $ascii > 36 ? $ascii > 62 ?
  337. '_encode95' : '_encode62' : '_encode36' : '_encode10';
  338. }
  339. // zero encoding
  340. // characters: 0123456789
  341. private function _encode10($charCode) {
  342. return $charCode;
  343. }
  344. // inherent base36 support
  345. // characters: 0123456789abcdefghijklmnopqrstuvwxyz
  346. private function _encode36($charCode) {
  347. return base_convert($charCode, 10, 36);
  348. }
  349. // hitch a ride on base36 and add the upper case alpha characters
  350. // characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  351. private function _encode62($charCode) {
  352. $res = '';
  353. if ($charCode >= $this->_encoding) {
  354. $res = $this->_encode62((int)($charCode / $this->_encoding));
  355. }
  356. $charCode = $charCode % $this->_encoding;
  357. if ($charCode > 35)
  358. return $res . chr($charCode + 29);
  359. else
  360. return $res . base_convert($charCode, 10, 36);
  361. }
  362. // use high-ascii values
  363. // characters: ?¢£¤¥|§¨?a??-?ˉ°±23′μ?·?1o?????àá??????èéê?ìí??D?òó???×?ùú?üYT?àáa?????èéê?ìí??e?òó???÷?ùú?üyt
  364. private function _encode95($charCode) {
  365. $res = '';
  366. if ($charCode >= $this->_encoding)
  367. $res = $this->_encode95($charCode / $this->_encoding);
  368. return $res . chr(($charCode % $this->_encoding) + 161);
  369. }
  370. private function _safeRegExp($string) {
  371. return '/'.preg_replace('//$/', '///$', $string).'/';
  372. }
  373. private function _encodePrivate($charCode) {
  374. return "_" . $charCode;
  375. }
  376. // protect characters used by the parser
  377. private function _escape($script) {
  378. return preg_replace('/([/////'])/', '///$1', $script);
  379. }
  380. // protect high-ascii characters already in the script
  381. private function _escape95($script) {
  382. return preg_replace_callback(
  383. '/[//xa1-//xff]/',
  384. array(&$this, '_escape95Bis'),
  385. $script
  386. );
  387. }
  388. private function _escape95Bis($match) {
  389. return '/x'.((string)dechex(ord($match)));
  390. }
  391. private function _getJSFunction($aName) {
  392. if (defined('self::JSFUNCTION'.$aName))
  393. return constant('self::JSFUNCTION'.$aName);
  394. else
  395. return '';
  396. }
  397. // JavaScript Functions used.
  398. // Note : In Dean's version, these functions are converted
  399. // with 'String(aFunctionName);'.
  400. // This internal conversion complete the original code, ex :
  401. // 'while (aBool) anAction();' is converted to
  402. // 'while (aBool) { anAction(); }'.
  403. // The JavaScript functions below are corrected.
  404. // unpacking function - this is the boot strap function
  405. // data extracted from this packing routine is passed to
  406. // this function when decoded in the target
  407. // NOTE ! : without the ';' final.
  408. const JSFUNCTION_unpack =
  409. 'function($packed, $ascii, $count, $keywords, $encode, $decode) {
  410. while ($count--) {
  411. if ($keywords[$count]) {
  412. $packed = $packed.replace(new RegExp(/'////b/' + $encode($count) + /'////b/', /'g/'), $keywords[$count]);
  413. }
  414. }
  415. return $packed;
  416. }';
  417. /*
  418. 'function($packed, $ascii, $count, $keywords, $encode, $decode) {
  419. while ($count--)
  420. if ($keywords[$count])
  421. $packed = $packed.replace(new RegExp(/'////b/' + $encode($count) + /'////b/', /'g/'), $keywords[$count]);
  422. return $packed;
  423. }';
  424. */
  425. // code-snippet inserted into the unpacker to speed up decoding
  426. const JSFUNCTION_decodeBody =
  427. //_decode = function() {
  428. // does the browser support String.replace where the
  429. // replacement value is a function?
  430. ' if (!/'/'.replace(/^/, String)) {
  431. // decode all the values we need
  432. while ($count--) {
  433. $decode[$encode($count)] = $keywords[$count] || $encode($count);
  434. }
  435. // global replacement function
  436. $keywords = [function ($encoded) {return $decode[$encoded]}];
  437. // generic match
  438. $encode = function () {return /'////w+/'};
  439. // reset the loop counter - we are now doing a global replace
  440. $count = 1;
  441. }
  442. ';
  443. //};
  444. /*
  445. ' if (!/'/'.replace(/^/, String)) {
  446. // decode all the values we need
  447. while ($count--) $decode[$encode($count)] = $keywords[$count] || $encode($count);
  448. // global replacement function
  449. $keywords = [function ($encoded) {return $decode[$encoded]}];
  450. // generic match
  451. $encode = function () {return/'////w+/'};
  452. // reset the loop counter - we are now doing a global replace
  453. $count = 1;
  454. }';
  455. */
  456. // zero encoding
  457. // characters: 0123456789
  458. const JSFUNCTION_encode10 =
  459. 'function($charCode) {
  460. return $charCode;
  461. }';//;';
  462. // inherent base36 support
  463. // characters: 0123456789abcdefghijklmnopqrstuvwxyz
  464. const JSFUNCTION_encode36 =
  465. 'function($charCode) {
  466. return $charCode.toString(36);
  467. }';//;';
  468. // hitch a ride on base36 and add the upper case alpha characters
  469. // characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  470. const JSFUNCTION_encode62 =
  471. 'function($charCode) {
  472. return ($charCode (($charCode = $charCode % _encoding) > 35 ? String.fromCharCode($charCode + 29) : $charCode.toString(36));
  473. }';
  474. // use high-ascii values
  475. // characters: ?¢£¤¥|§¨?a??-?ˉ°±23′μ?·?1o?????àá??????èéê?ìí??D?òó???×?ùú?üYT?àáa?????èéê?ìí??e?òó???÷?ùú?üyt
  476. const JSFUNCTION_encode95 =
  477. 'function($charCode) {
  478. return ($charCode String.fromCharCode($charCode % _encoding + 161);
  479. }';
  480. }
  481. class ParseMaster {
  482. public $ignoreCase = false;
  483. public $escapeChar = '';
  484. // constants
  485. const EXPRESSION = 0;
  486. const REPLACEMENT = 1;
  487. const LENGTH = 2;
  488. // used to determine nesting levels
  489. private $GROUPS = '///(/';//g
  490. private $SUB_REPLACE = '///$//d/';
  491. private $INDEXED = '/^//$//d+$/';
  492. private $TRIM = '/([/'"])//1//.(.*)//.//1//1$/';
  493. private $ESCAPE = '////./';//g
  494. private $QUOTE = '//'/';
  495. private $DELETED = '///x01[^//x01]*//x01/';//g
  496. public function add($expression, $replacement = '') {
  497. // count the number of sub-expressions
  498. // - add one because each pattern is itself a sub-expression
  499. $length = 1 + preg_match_all($this->GROUPS, $this->_internalEscape((string)$expression), $out);
  500. // treat only strings $replacement
  501. if (is_string($replacement)) {
  502. // does the pattern deal with sub-expressions?
  503. if (preg_match($this->SUB_REPLACE, $replacement)) {
  504. // a simple lookup? (e.g. "$2")
  505. if (preg_match($this->INDEXED, $replacement)) {
  506. // store the index (used for fast retrieval of matched strings)
  507. $replacement = (int)(substr($replacement, 1)) - 1;
  508. } else { // a complicated lookup (e.g. "Hello $2 $1")
  509. // build a function to do the lookup
  510. $quote = preg_match($this->QUOTE, $this->_internalEscape($replacement))
  511. ? '"' : "'";
  512. $replacement = array(
  513. 'fn' => '_backReferences',
  514. 'data' => array(
  515. 'replacement' => $replacement,
  516. 'length' => $length,
  517. 'quote' => $quote
  518. )
  519. );
  520. }
  521. }
  522. }
  523. // pass the modified arguments
  524. if (!emptyempty($expression)) $this->_add($expression, $replacement, $length);
  525. else $this->_add('/^$/', $replacement, $length);
  526. }
  527. public function exec($string) {
  528. // execute the global replacement
  529. $this->_escaped = array();
  530. // simulate the _patterns.toSTring of Dean
  531. $regexp = '/';
  532. foreach ($this->_patterns as $reg) {
  533. $regexp .= '(' . substr($reg[self::EXPRESSION], 1, -1) . ')|';
  534. }
  535. $regexp = substr($regexp, 0, -1) . '/';
  536. $regexp .= ($this->ignoreCase) ? 'i' : '';
  537. $string = $this->_escape($string, $this->escapeChar);
  538. $string = preg_replace_callback(
  539. $regexp,
  540. array(
  541. &$this,
  542. '_replacement'
  543. ),
  544. $string
  545. );
  546. $string = $this->_unescape($string, $this->escapeChar);
  547. return preg_replace($this->DELETED, '', $string);
  548. }
  549. public function reset() {
  550. // clear the patterns collection so that this object may be re-used
  551. $this->_patterns = array();
  552. }
  553. // private
  554. private $_escaped = array(); // escaped characters
  555. private $_patterns = array(); // patterns stored by index
  556. // create and add a new pattern to the patterns collection
  557. private function _add() {
  558. $arguments = func_get_args();
  559. $this->_patterns[] = $arguments;
  560. }
  561. // this is the global replace function (it's quite complicated)
  562. private function _replacement($arguments) {
  563. if (emptyempty($arguments)) return '';
  564. $i = 1; $j = 0;
  565. // loop through the patterns
  566. while (isset($this->_patterns[$j])) {
  567. $pattern = $this->_patterns[$j++];
  568. // do we have a result?
  569. if (isset($arguments[$i]) && ($arguments[$i] != '')) {
  570. $replacement = $pattern[self::REPLACEMENT];
  571. if (is_array($replacement) && isset($replacement['fn'])) {
  572. if (isset($replacement['data'])) $this->buffer = $replacement['data'];
  573. return call_user_func(array(&$this, $replacement['fn']), $arguments, $i);
  574. } elseif (is_int($replacement)) {
  575. return $arguments[$replacement + $i];
  576. }
  577. $delete = ($this->escapeChar == '' ||
  578. strpos($arguments[$i], $this->escapeChar) === false)
  579. ? '' : "/x01" . $arguments[$i] . "/x01";
  580. return $delete . $replacement;
  581. // skip over references to sub-expressions
  582. } else {
  583. $i += $pattern[self::LENGTH];
  584. }
  585. }
  586. }
  587. private function _backReferences($match, $offset) {
  588. $replacement = $this->buffer['replacement'];
  589. $quote = $this->buffer['quote'];
  590. $i = $this->buffer['length'];
  591. while ($i) {
  592. $replacement = str_replace('$'.$i--, $match[$offset + $i], $replacement);
  593. }
  594. return $replacement;
  595. }
  596. private function _replace_name($match, $offset){
  597. $length = strlen($match[$offset + 2]);
  598. $start = $length - max($length - strlen($match[$offset + 3]), 0);
  599. return substr($match[$offset + 1], $start, $length) . $match[$offset + 4];
  600. }
  601. private function _replace_encoded($match, $offset) {
  602. return $this->buffer[$match[$offset]];
  603. }
  604. // php : we cannot pass additional data to preg_replace_callback,
  605. // and we cannot use &$this in create_function, so let's go to lower level
  606. private $buffer;
  607. // encode escaped characters
  608. private function _escape($string, $escapeChar) {
  609. if ($escapeChar) {
  610. $this->buffer = $escapeChar;
  611. return preg_replace_callback(
  612. '///' . $escapeChar . '(.)' .'/',
  613. array(&$this, '_escapeBis'),
  614. $string
  615. );
  616. } else {
  617. return $string;
  618. }
  619. }
  620. private function _escapeBis($match) {
  621. $this->_escaped[] = $match[1];
  622. return $this->buffer;
  623. }
  624. // decode escaped characters
  625. private function _unescape($string, $escapeChar) {
  626. if ($escapeChar) {
  627. $regexp = '/'.'//'.$escapeChar.'/';
  628. $this->buffer = array('escapeChar'=> $escapeChar, 'i' => 0);
  629. return preg_replace_callback
  630. (
  631. $regexp,
  632. array(&$this, '_unescapeBis'),
  633. $string
  634. );
  635. } else {
  636. return $string;
  637. }
  638. }
  639. private function _unescapeBis() {
  640. if (isset($this->_escaped[$this->buffer['i']])
  641. && $this->_escaped[$this->buffer['i']] != '')
  642. {
  643. $temp = $this->_escaped[$this->buffer['i']];
  644. } else {
  645. $temp = '';
  646. }
  647. $this->buffer['i']++;
  648. return $this->buffer['escapeChar'] . $temp;
  649. }
  650. private function _internalEscape($string) {
  651. return preg_replace($this->ESCAPE, '', $string);
  652. }
  653. }
  654. ?>
复制代码

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完成,那是相当的方便!!



Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)