And while I'm at it: removed unused global declarations of $wgFeedClasses
[lhc/web/wiklou.git] / includes / StringUtils.php
1 <?php
2 /**
3 * A collection of static methods to play with strings.
4 */
5 class StringUtils {
6 /**
7 * Perform an operation equivalent to
8 *
9 * preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
10 *
11 * except that it's worst-case O(N) instead of O(N^2)
12 *
13 * Compared to delimiterReplace(), this implementation is fast but memory-
14 * hungry and inflexible. The memory requirements are such that I don't
15 * recommend using it on anything but guaranteed small chunks of text.
16 */
17 static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
18 $segments = explode( $startDelim, $subject );
19 $output = array_shift( $segments );
20 foreach ( $segments as $s ) {
21 $endDelimPos = strpos( $s, $endDelim );
22 if ( $endDelimPos === false ) {
23 $output .= $startDelim . $s;
24 } else {
25 $output .= $replace . substr( $s, $endDelimPos + strlen( $endDelim ) );
26 }
27 }
28 return $output;
29 }
30
31 /**
32 * Perform an operation equivalent to
33 *
34 * preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject )
35 *
36 * This implementation is slower than hungryDelimiterReplace but uses far less
37 * memory. The delimiters are literal strings, not regular expressions.
38 *
39 * @param string $flags Regular expression flags
40 */
41 # If the start delimiter ends with an initial substring of the end delimiter,
42 # e.g. in the case of C-style comments, the behaviour differs from the model
43 # regex. In this implementation, the end must share no characters with the
44 # start, so e.g. /*/ is not considered to be both the start and end of a
45 # comment. /*/xy/*/ is considered to be a single comment with contents /xy/.
46 static function delimiterReplaceCallback( $startDelim, $endDelim, $callback, $subject, $flags = '' ) {
47 $inputPos = 0;
48 $outputPos = 0;
49 $output = '';
50 $foundStart = false;
51 $encStart = preg_quote( $startDelim, '!' );
52 $encEnd = preg_quote( $endDelim, '!' );
53 $strcmp = strpos( $flags, 'i' ) === false ? 'strcmp' : 'strcasecmp';
54 $endLength = strlen( $endDelim );
55 $m = array();
56
57 while ( $inputPos < strlen( $subject ) &&
58 preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE, $inputPos ) )
59 {
60 $tokenOffset = $m[0][1];
61 if ( $m[1][0] != '' ) {
62 if ( $foundStart &&
63 $strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0 )
64 {
65 # An end match is present at the same location
66 $tokenType = 'end';
67 $tokenLength = $endLength;
68 } else {
69 $tokenType = 'start';
70 $tokenLength = strlen( $m[0][0] );
71 }
72 } elseif ( $m[2][0] != '' ) {
73 $tokenType = 'end';
74 $tokenLength = strlen( $m[0][0] );
75 } else {
76 throw new MWException( 'Invalid delimiter given to ' . __METHOD__ );
77 }
78
79 if ( $tokenType == 'start' ) {
80 $inputPos = $tokenOffset + $tokenLength;
81 # Only move the start position if we haven't already found a start
82 # This means that START START END matches outer pair
83 if ( !$foundStart ) {
84 # Found start
85 # Write out the non-matching section
86 $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
87 $outputPos = $tokenOffset;
88 $contentPos = $inputPos;
89 $foundStart = true;
90 }
91 } elseif ( $tokenType == 'end' ) {
92 if ( $foundStart ) {
93 # Found match
94 $output .= call_user_func( $callback, array(
95 substr( $subject, $outputPos, $tokenOffset + $tokenLength - $outputPos ),
96 substr( $subject, $contentPos, $tokenOffset - $contentPos )
97 ));
98 $foundStart = false;
99 } else {
100 # Non-matching end, write it out
101 $output .= substr( $subject, $inputPos, $tokenOffset + $tokenLength - $outputPos );
102 }
103 $inputPos = $outputPos = $tokenOffset + $tokenLength;
104 } else {
105 throw new MWException( 'Invalid delimiter given to ' . __METHOD__ );
106 }
107 }
108 if ( $outputPos < strlen( $subject ) ) {
109 $output .= substr( $subject, $outputPos );
110 }
111 return $output;
112 }
113
114 /*
115 * Perform an operation equivalent to
116 *
117 * preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
118 *
119 * @param string $startDelim Start delimiter regular expression
120 * @param string $endDelim End delimiter regular expression
121 * @param string $replace Replacement string. May contain $1, which will be
122 * replaced by the text between the delimiters
123 * @param string $subject String to search
124 * @return string The string with the matches replaced
125 */
126 static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
127 $replacer = new RegexlikeReplacer( $replace );
128 return self::delimiterReplaceCallback( $startDelim, $endDelim,
129 $replacer->cb(), $subject, $flags );
130 }
131
132 /**
133 * More or less "markup-safe" explode()
134 * Ignores any instances of the separator inside <...>
135 * @param string $separator
136 * @param string $text
137 * @return array
138 */
139 static function explodeMarkup( $separator, $text ) {
140 $placeholder = "\x00";
141
142 // Remove placeholder instances
143 $text = str_replace( $placeholder, '', $text );
144
145 // Replace instances of the separator inside HTML-like tags with the placeholder
146 $replacer = new DoubleReplacer( $separator, $placeholder );
147 $cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
148
149 // Explode, then put the replaced separators back in
150 $items = explode( $separator, $cleaned );
151 foreach( $items as $i => $str ) {
152 $items[$i] = str_replace( $placeholder, $separator, $str );
153 }
154
155 return $items;
156 }
157
158 /**
159 * Escape a string to make it suitable for inclusion in a preg_replace()
160 * replacement parameter.
161 *
162 * @param string $string
163 * @return string
164 */
165 static function escapeRegexReplacement( $string ) {
166 $string = str_replace( '\\', '\\\\', $string );
167 $string = str_replace( '$', '\\$', $string );
168 return $string;
169 }
170
171 /**
172 * Workalike for explode() with limited memory usage.
173 * Returns an Iterator
174 */
175 static function explode( $separator, $subject ) {
176 if ( substr_count( $subject, $separator ) > 1000 ) {
177 return new ExplodeIterator( $separator, $subject );
178 } else {
179 return new ArrayIterator( explode( $separator, $subject ) );
180 }
181 }
182
183 /**
184 * Workalike for preg_split() with limited memory usage.
185 * Returns an Iterator
186 */
187 static function preg_split( $pattern, $subject, $limit = -1, $flags = 0 ) {
188 return new PregSplitIterator( $pattern, $subject, $limit, $flags );
189 }
190 }
191
192 /**
193 * Base class for "replacers", objects used in preg_replace_callback() and
194 * StringUtils::delimiterReplaceCallback()
195 */
196 class Replacer {
197 function cb() {
198 return array( &$this, 'replace' );
199 }
200 }
201
202 /**
203 * Class to replace regex matches with a string similar to that used in preg_replace()
204 */
205 class RegexlikeReplacer extends Replacer {
206 var $r;
207 function __construct( $r ) {
208 $this->r = $r;
209 }
210
211 function replace( $matches ) {
212 $pairs = array();
213 foreach ( $matches as $i => $match ) {
214 $pairs["\$$i"] = $match;
215 }
216 return strtr( $this->r, $pairs );
217 }
218
219 }
220
221 /**
222 * Class to perform secondary replacement within each replacement string
223 */
224 class DoubleReplacer extends Replacer {
225 function __construct( $from, $to, $index = 0 ) {
226 $this->from = $from;
227 $this->to = $to;
228 $this->index = $index;
229 }
230
231 function replace( $matches ) {
232 return str_replace( $this->from, $this->to, $matches[$this->index] );
233 }
234 }
235
236 /**
237 * Class to perform replacement based on a simple hashtable lookup
238 */
239 class HashtableReplacer extends Replacer {
240 var $table, $index;
241
242 function __construct( $table, $index = 0 ) {
243 $this->table = $table;
244 $this->index = $index;
245 }
246
247 function replace( $matches ) {
248 return $this->table[$matches[$this->index]];
249 }
250 }
251
252 /**
253 * Replacement array for FSS with fallback to strtr()
254 * Supports lazy initialisation of FSS resource
255 */
256 class ReplacementArray {
257 /*mostly private*/ var $data = false;
258 /*mostly private*/ var $fss = false;
259
260 /**
261 * Create an object with the specified replacement array
262 * The array should have the same form as the replacement array for strtr()
263 */
264 function __construct( $data = array() ) {
265 $this->data = $data;
266 }
267
268 function __sleep() {
269 return array( 'data' );
270 }
271
272 function __wakeup() {
273 $this->fss = false;
274 }
275
276 /**
277 * Set the whole replacement array at once
278 */
279 function setArray( $data ) {
280 $this->data = $data;
281 $this->fss = false;
282 }
283
284 function getArray() {
285 return $this->data;
286 }
287
288 /**
289 * Set an element of the replacement array
290 */
291 function setPair( $from, $to ) {
292 $this->data[$from] = $to;
293 $this->fss = false;
294 }
295
296 function mergeArray( $data ) {
297 $this->data = array_merge( $this->data, $data );
298 $this->fss = false;
299 }
300
301 function merge( $other ) {
302 $this->data = array_merge( $this->data, $other->data );
303 $this->fss = false;
304 }
305
306 function removePair( $from ) {
307 unset($this->data[$from]);
308 $this->fss = false;
309 }
310
311 function removeArray( $data ) {
312 foreach( $data as $from => $to )
313 $this->removePair( $from );
314 $this->fss = false;
315 }
316
317 function replace( $subject ) {
318 if ( function_exists( 'fss_prep_replace' ) ) {
319 wfProfileIn( __METHOD__.'-fss' );
320 if ( $this->fss === false ) {
321 $this->fss = fss_prep_replace( $this->data );
322 }
323 $result = fss_exec_replace( $this->fss, $subject );
324 wfProfileOut( __METHOD__.'-fss' );
325 } else {
326 wfProfileIn( __METHOD__.'-strtr' );
327 $result = strtr( $subject, $this->data );
328 wfProfileOut( __METHOD__.'-strtr' );
329 }
330 return $result;
331 }
332 }
333
334 /**
335 * An iterator which works exactly like:
336 *
337 * foreach ( explode( $delim, $s ) as $element ) {
338 * ...
339 * }
340 *
341 * Except it doesn't use 193 byte per element
342 */
343 class ExplodeIterator implements Iterator {
344 // The subject string
345 var $subject, $subjectLength;
346
347 // The delimiter
348 var $delim, $delimLength;
349
350 // The position of the start of the line
351 var $curPos;
352
353 // The position after the end of the next delimiter
354 var $endPos;
355
356 // The current token
357 var $current;
358
359 /**
360 * Construct a DelimIterator
361 */
362 function __construct( $delim, $s ) {
363 $this->subject = $s;
364 $this->delim = $delim;
365
366 // Micro-optimisation (theoretical)
367 $this->subjectLength = strlen( $s );
368 $this->delimLength = strlen( $delim );
369
370 $this->rewind();
371 }
372
373 function rewind() {
374 $this->curPos = 0;
375 $this->endPos = strpos( $this->subject, $this->delim );
376 $this->refreshCurrent();
377 }
378
379
380 function refreshCurrent() {
381 if ( $this->curPos === false ) {
382 $this->current = false;
383 } elseif ( $this->curPos >= $this->subjectLength ) {
384 $this->current = '';
385 } elseif ( $this->endPos === false ) {
386 $this->current = substr( $this->subject, $this->curPos );
387 } else {
388 $this->current = substr( $this->subject, $this->curPos, $this->endPos - $this->curPos );
389 }
390 }
391
392 function current() {
393 return $this->current;
394 }
395
396 function key() {
397 return $this->curPos;
398 }
399
400 function next() {
401 if ( $this->endPos === false ) {
402 $this->curPos = false;
403 } else {
404 $this->curPos = $this->endPos + $this->delimLength;
405 if ( $this->curPos >= $this->subjectLength ) {
406 $this->endPos = false;
407 } else {
408 $this->endPos = strpos( $this->subject, $this->delim, $this->curPos );
409 }
410 }
411 $this->refreshCurrent();
412 return $this->current;
413 }
414
415 function valid() {
416 return $this->curPos !== false;
417 }
418 }
419
420
421 /**
422 * An iterator which works exactly like:
423 *
424 * foreach ( preg_split( $pattern, $s, $limit, $flags ) as $element ) {
425 * ...
426 * }
427 *
428 * Except it doesn't use huge amounts of memory when $limit is -1
429 *
430 * The flag PREG_SPLIT_OFFSET_CAPTURE isn't supported.
431 */
432 class PregSplitIterator implements Iterator {
433 // The subject string
434 var $pattern, $subject, $originalLimit, $flags;
435
436 // The last extracted group of items.
437 var $smallArray;
438
439 // The position on the iterator.
440 var $curPos;
441
442 const MAX_LIMIT = 100;
443
444 /**
445 * Construct a PregSplitIterator
446 */
447 function __construct( $pattern, $s, $limit, $flags) {
448 $this->pattern = $pattern;
449 $this->subject = $s;
450 $this->originalLimit = $limit;
451 $this->flags = $flags;
452
453 $this->rewind();
454 }
455
456 private function effectiveLimit() {
457 if ($this->originalLimit == -1) {
458 return self::MAX_LIMIT + 1;
459 } else if ($this->limit > self::MAX_LIMIT) {
460 $this->limit -= self::MAX_LIMIT;
461 return self::MAX_LIMIT + 1;
462 } else {
463 $old = $this->limit;
464 $this->limit = 0;
465 return $old;
466 }
467 }
468
469 function rewind() {
470 $this->curPos = 0;
471 $this->limit = $this->originalLimit;
472 if ($this->limit == -1) $this->limit = self::MAX_LIMIT;
473 $this->smallArray = preg_split( $this->pattern, $this->subject, $this->effectiveLimit(), $this->flags);
474 }
475
476 function current() {
477 return $this->smallArray[$this->curPos % self::MAX_LIMIT];
478 }
479
480 function key() {
481 return $this->curPos;
482 }
483
484 function next() {
485 $this->curPos++;
486 if ( $this->curPos % self::MAX_LIMIT == 0 ) {
487 # Last item contains the rest unsplitted.
488 if ($this->limit > 0) {
489 $this->smallArray = preg_split( $this->pattern, $this->smallArray[self::MAX_LIMIT], $this->effectiveLimit(), $this->flags);
490 }
491 }
492 return;
493 }
494
495 function valid() {
496 return $this->curPos % self::MAX_LIMIT < count($this->smallArray);
497 }
498 }