PluginProbe
WP Coder – Insert & Manage Code Snippets / 1.1
WP Coder – Insert & Manage Code Snippets v1.1
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 / include / class / packer.php

packer.php in WP Coder – Insert & Manage Code Snippets 1.1, at include/class/packer.php

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