PluginProbe
WP Coder – Insert & Manage Code Snippets / 2.3.2
WP Coder – Insert & Manage Code Snippets v2.3.2
4.5.1 1.1 2.3.1 2.3.2 2.4.1 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.1 3.1.1 3.2 3.2.1 3.3 3.4 3.5 3.5.1 All 39 releases
wp-coder / includes / class-js-packer.php

class-js-packer.php in WP Coder – Insert & Manage Code Snippets 2.3.2, at includes/class-js-packer.php

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