]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/StringUtils.php
MediaWiki 1.16.2
[autoinstallsdev/mediawiki.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                                 # Only move the start position if we haven't already found a start
81                                 # This means that START START END matches outer pair
82                                 if ( !$foundStart ) {
83                                         # Found start
84                                         $inputPos = $tokenOffset + $tokenLength;
85                                         # Write out the non-matching section
86                                         $output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
87                                         $outputPos = $tokenOffset;
88                                         $contentPos = $inputPos;
89                                         $foundStart = true;
90                                 } else {
91                                         # Move the input position past the *first character* of START,
92                                         # to protect against missing END when it overlaps with START
93                                         $inputPos = $tokenOffset + 1;
94                                 }
95                         } elseif ( $tokenType == 'end' ) {
96                                 if ( $foundStart ) {
97                                         # Found match
98                                         $output .= call_user_func( $callback, array(
99                                                 substr( $subject, $outputPos, $tokenOffset + $tokenLength - $outputPos ),
100                                                 substr( $subject, $contentPos, $tokenOffset - $contentPos )
101                                         ));
102                                         $foundStart = false;
103                                 } else {
104                                         # Non-matching end, write it out
105                                         $output .= substr( $subject, $inputPos, $tokenOffset + $tokenLength - $outputPos );
106                                 }
107                                 $inputPos = $outputPos = $tokenOffset + $tokenLength;
108                         } else {
109                                 throw new MWException( 'Invalid delimiter given to ' . __METHOD__ );
110                         }
111                 }
112                 if ( $outputPos < strlen( $subject ) ) {
113                         $output .= substr( $subject, $outputPos );
114                 }
115                 return $output;
116         }
117
118         /*
119          * Perform an operation equivalent to
120          *
121          *   preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject )
122          *
123          * @param string $startDelim Start delimiter regular expression
124          * @param string $endDelim End delimiter regular expression
125          * @param string $replace Replacement string. May contain $1, which will be
126          *               replaced by the text between the delimiters
127          * @param string $subject String to search
128          * @return string The string with the matches replaced
129          */
130         static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
131                 $replacer = new RegexlikeReplacer( $replace );
132                 return self::delimiterReplaceCallback( $startDelim, $endDelim,
133                         $replacer->cb(), $subject, $flags );
134         }
135
136         /**
137          * More or less "markup-safe" explode()
138          * Ignores any instances of the separator inside <...>
139          * @param string $separator
140          * @param string $text
141          * @return array
142          */
143         static function explodeMarkup( $separator, $text ) {
144                 $placeholder = "\x00";
145
146                 // Remove placeholder instances
147                 $text = str_replace( $placeholder, '', $text );
148
149                 // Replace instances of the separator inside HTML-like tags with the placeholder
150                 $replacer = new DoubleReplacer( $separator, $placeholder );
151                 $cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
152
153                 // Explode, then put the replaced separators back in
154                 $items = explode( $separator, $cleaned );
155                 foreach( $items as $i => $str ) {
156                         $items[$i] = str_replace( $placeholder, $separator, $str );
157                 }
158
159                 return $items;
160         }
161
162         /**
163          * Escape a string to make it suitable for inclusion in a preg_replace()
164          * replacement parameter.
165          *
166          * @param string $string
167          * @return string
168          */
169         static function escapeRegexReplacement( $string ) {
170                 $string = str_replace( '\\', '\\\\', $string );
171                 $string = str_replace( '$', '\\$', $string );
172                 return $string;
173         }
174
175         /**
176          * Workalike for explode() with limited memory usage.
177          * Returns an Iterator
178          */
179         static function explode( $separator, $subject ) {
180                 if ( substr_count( $subject, $separator ) > 1000 ) {
181                         return new ExplodeIterator( $separator, $subject );
182                 } else {
183                         return new ArrayIterator( explode( $separator, $subject ) );
184                 }
185         }
186 }
187
188 /**
189  * Base class for "replacers", objects used in preg_replace_callback() and
190  * StringUtils::delimiterReplaceCallback()
191  */
192 class Replacer {
193         function cb() {
194                 return array( &$this, 'replace' );
195         }
196 }
197
198 /**
199  * Class to replace regex matches with a string similar to that used in preg_replace()
200  */
201 class RegexlikeReplacer extends Replacer {
202         var $r;
203         function __construct( $r ) {
204                 $this->r = $r;
205         }
206
207         function replace( $matches ) {
208                 $pairs = array();
209                 foreach ( $matches as $i => $match ) {
210                         $pairs["\$$i"] = $match;
211                 }
212                 return strtr( $this->r, $pairs );
213         }
214
215 }
216
217 /**
218  * Class to perform secondary replacement within each replacement string
219  */
220 class DoubleReplacer extends Replacer {
221         function __construct( $from, $to, $index = 0 ) {
222                 $this->from = $from;
223                 $this->to = $to;
224                 $this->index = $index;
225         }
226
227         function replace( $matches ) {
228                 return str_replace( $this->from, $this->to, $matches[$this->index] );
229         }
230 }
231
232 /**
233  * Class to perform replacement based on a simple hashtable lookup
234  */
235 class HashtableReplacer extends Replacer {
236         var $table, $index;
237
238         function __construct( $table, $index = 0 ) {
239                 $this->table = $table;
240                 $this->index = $index;
241         }
242
243         function replace( $matches ) {
244                 return $this->table[$matches[$this->index]];
245         }
246 }
247
248 /**
249  * Replacement array for FSS with fallback to strtr()
250  * Supports lazy initialisation of FSS resource
251  */
252 class ReplacementArray {
253         /*mostly private*/ var $data = false;
254         /*mostly private*/ var $fss = false;
255
256         /**
257          * Create an object with the specified replacement array
258          * The array should have the same form as the replacement array for strtr()
259          */
260         function __construct( $data = array() ) {
261                 $this->data = $data;
262         }
263
264         function __sleep() {
265                 return array( 'data' );
266         }
267
268         function __wakeup() {
269                 $this->fss = false;
270         }
271
272         /**
273          * Set the whole replacement array at once
274          */
275         function setArray( $data ) {
276                 $this->data = $data;
277                 $this->fss = false;
278         }
279
280         function getArray() {
281                 return $this->data;
282         }
283
284         /**
285          * Set an element of the replacement array
286          */
287         function setPair( $from, $to ) {
288                 $this->data[$from] = $to;
289                 $this->fss = false;
290         }
291
292         function mergeArray( $data ) {
293                 $this->data = array_merge( $this->data, $data );
294                 $this->fss = false;
295         }
296
297         function merge( $other ) {
298                 $this->data = array_merge( $this->data, $other->data );
299                 $this->fss = false;
300         }
301
302         function removePair( $from ) {
303                 unset($this->data[$from]);
304                 $this->fss = false;
305         }
306
307         function removeArray( $data ) {
308                 foreach( $data as $from => $to )
309                         $this->removePair( $from );
310                 $this->fss = false;
311         }
312
313         function replace( $subject ) {
314                 if ( function_exists( 'fss_prep_replace' ) ) {
315                         wfProfileIn( __METHOD__.'-fss' );
316                         if ( $this->fss === false ) {
317                                 $this->fss = fss_prep_replace( $this->data );
318                         }
319                         $result = fss_exec_replace( $this->fss, $subject );
320                         wfProfileOut( __METHOD__.'-fss' );
321                 } else {
322                         wfProfileIn( __METHOD__.'-strtr' );
323                         $result = strtr( $subject, $this->data );
324                         wfProfileOut( __METHOD__.'-strtr' );
325                 }
326                 return $result;
327         }
328 }
329
330 /**
331  * An iterator which works exactly like:
332  * 
333  * foreach ( explode( $delim, $s ) as $element ) {
334  *    ...
335  * }
336  *
337  * Except it doesn't use 193 byte per element
338  */
339 class ExplodeIterator implements Iterator {
340         // The subject string
341         var $subject, $subjectLength;
342
343         // The delimiter
344         var $delim, $delimLength;
345
346         // The position of the start of the line
347         var $curPos;
348
349         // The position after the end of the next delimiter
350         var $endPos;
351
352         // The current token
353         var $current;
354
355         /** 
356          * Construct a DelimIterator
357          */
358         function __construct( $delim, $s ) {
359                 $this->subject = $s;
360                 $this->delim = $delim;
361
362                 // Micro-optimisation (theoretical)
363                 $this->subjectLength = strlen( $s );
364                 $this->delimLength = strlen( $delim );
365
366                 $this->rewind();
367         }
368
369         function rewind() {
370                 $this->curPos = 0;
371                 $this->endPos = strpos( $this->subject, $this->delim );
372                 $this->refreshCurrent();
373         }
374
375
376         function refreshCurrent() {
377                 if ( $this->curPos === false ) {
378                         $this->current = false;
379                 } elseif ( $this->curPos >= $this->subjectLength ) {
380                         $this->current = '';
381                 } elseif ( $this->endPos === false ) {
382                         $this->current = substr( $this->subject, $this->curPos );
383                 } else {
384                         $this->current = substr( $this->subject, $this->curPos, $this->endPos - $this->curPos );
385                 }
386         }
387
388         function current() {
389                 return $this->current;
390         }
391
392         function key() {
393                 return $this->curPos;
394         }
395
396         function next() {
397                 if ( $this->endPos === false ) {
398                         $this->curPos = false;
399                 } else {
400                         $this->curPos = $this->endPos + $this->delimLength;
401                         if ( $this->curPos >= $this->subjectLength ) {
402                                 $this->endPos = false;
403                         } else {
404                                 $this->endPos = strpos( $this->subject, $this->delim, $this->curPos );
405                         }
406                 }
407                 $this->refreshCurrent();
408                 return $this->current;
409         }
410
411         function valid() {
412                 return $this->curPos !== false;
413         }
414 }
415