0
-/* 9 April 2008. version 1.1
0
- * This is the php version of the Dean Edwards JavaScript's Packer,
0
- * ParseMaster, version 1.0.2 (2005-08-19) Copyright 2005, Dean Edwards
0
- * a multi-pattern parser.
0
- * KNOWN BUG: erroneous behavior when using escapeChar with a replacement
0
- * value that is a function
0
- * packer, version 2.0.2 (2005-08-19) Copyright 2004-2005, Dean Edwards
0
- * License: http://creativecommons.org/licenses/LGPL/2.1/
0
- * Ported to PHP by Nicolas Martin.
0
- * ----------------------------------------------------------------------
0
- * 1.1 : correct a bug, '\0' packed then unpacked becomes '\'.
0
- * ----------------------------------------------------------------------
0
- * $myPacker = new JavaScriptPacker($script, 62, true, false);
0
- * $packed = $myPacker->pack();
0
- * $myPacker = new JavaScriptPacker($script, 'Normal', true, false);
0
- * $packed = $myPacker->pack();
0
- * $myPacker = new JavaScriptPacker($script);
0
- * $packed = $myPacker->pack();
0
- * params of the constructor :
0
- * $script: the JavaScript to pack, string.
0
- * $encoding: level of encoding, int or string :
0
- * 0,10,62,95 or 'None', 'Numeric', 'Normal', 'High ASCII'.
0
- * $fastDecode: include the fast decoder in the packed result, boolean.
0
- * $specialChars: if you are flagged your private and local variables
0
- * in the script, boolean.
0
- * The pack() method return the compressed JavasScript, as a string.
0
- * see http://dean.edwards.name/packer/usage/ for more information.
0
- * # need PHP 5 . Tested with PHP 5.1.2, 5.1.3, 5.1.4, 5.2.3
0
- * # The packed result may be different than with the Dean Edwards
0
- * version, but with the same length. The reason is that the PHP
0
- * function usort to sort array don't necessarily preserve the
0
- * original order of two equal member. The Javascript sort function
0
- * in fact preserve this order (but that's not require by the
0
- * ECMAScript standard). So the encoded keywords order can be
0
- * different in the two results.
0
- * # Be careful with the 'High ASCII' Level encoding if you use
0
- * UTF-8 in your files...
0
-class JavaScriptPacker {
0
- // validate parameters
0
- private $_script = '';
0
- private $_encoding = 62;
0
- private $_fastDecode = true;
0
- private $_specialChars = false;
0
- private $LITERAL_ENCODING = array(
0
- public function __construct($_script, $_encoding = 62, $_fastDecode = true, $_specialChars = false)
0
- $this->_script = $_script . "\n";
0
- if (array_key_exists($_encoding, $this->LITERAL_ENCODING))
0
- $_encoding = $this->LITERAL_ENCODING[$_encoding];
0
- $this->_encoding = min((int)$_encoding, 95);
0
- $this->_fastDecode = $_fastDecode;
0
- $this->_specialChars = $_specialChars;
0
- public function pack() {
0
- $this->_addParser('_basicCompression');
0
- if ($this->_specialChars)
0
- $this->_addParser('_encodeSpecialChars');
0
- $this->_addParser('_encodeKeywords');
0
- return $this->_pack($this->_script);
0
- // apply all parsing routines
0
- private function _pack($script) {
0
- for ($i = 0; isset($this->_parsers[$i]); $i++) {
0
- $script = call_user_func(array(&$this,$this->_parsers[$i]), $script);
0
- // keep a list of parsing functions, they'll be executed all at once
0
- private $_parsers = array();
0
- private function _addParser($parser) {
0
- $this->_parsers[] = $parser;
0
- // zero encoding - just removal of white space and comments
0
- private function _basicCompression($script) {
0
- $parser = new ParseMaster();
0
- $parser->escapeChar = '\\';
0
- $parser->add('/\'[^\'\\n\\r]*\'/', self::IGNORE);
0
- $parser->add('/"[^"\\n\\r]*"/', self::IGNORE);
0
- $parser->add('/\\/\\/[^\\n\\r]*[\\n\\r]/', ' ');
0
- $parser->add('/\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\//', ' ');
0
- // protect regular expressions
0
- $parser->add('/\\s+(\\/[^\\/\\n\\r\\*][^\\/\\n\\r]*\\/g?i?)/', '$2'); // IGNORE
0
- $parser->add('/[^\\w\\x24\\/\'"*)\\?:]\\/[^\\/\\n\\r\\*][^\\/\\n\\r]*\\/g?i?/', self::IGNORE);
0
- // remove: ;;; doSomething();
0
- if ($this->_specialChars) $parser->add('/;;;[^\\n\\r]+[\\n\\r]/');
0
- // remove redundant semi-colons
0
- $parser->add('/\\(;;\\)/', self::IGNORE); // protect for (;;) loops
0
- $parser->add('/;+\\s*([};])/', '$2');
0
- $script = $parser->exec($script);
0
- $parser->add('/(\\b|\\x24)\\s+(\\b|\\x24)/', '$2 $3');
0
- $parser->add('/([+\\-])\\s+([+\\-])/', '$2 $3');
0
- $parser->add('/\\s+/', '');
0
- return $parser->exec($script);
0
- private function _encodeSpecialChars($script) {
0
- $parser = new ParseMaster();
0
- // replace: $name -> n, $$name -> na
0
- $parser->add('/((\\x24+)([a-zA-Z$_]+))(\\d*)/',
0
- array('fn' => '_replace_name')
0
- // replace: _name -> _0, double-underscore (__name) is ignored
0
- $regexp = '/\\b_[A-Za-z\\d]\\w*/';
0
- // build the word list
0
- $keywords = $this->_analyze($script, $regexp, '_encodePrivate');
0
- $encoded = $keywords['encoded'];
0
- 'fn' => '_replace_encoded',
0
- return $parser->exec($script);
0
- private function _encodeKeywords($script) {
0
- // escape high-ascii values already in the script (i.e. in strings)
0
- if ($this->_encoding > 62)
0
- $script = $this->_escape95($script);
0
- $parser = new ParseMaster();
0
- $encode = $this->_getEncoder($this->_encoding);
0
- // for high-ascii, don't encode single character low-ascii
0
- $regexp = ($this->_encoding > 62) ? '/\\w\\w+/' : '/\\w+/';
0
- // build the word list
0
- $keywords = $this->_analyze($script, $regexp, $encode);
0
- $encoded = $keywords['encoded'];
0
- 'fn' => '_replace_encoded',
0
- if (empty($script)) return $script;
0
- //$res = $parser->exec($script);
0
- //$res = $this->_bootStrap($res, $keywords);
0
- return $this->_bootStrap($parser->exec($script), $keywords);
0
- private function _analyze($script, $regexp, $encode) {
0
- // retreive all words in the script
0
- preg_match_all($regexp, $script, $all);
0
- $_sorted = array(); // list of words sorted by frequency
0
- $_encoded = array(); // dictionary of word->encoding
0
- $_protected = array(); // instances of "protected" words
0
- $all = $all[0]; // simulate the javascript comportement of global match
0
- $unsorted = array(); // same list, not sorted
0
- $protected = array(); // "protected" words (dictionary of word->"word")
0
- $value = array(); // dictionary of charCode->encoding (eg. 256->ff)
0
- $this->_count = array(); // word->count
0
- $i = count($all); $j = 0; //$word = null;
0
- // count the occurrences - used for sorting later
0
- $word = '$' . $all[$i];
0
- if (!isset($this->_count[$word])) {
0
- $this->_count[$word] = 0;
0
- $unsorted[$j] = $word;
0
- // make a dictionary of all of the protected words in this script
0
- // these are words that might be mistaken for encoding
0
- //if (is_string($encode) && method_exists($this, $encode))
0
- $values[$j] = call_user_func(array(&$this, $encode), $j);
0
- $protected['$' . $values[$j]] = $j++;
0
- // increment the word counter
0
- $this->_count[$word]++;
0
- // prepare to sort the word list, first we must protect
0
- // words that are also used as codes. we assign them a code
0
- // equivalent to the word itself.
0
- // e.g. if "do" falls within our encoding range
0
- // then we store keywords["do"] = "do";
0
- // this avoids problems when decoding
0
- $i = count($unsorted);
0
- $word = $unsorted[--$i];
0
- if (isset($protected[$word]) /*!= null*/) {
0
- $_sorted[$protected[$word]] = substr($word, 1);
0
- $_protected[$protected[$word]] = true;
0
- $this->_count[$word] = 0;
0
- // sort the words by frequency
0
- // Note: the javascript and php version of sort can be different :
0
- // in php manual, usort :
0
- // " If two members compare as equal,
0
- // their order in the sorted array is undefined."
0
- // so the final packed script is different of the Dean's javascript version
0
- // the ECMAscript standard does not guarantee this behaviour,
0
- // and thus not all browsers (e.g. Mozilla versions dating back to at
0
- // least 2003) respect this.
0
- usort($unsorted, array(&$this, '_sortWords'));
0
- // because there are "protected" words in the list
0
- // we must add the sorted words around them
0
- if (!isset($_sorted[$i]))
0
- $_sorted[$i] = substr($unsorted[$j++], 1);
0
- $_encoded[$_sorted[$i]] = $values[$i];
0
- } while (++$i < count($unsorted));
0
- 'encoded' => $_encoded,
0
- 'protected' => $_protected);
0
- private $_count = array();
0
- private function _sortWords($match1, $match2) {
0
- return $this->_count[$match2] - $this->_count[$match1];
0
- // build the boot function used for loading and decoding
0
- private function _bootStrap($packed, $keywords) {
0
- $ENCODE = $this->_safeRegExp('$encode\\($count\\)');
0
- // $packed: the packed script
0
- $packed = "'" . $this->_escape($packed) . "'";
0
- // $ascii: base for encoding
0
- $ascii = min(count($keywords['sorted']), $this->_encoding);
0
- if ($ascii == 0) $ascii = 1;
0
- // $count: number of words contained in the script
0
- $count = count($keywords['sorted']);
0
- // $keywords: list of words contained in the script
0
- foreach ($keywords['protected'] as $i=>$value) {
0
- $keywords['sorted'][$i] = '';
0
- // convert from a string to an array
0
- ksort($keywords['sorted']);
0
- $keywords = "'" . implode('|',$keywords['sorted']) . "'.split('|')";
0
- $encode = ($this->_encoding > 62) ? '_encode95' : $this->_getEncoder($ascii);
0
- $encode = $this->_getJSFunction($encode);
0
- $encode = preg_replace('/_encoding/','$ascii', $encode);
0
- $encode = preg_replace('/arguments\\.callee/','$encode', $encode);
0
- $inline = '\\$count' . ($ascii > 10 ? '.toString(\\$ascii)' : '');
0
- // $decode: code snippet to speed up decoding
0
- if ($this->_fastDecode) {
0
- $decode = $this->_getJSFunction('_decodeBody');
0
- if ($this->_encoding > 62)
0
- $decode = preg_replace('/\\\\w/', '[\\xa1-\\xff]', $decode);
0
- // perform the encoding inline for lower ascii values
0
- $decode = preg_replace($ENCODE, $inline, $decode);
0
- // special case: when $count==0 there are no keywords. I want to keep
0
- // the basic shape of the unpacking funcion so i'll frig the code...
0
- $decode = preg_replace($this->_safeRegExp('($count)\\s*=\\s*1'), '$1=0', $decode, 1);
0
- $unpack = $this->_getJSFunction('_unpack');
0
- if ($this->_fastDecode) {
0
- $this->buffer = $decode;
0
- $unpack = preg_replace_callback('/\\{/', array(&$this, '_insertFastDecode'), $unpack, 1);
0
- $unpack = preg_replace('/"/', "'", $unpack);
0
- if ($this->_encoding > 62) { // high-ascii
0
- // get rid of the word-boundaries for regexp matches
0
- $unpack = preg_replace('/\'\\\\\\\\b\'\s*\\+|\\+\s*\'\\\\\\\\b\'/', '', $unpack);
0
- if ($ascii > 36 || $this->_encoding > 62 || $this->_fastDecode) {
0
- // insert the encode function
0
- $this->buffer = $encode;
0
- $unpack = preg_replace_callback('/\\{/', array(&$this, '_insertFastEncode'), $unpack, 1);
0
- // perform the encoding inline
0
- $unpack = preg_replace($ENCODE, $inline, $unpack);
0
- // pack the boot function too
0
- $unpackPacker = new JavaScriptPacker($unpack, 0, false, true);
0
- $unpack = $unpackPacker->pack();
0
- $params = array($packed, $ascii, $count, $keywords);
0
- if ($this->_fastDecode) {
0
- $params = implode(',', $params);
0
- return 'eval(' . $unpack . '(' . $params . "))\n";
0
- private function _insertFastDecode($match) {
0
- return '{' . $this->buffer . ';';
0
- private function _insertFastEncode($match) {
0
- return '{$encode=' . $this->buffer . ';';
0
- // mmm.. ..which one do i need ??
0
- private function _getEncoder($ascii) {
0
- return $ascii > 10 ? $ascii > 36 ? $ascii > 62 ?
0
- '_encode95' : '_encode62' : '_encode36' : '_encode10';
0
- // characters: 0123456789
0
- private function _encode10($charCode) {
0
- // inherent base36 support
0
- // characters: 0123456789abcdefghijklmnopqrstuvwxyz
0
- private function _encode36($charCode) {
0
- return base_convert($charCode, 10, 36);
0
- // hitch a ride on base36 and add the upper case alpha characters
0
- // characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0
- private function _encode62($charCode) {
0
- if ($charCode >= $this->_encoding) {
0
- $res = $this->_encode62((int)($charCode / $this->_encoding));
0
- $charCode = $charCode % $this->_encoding;
0
- return $res . chr($charCode + 29);
0
- return $res . base_convert($charCode, 10, 36);
0
- // use high-ascii values
0
- // characters: ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ
0
- private function _encode95($charCode) {
0
- if ($charCode >= $this->_encoding)
0
- $res = $this->_encode95($charCode / $this->_encoding);
0
- return $res . chr(($charCode % $this->_encoding) + 161);
0
- private function _safeRegExp($string) {
0
- return '/'.preg_replace('/\$/', '\\\$', $string).'/';
0
- private function _encodePrivate($charCode) {
0
- return "_" . $charCode;
0
- // protect characters used by the parser
0
- private function _escape($script) {
0
- return preg_replace('/([\\\\\'])/', '\\\$1', $script);
0
- // protect high-ascii characters already in the script
0
- private function _escape95($script) {
0
- return preg_replace_callback(
0
- array(&$this, '_escape95Bis'),
0
- private function _escape95Bis($match) {
0
- return '\x'.((string)dechex(ord($match)));
0
- private function _getJSFunction($aName) {
0
- if (defined('self::JSFUNCTION'.$aName))
0
- return constant('self::JSFUNCTION'.$aName);
0
- // JavaScript Functions used.
0
- // Note : In Dean's version, these functions are converted
0
- // with 'String(aFunctionName);'.
0
- // This internal conversion complete the original code, ex :
0
- // 'while (aBool) anAction();' is converted to
0
- // 'while (aBool) { anAction(); }'.
0
- // The JavaScript functions below are corrected.
0
- // unpacking function - this is the boot strap function
0
- // data extracted from this packing routine is passed to
0
- // this function when decoded in the target
0
- // NOTE ! : without the ';' final.
0
- const JSFUNCTION_unpack =
0
-'function($packed, $ascii, $count, $keywords, $encode, $decode) {
0
- if ($keywords[$count]) {
0
- $packed = $packed.replace(new RegExp(\'\\\\b\' + $encode($count) + \'\\\\b\', \'g\'), $keywords[$count]);
0
-'function($packed, $ascii, $count, $keywords, $encode, $decode) {
0
- if ($keywords[$count])
0
- $packed = $packed.replace(new RegExp(\'\\\\b\' + $encode($count) + \'\\\\b\', \'g\'), $keywords[$count]);
0
- // code-snippet inserted into the unpacker to speed up decoding
0
- const JSFUNCTION_decodeBody =
0
-//_decode = function() {
0
-// does the browser support String.replace where the
0
-// replacement value is a function?
0
-' if (!\'\'.replace(/^/, String)) {
0
- // decode all the values we need
0
- $decode[$encode($count)] = $keywords[$count] || $encode($count);
0
- // global replacement function
0
- $keywords = [function ($encoded) {return $decode[$encoded]}];
0
- $encode = function () {return \'\\\\w+\'};
0
- // reset the loop counter - we are now doing a global replace
0
-' if (!\'\'.replace(/^/, String)) {
0
- // decode all the values we need
0
- while ($count--) $decode[$encode($count)] = $keywords[$count] || $encode($count);
0
- // global replacement function
0
- $keywords = [function ($encoded) {return $decode[$encoded]}];
0
- $encode = function () {return\'\\\\w+\'};
0
- // reset the loop counter - we are now doing a global replace
0
- // characters: 0123456789
0
- const JSFUNCTION_encode10 =
0
- // inherent base36 support
0
- // characters: 0123456789abcdefghijklmnopqrstuvwxyz
0
- const JSFUNCTION_encode36 =
0
- return $charCode.toString(36);
0
- // hitch a ride on base36 and add the upper case alpha characters
0
- // characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0
- const JSFUNCTION_encode62 =
0
- return ($charCode < _encoding ? \'\' : arguments.callee(parseInt($charCode / _encoding))) +
0
- (($charCode = $charCode % _encoding) > 35 ? String.fromCharCode($charCode + 29) : $charCode.toString(36));
0
- // use high-ascii values
0
- // characters: ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ
0
- const JSFUNCTION_encode95 =
0
- return ($charCode < _encoding ? \'\' : arguments.callee($charCode / _encoding)) +
0
- String.fromCharCode($charCode % _encoding + 161);
0
- public $ignoreCase = false;
0
- public $escapeChar = '';
0
- const REPLACEMENT = 1;
0
- // used to determine nesting levels
0
- private $GROUPS = '/\\(/';//g
0
- private $SUB_REPLACE = '/\\$\\d/';
0
- private $INDEXED = '/^\\$\\d+$/';
0
- private $TRIM = '/([\'"])\\1\\.(.*)\\.\\1\\1$/';
0
- private $ESCAPE = '/\\\./';//g
0
- private $QUOTE = '/\'/';
0
- private $DELETED = '/\\x01[^\\x01]*\\x01/';//g
0
- public function add($expression, $replacement = '') {
0
- // count the number of sub-expressions
0
- // - add one because each pattern is itself a sub-expression
0
- $length = 1 + preg_match_all($this->GROUPS, $this->_internalEscape((string)$expression), $out);
0
- // treat only strings $replacement
0
- if (is_string($replacement)) {
0
- // does the pattern deal with sub-expressions?
0
- if (preg_match($this->SUB_REPLACE, $replacement)) {
0
- // a simple lookup? (e.g. "$2")
0
- if (preg_match($this->INDEXED, $replacement)) {
0
- // store the index (used for fast retrieval of matched strings)
0
- $replacement = (int)(substr($replacement, 1)) - 1;
0
- } else { // a complicated lookup (e.g. "Hello $2 $1")
0
- // build a function to do the lookup
0
- $quote = preg_match($this->QUOTE, $this->_internalEscape($replacement))
0
- 'fn' => '_backReferences',
0
- 'replacement' => $replacement,
0
- // pass the modified arguments
0
- if (!empty($expression)) $this->_add($expression, $replacement, $length);
0
- else $this->_add('/^$/', $replacement, $length);
0
- public function exec($string) {
0
- // execute the global replacement
0
- $this->_escaped = array();
0
- // simulate the _patterns.toSTring of Dean
0
- foreach ($this->_patterns as $reg) {
0
- $regexp .= '(' . substr($reg[self::EXPRESSION], 1, -1) . ')|';
0
- $regexp = substr($regexp, 0, -1) . '/';
0
- $regexp .= ($this->ignoreCase) ? 'i' : '';
0
- $string = $this->_escape($string, $this->escapeChar);
0
- $string = preg_replace_callback(
0
- $string = $this->_unescape($string, $this->escapeChar);
0
- return preg_replace($this->DELETED, '', $string);
0
- public function reset() {
0
- // clear the patterns collection so that this object may be re-used
0
- $this->_patterns = array();
0
- private $_escaped = array(); // escaped characters
0
- private $_patterns = array(); // patterns stored by index
0
- // create and add a new pattern to the patterns collection
0
- private function _add() {
0
- $arguments = func_get_args();
0
- $this->_patterns[] = $arguments;
0
- // this is the global replace function (it's quite complicated)
0
- private function _replacement($arguments) {
0
- if (empty($arguments)) return '';
0
- // loop through the patterns
0
- while (isset($this->_patterns[$j])) {
0
- $pattern = $this->_patterns[$j++];
0
- // do we have a result?
0
- if (isset($arguments[$i]) && ($arguments[$i] != '')) {
0
- $replacement = $pattern[self::REPLACEMENT];
0
- if (is_array($replacement) && isset($replacement['fn'])) {
0
- if (isset($replacement['data'])) $this->buffer = $replacement['data'];
0
- return call_user_func(array(&$this, $replacement['fn']), $arguments, $i);
0
- } elseif (is_int($replacement)) {
0
- return $arguments[$replacement + $i];
0
- $delete = ($this->escapeChar == '' ||
0
- strpos($arguments[$i], $this->escapeChar) === false)
0
- ? '' : "\x01" . $arguments[$i] . "\x01";
0
- return $delete . $replacement;
0
- // skip over references to sub-expressions
0
- $i += $pattern[self::LENGTH];
0
- private function _backReferences($match, $offset) {
0
- $replacement = $this->buffer['replacement'];
0
- $quote = $this->buffer['quote'];
0
- $i = $this->buffer['length'];
0
- $replacement = str_replace('$'.$i--, $match[$offset + $i], $replacement);
0
- private function _replace_name($match, $offset){
0
- $length = strlen($match[$offset + 2]);
0
- $start = $length - max($length - strlen($match[$offset + 3]), 0);
0
- return substr($match[$offset + 1], $start, $length) . $match[$offset + 4];
0
- private function _replace_encoded($match, $offset) {
0
- return $this->buffer[$match[$offset]];
0
- // php : we cannot pass additional data to preg_replace_callback,
0
- // and we cannot use &$this in create_function, so let's go to lower level
0
- // encode escaped characters
0
- private function _escape($string, $escapeChar) {
0
- $this->buffer = $escapeChar;
0
- return preg_replace_callback(
0
- '/\\' . $escapeChar . '(.)' .'/',
0
- array(&$this, '_escapeBis'),
0
- private function _escapeBis($match) {
0
- $this->_escaped[] = $match[1];
0
- // decode escaped characters
0
- private function _unescape($string, $escapeChar) {
0
- $regexp = '/'.'\\'.$escapeChar.'/';
0
- $this->buffer = array('escapeChar'=> $escapeChar, 'i' => 0);
0
- return preg_replace_callback
0
- array(&$this, '_unescapeBis'),
0
- private function _unescapeBis() {
0
- if (isset($this->_escaped[$this->buffer['i']])
0
- && $this->_escaped[$this->buffer['i']] != '')
0
- $temp = $this->_escaped[$this->buffer['i']];
0
- return $this->buffer['escapeChar'] . $temp;
0
- private function _internalEscape($string) {
0
- return preg_replace($this->ESCAPE, '', $string);