Advertisement
Guest User

Untitled

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