Advertisement
pulsorock

Packer JavaScript en PHP

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