PluginProbe
Float menu – awesome floating side menu / 3.3.1
Float menu – awesome floating side menu v3.3.1
7.2.5 trunk 2.1 2.2 3.0.1 3.1 3.2.2 3.3.1 3.5 3.5.1 3.5.2 3.5.3. 3.5.4 4.0 4.1 4.1.1 4.2 4.3 4.3.1 4.3.2 5.0 5.0.1 5.0.2 5.0.3 5.1 All 57 releases
float-menu / includes / class-js-packer.php

class-js-packer.php in Float menu – awesome floating side menu 3.3.1, at includes/class-js-packer.php

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