4 * Global functions used everywhere
9 * Some globals and requires needed
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
16 $wgNumberOfArticles = -1; # Unset
18 * Total number of views
19 * @global integer $wgTotalViews
23 * Total number of edits
24 * @global integer $wgTotalEdits
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.php' );
33 require_once( 'XmlFunctions.php' );
36 * Compatibility functions
37 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
38 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
39 * such as the new autoglobals.
41 if( !function_exists('iconv') ) {
42 # iconv support is not in the default configuration and so may not be present.
43 # Assume will only ever use utf-8 and iso-8859-1.
44 # This will *not* work in all circumstances.
45 function iconv( $from, $to, $string ) {
46 if(strcasecmp( $from, $to ) == 0) return $string;
47 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
48 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
53 if( !function_exists('file_get_contents') ) {
54 # Exists in PHP 4.3.0+
55 function file_get_contents( $filename ) {
56 return implode( '', file( $filename ) );
60 if( !function_exists('is_a') ) {
61 # Exists in PHP 4.2.0+
62 function is_a( $object, $class_name ) {
64 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
65 is_subclass_of( $object, $class_name );
69 # UTF-8 substr function based on a PHP manual comment
70 if ( !function_exists( 'mb_substr' ) ) {
71 function mb_substr( $str, $start ) {
72 preg_match_all( '/./us', $str, $ar );
74 if( func_num_args() >= 3 ) {
75 $end = func_get_arg( 2 );
76 return join( '', array_slice( $ar[0], $start, $end ) );
78 return join( '', array_slice( $ar[0], $start ) );
83 if( !function_exists( 'floatval' ) ) {
85 * First defined in PHP 4.2.0
89 function floatval( $var ) {
94 if ( !function_exists( 'array_diff_key' ) ) {
96 * Exists in PHP 5.1.0+
97 * Not quite compatible, two-argument version only
98 * Null values will cause problems due to this use of isset()
100 function array_diff_key( $left, $right ) {
102 foreach ( $left as $key => $value ) {
103 if ( isset( $right[$key] ) ) {
104 unset( $result[$key] );
113 * Wrapper for clone() for PHP 4, for the moment.
114 * PHP 5 won't let you declare a 'clone' function, even conditionally,
115 * so it has to be a wrapper with a different name.
117 function wfClone( $object ) {
118 // WARNING: clone() is not a function in PHP 5, so function_exists fails.
119 if( version_compare( PHP_VERSION
, '5.0' ) < 0 ) {
122 return clone( $object );
127 * Where as we got a random seed
128 * @var bool $wgTotalViews
130 $wgRandomSeeded = false;
133 * Seed Mersenne Twister
134 * Only necessary in PHP < 4.2.0
138 function wfSeedRandom() {
139 global $wgRandomSeeded;
141 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
142 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
144 $wgRandomSeeded = true;
149 * Get a random decimal value between 0 and 1, in a way
150 * not likely to give duplicate values for any realistic
151 * number of articles.
155 function wfRandom() {
156 # The maximum random value is "only" 2^31-1, so get two random
157 # values to reduce the chance of dupes
158 $max = mt_getrandmax();
159 $rand = number_format( (mt_rand() * $max +
mt_rand())
160 / $max / $max, 12, '.', '' );
165 * We want / and : to be included as literal characters in our title URLs.
166 * %2F in the page titles seems to fatally break for some reason.
171 function wfUrlencode ( $s ) {
172 $s = urlencode( $s );
173 $s = preg_replace( '/%3[Aa]/', ':', $s );
174 $s = preg_replace( '/%2[Ff]/', '/', $s );
180 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
181 * In normal operation this is a NOP.
183 * Controlling globals:
184 * $wgDebugLogFile - points to the log file
185 * $wgProfileOnly - if set, normal debug messages will not be recorded.
186 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
187 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
189 * @param string $text
190 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
192 function wfDebug( $text, $logonly = false ) {
193 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
195 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
196 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
200 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
201 $wgOut->debug( $text );
203 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
204 # Strip unprintables; they can switch terminal modes when binary data
205 # gets dumped, which is pretty annoying.
206 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
207 @error_log
( $text, 3, $wgDebugLogFile );
212 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
213 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
215 * @param string $logGroup
216 * @param string $text
217 * @param bool $public Whether to log the event in the public log if no private
218 * log file is specified, (default true)
220 function wfDebugLog( $logGroup, $text, $public = true ) {
221 global $wgDebugLogGroups, $wgDBname;
222 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
223 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
224 $time = wfTimestamp( TS_DB
);
225 @error_log
( "$time $wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
226 } else if ( $public === true ) {
227 wfDebug( $text, true );
232 * Log for database errors
233 * @param string $text Database error message.
235 function wfLogDBError( $text ) {
236 global $wgDBerrorLog;
237 if ( $wgDBerrorLog ) {
238 $host = trim(`hostname`
);
239 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
240 error_log( $text, 3, $wgDBerrorLog );
247 function logProfilingData() {
248 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
249 global $wgProfiling, $wgUser;
252 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
253 $start = (float)$sec +
(float)$usec;
254 $elapsed = $now - $start;
255 if ( $wgProfiling ) {
256 $prof = wfGetProfilingOutput( $start, $elapsed );
258 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
259 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
260 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
261 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
262 if( !empty( $_SERVER['HTTP_FROM'] ) )
263 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
265 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
266 if( is_object($wgUser) && $wgUser->isAnon() )
268 $log = sprintf( "%s\t%04.3f\t%s\n",
269 gmdate( 'YmdHis' ), $elapsed,
270 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
271 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
272 error_log( $log . $prof, 3, $wgDebugLogFile );
278 * Check if the wiki read-only lock file is present. This can be used to lock
279 * off editing functions, but doesn't guarantee that the database will not be
283 function wfReadOnly() {
284 global $wgReadOnlyFile, $wgReadOnly;
286 if ( !is_null( $wgReadOnly ) ) {
287 return (bool)$wgReadOnly;
289 if ( '' == $wgReadOnlyFile ) {
292 // Set $wgReadOnly for faster access next time
293 if ( is_file( $wgReadOnlyFile ) ) {
294 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
298 return (bool)$wgReadOnly;
303 * Get a message from anywhere, for the current user language.
305 * Use wfMsgForContent() instead if the message should NOT
306 * change depending on the user preferences.
308 * Note that the message may contain HTML, and is therefore
309 * not safe for insertion anywhere. Some functions such as
310 * addWikiText will do the escaping for you. Use wfMsgHtml()
311 * if you need an escaped message.
313 * @param string lookup key for the message, usually
314 * defined in languages/Language.php
316 function wfMsg( $key ) {
317 $args = func_get_args();
318 array_shift( $args );
319 return wfMsgReal( $key, $args, true );
323 * Same as above except doesn't transform the message
325 function wfMsgNoTrans( $key ) {
326 $args = func_get_args();
327 array_shift( $args );
328 return wfMsgReal( $key, $args, true, false );
332 * Get a message from anywhere, for the current global language
333 * set with $wgLanguageCode.
335 * Use this if the message should NOT change dependent on the
336 * language set in the user's preferences. This is the case for
337 * most text written into logs, as well as link targets (such as
338 * the name of the copyright policy page). Link titles, on the
339 * other hand, should be shown in the UI language.
341 * Note that MediaWiki allows users to change the user interface
342 * language in their preferences, but a single installation
343 * typically only contains content in one language.
345 * Be wary of this distinction: If you use wfMsg() where you should
346 * use wfMsgForContent(), a user of the software may have to
347 * customize over 70 messages in order to, e.g., fix a link in every
350 * @param string lookup key for the message, usually
351 * defined in languages/Language.php
353 function wfMsgForContent( $key ) {
354 global $wgForceUIMsgAsContentMsg;
355 $args = func_get_args();
356 array_shift( $args );
358 if( is_array( $wgForceUIMsgAsContentMsg ) &&
359 in_array( $key, $wgForceUIMsgAsContentMsg ) )
361 return wfMsgReal( $key, $args, true, $forcontent );
365 * Same as above except doesn't transform the message
367 function wfMsgForContentNoTrans( $key ) {
368 global $wgForceUIMsgAsContentMsg;
369 $args = func_get_args();
370 array_shift( $args );
372 if( is_array( $wgForceUIMsgAsContentMsg ) &&
373 in_array( $key, $wgForceUIMsgAsContentMsg ) )
375 return wfMsgReal( $key, $args, true, $forcontent, false );
379 * Get a message from the language file, for the UI elements
381 function wfMsgNoDB( $key ) {
382 $args = func_get_args();
383 array_shift( $args );
384 return wfMsgReal( $key, $args, false );
388 * Get a message from the language file, for the content
390 function wfMsgNoDBForContent( $key ) {
391 global $wgForceUIMsgAsContentMsg;
392 $args = func_get_args();
393 array_shift( $args );
395 if( is_array( $wgForceUIMsgAsContentMsg ) &&
396 in_array( $key, $wgForceUIMsgAsContentMsg ) )
398 return wfMsgReal( $key, $args, false, $forcontent );
403 * Really get a message
405 function wfMsgReal( $key, $args, $useDB, $forContent=false, $transform = true ) {
406 $fname = 'wfMsgReal';
408 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
409 $message = wfMsgReplaceArgs( $message, $args );
414 * This function provides the message source for messages to be edited which are *not* stored in the database
417 function wfMsgWeirdKey ( $key ) {
418 $subsource = str_replace ( ' ' , '_' , $key ) ;
419 $source = wfMsg ( $subsource ) ;
420 if ( $source == "<{$subsource}>" ) {
421 # Try again with first char lower case
422 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
423 $source = wfMsg ( $subsource ) ;
425 if ( $source == "<{$subsource}>" ) {
426 # Didn't work either, return blank text
433 * Fetch a message string value, but don't replace any keys yet.
436 * @param bool $forContent
440 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
441 global $wgParser, $wgMsgParserOptions, $wgContLang, $wgMessageCache, $wgLang;
443 if ( is_object( $wgMessageCache ) )
444 $transstat = $wgMessageCache->getTransform();
446 if( is_object( $wgMessageCache ) ) {
448 $wgMessageCache->disableTransform();
449 $message = $wgMessageCache->get( $key, $useDB, $forContent );
452 $lang = &$wgContLang;
457 wfSuppressWarnings();
459 if( is_object( $lang ) ) {
460 $message = $lang->getMessage( $key );
465 if($message === false)
466 $message = Language
::getMessage($key);
467 if ( $transform && strstr( $message, '{{' ) !== false ) {
468 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
472 if ( is_object( $wgMessageCache ) && ! $transform )
473 $wgMessageCache->setTransform( $transstat );
479 * Replace message parameter keys on the given formatted output.
481 * @param string $message
486 function wfMsgReplaceArgs( $message, $args ) {
487 # Fix windows line-endings
488 # Some messages are split with explode("\n", $msg)
489 $message = str_replace( "\r", '', $message );
492 if ( count( $args ) ) {
493 if ( is_array( $args[0] ) ) {
494 foreach ( $args[0] as $key => $val ) {
495 $message = str_replace( '$' . $key, $val, $message );
498 foreach( $args as $n => $param ) {
499 $replacementKeys['$' . ($n +
1)] = $param;
501 $message = strtr( $message, $replacementKeys );
509 * Return an HTML-escaped version of a message.
510 * Parameter replacements, if any, are done *after* the HTML-escaping,
511 * so parameters may contain HTML (eg links or form controls). Be sure
512 * to pre-escape them if you really do want plaintext, or just wrap
513 * the whole thing in htmlspecialchars().
516 * @param string ... parameters
519 function wfMsgHtml( $key ) {
520 $args = func_get_args();
521 array_shift( $args );
522 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
526 * Return an HTML version of message
527 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
528 * so parameters may contain HTML (eg links or form controls). Be sure
529 * to pre-escape them if you really do want plaintext, or just wrap
530 * the whole thing in htmlspecialchars().
533 * @param string ... parameters
536 function wfMsgWikiHtml( $key ) {
538 $args = func_get_args();
539 array_shift( $args );
540 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
544 * Returns message in the requested format
545 * @param string $key Key of the message
546 * @param array $options Processing rules:
547 * <i>parse<i>: parses wikitext to html
548 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
549 * <i>escape<i>: filters message trough htmlspecialchars
550 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
552 function wfMsgExt( $key, $options ) {
555 $args = func_get_args();
556 array_shift( $args );
557 array_shift( $args );
559 if( !is_array($options) ) {
560 $options = array($options);
563 $string = wfMsgGetKey( $key, true );
565 if( !in_array('replaceafter', $options) ) {
566 $string = wfMsgReplaceArgs( $string, $args );
569 if( in_array('parse', $options) ) {
570 $string = $wgOut->parse( $string, true );
571 } elseif ( in_array('parseinline', $options) ) {
572 $string = $wgOut->parse( $string, true );
573 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m = null ) ) {
576 } elseif ( in_array('escape', $options) ) {
577 $string = htmlspecialchars ( $string );
580 if( in_array('replaceafter', $options) ) {
581 $string = wfMsgReplaceArgs( $string, $args );
589 * Just like exit() but makes a note of it.
590 * Commits open transactions except if the error parameter is set
592 function wfAbruptExit( $error = false ){
593 global $wgLoadBalancer;
594 static $called = false;
600 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
601 $bt = debug_backtrace();
602 for($i = 0; $i < count($bt) ; $i++
){
603 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
604 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
605 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
608 wfDebug('WARNING: Abrupt exit\n');
615 $wgLoadBalancer->closeAll();
623 function wfErrorExit() {
624 wfAbruptExit( true );
628 * Print a simple message and die, returning nonzero to the shell if any.
629 * Plain die() fails to return nonzero to the shell if you pass a string.
632 function wfDie( $msg='' ) {
638 * Die with a backtrace
639 * This is meant as a debugging aid to track down where bad data comes from.
640 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
642 * @param string $msg Message shown when dieing.
644 function wfDebugDieBacktrace( $msg = '' ) {
645 global $wgCommandLineMode;
647 $backtrace = wfBacktrace();
648 if ( $backtrace !== false ) {
649 if ( $wgCommandLineMode ) {
650 $msg .= "\nBacktrace:\n$backtrace";
652 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
656 echo wfReportTime()."\n";
661 * Returns a HTML comment with the elapsed time since request.
662 * This method has no side effects.
665 function wfReportTime() {
666 global $wgRequestTime;
669 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
670 $start = (float)$sec +
(float)$usec;
671 $elapsed = $now - $start;
673 # Use real server name if available, so we know which machine
674 # in a server farm generated the current page.
675 if ( function_exists( 'posix_uname' ) ) {
676 $uname = @posix_uname
();
680 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
681 $hostname = $uname['nodename'];
683 # This may be a virtual server.
684 $hostname = $_SERVER['SERVER_NAME'];
686 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
687 $hostname, $elapsed );
691 function wfBacktrace() {
692 global $wgCommandLineMode;
693 if ( !function_exists( 'debug_backtrace' ) ) {
697 if ( $wgCommandLineMode ) {
702 $backtrace = debug_backtrace();
703 foreach( $backtrace as $call ) {
704 if( isset( $call['file'] ) ) {
705 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
706 $file = $f[count($f)-1];
710 if( isset( $call['line'] ) ) {
711 $line = $call['line'];
715 if ( $wgCommandLineMode ) {
716 $msg .= "$file line $line calls ";
718 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
720 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
721 $msg .= $call['function'] . '()';
723 if ( $wgCommandLineMode ) {
729 if ( $wgCommandLineMode ) {
739 /* Some generic result counters, pulled out of SearchEngine */
745 function wfShowingResults( $offset, $limit ) {
747 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
753 function wfShowingResultsNum( $offset, $limit, $num ) {
755 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
761 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
763 $fmtLimit = $wgLang->formatNum( $limit );
764 $prev = wfMsg( 'prevn', $fmtLimit );
765 $next = wfMsg( 'nextn', $fmtLimit );
767 if( is_object( $link ) ) {
770 $title = Title
::newFromText( $link );
771 if( is_null( $title ) ) {
776 if ( 0 != $offset ) {
777 $po = $offset - $limit;
778 if ( $po < 0 ) { $po = 0; }
779 $q = "limit={$limit}&offset={$po}";
780 if ( '' != $query ) { $q .= '&'.$query; }
781 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
782 } else { $plink = $prev; }
784 $no = $offset +
$limit;
785 $q = 'limit='.$limit.'&offset='.$no;
786 if ( '' != $query ) { $q .= '&'.$query; }
791 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
793 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
794 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
795 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
796 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
797 wfNumLink( $offset, 500, $title, $query );
799 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
805 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
807 if ( '' == $query ) { $q = ''; }
808 else { $q = $query.'&'; }
809 $q .= 'limit='.$limit.'&offset='.$offset;
811 $fmtLimit = $wgLang->formatNum( $limit );
812 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
818 * @todo FIXME: we may want to blacklist some broken browsers
820 * @return bool Whereas client accept gzip compression
822 function wfClientAcceptsGzip() {
825 # FIXME: we may want to blacklist some broken browsers
827 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
828 $_SERVER['HTTP_ACCEPT_ENCODING'],
830 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
831 wfDebug( " accepts gzip\n" );
839 * Obtain the offset and limit values from the request string;
840 * used in special pages
842 * @param $deflimit Default limit if none supplied
843 * @param $optionname Name of a user preference to check against
847 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
849 return $wgRequest->getLimitOffset( $deflimit, $optionname );
853 * Escapes the given text so that it may be output using addWikiText()
854 * without any linking, formatting, etc. making its way through. This
855 * is achieved by substituting certain characters with HTML entities.
856 * As required by the callers, <nowiki> is not used. It currently does
857 * not filter out characters which have special meaning only at the
858 * start of a line, such as "*".
860 * @param string $text Text to be escaped
862 function wfEscapeWikiText( $text ) {
864 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
865 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
866 htmlspecialchars($text) );
873 function wfQuotedPrintable( $string, $charset = '' ) {
874 # Probably incomplete; see RFC 2045
875 if( empty( $charset ) ) {
876 global $wgInputEncoding;
877 $charset = $wgInputEncoding;
879 $charset = strtoupper( $charset );
880 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
882 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
883 $replace = $illegal . '\t ?_';
884 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
885 $out = "=?$charset?Q?";
886 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
897 $st = explode( ' ', microtime() );
898 return (float)$st[0] +
(float)$st[1];
902 * Sets dest to source and returns the original value of dest
903 * If source is NULL, it just returns the value, it doesn't set the variable
905 function wfSetVar( &$dest, $source ) {
907 if ( !is_null( $source ) ) {
914 * As for wfSetVar except setting a bit
916 function wfSetBit( &$dest, $bit, $state = true ) {
917 $temp = (bool)($dest & $bit );
918 if ( !is_null( $state ) ) {
929 * This function takes two arrays as input, and returns a CGI-style string, e.g.
930 * "days=7&limit=100". Options in the first array override options in the second.
931 * Options set to "" will not be output.
933 function wfArrayToCGI( $array1, $array2 = NULL )
935 if ( !is_null( $array2 ) ) {
936 $array1 = $array1 +
$array2;
940 foreach ( $array1 as $key => $value ) {
941 if ( '' !== $value ) {
945 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
952 * This is obsolete, use SquidUpdate::purge()
955 function wfPurgeSquidServers ($urlArr) {
956 SquidUpdate
::purge( $urlArr );
960 * Windows-compatible version of escapeshellarg()
961 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
962 * function puts single quotes in regardless of OS
964 function wfEscapeShellArg( ) {
965 $args = func_get_args();
968 foreach ( $args as $arg ) {
975 if ( wfIsWindows() ) {
976 // Escaping for an MSVC-style command line parser
977 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
978 // Double the backslashes before any double quotes. Escape the double quotes.
979 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
982 foreach ( $tokens as $token ) {
984 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
990 // Double the backslashes before the end of the string, because
991 // we will soon add a quote
992 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
993 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
996 // Add surrounding quotes
997 $retVal .= '"' . $arg . '"';
999 $retVal .= escapeshellarg( $arg );
1006 * wfMerge attempts to merge differences between three texts.
1007 * Returns true for a clean merge and false for failure or a conflict.
1009 function wfMerge( $old, $mine, $yours, &$result ){
1012 # This check may also protect against code injection in
1013 # case of broken installations.
1014 if(! file_exists( $wgDiff3 ) ){
1015 wfDebug( "diff3 not found\n" );
1019 # Make temporary files
1021 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1022 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1023 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1025 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1026 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1027 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1029 # Check for a conflict
1030 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1031 wfEscapeShellArg( $mytextName ) . ' ' .
1032 wfEscapeShellArg( $oldtextName ) . ' ' .
1033 wfEscapeShellArg( $yourtextName );
1034 $handle = popen( $cmd, 'r' );
1036 if( fgets( $handle, 1024 ) ){
1044 $cmd = $wgDiff3 . ' -a -e --merge ' .
1045 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1046 $handle = popen( $cmd, 'r' );
1049 $data = fread( $handle, 8192 );
1050 if ( strlen( $data ) == 0 ) {
1056 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1058 if ( $result === '' && $old !== '' && $conflict == false ) {
1059 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1068 function wfVarDump( $var ) {
1070 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1071 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1074 $wgOut->addHTML( $s );
1079 * Provide a simple HTTP error.
1081 function wfHttpError( $code, $label, $desc ) {
1084 header( "HTTP/1.0 $code $label" );
1085 header( "Status: $code $label" );
1086 $wgOut->sendCacheControl();
1088 header( 'Content-type: text/html' );
1089 print "<html><head><title>" .
1090 htmlspecialchars( $label ) .
1091 "</title></head><body><h1>" .
1092 htmlspecialchars( $label ) .
1094 htmlspecialchars( $desc ) .
1095 "</p></body></html>\n";
1099 * Converts an Accept-* header into an array mapping string values to quality
1102 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1103 # No arg means accept anything (per HTTP spec)
1105 return array( $def => 1 );
1110 $parts = explode( ',', $accept );
1112 foreach( $parts as $part ) {
1113 # FIXME: doesn't deal with params like 'text/html; level=1'
1114 @list
( $value, $qpart ) = explode( ';', $part );
1115 if( !isset( $qpart ) ) {
1117 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1118 $prefs[$value] = $match[1];
1126 * Checks if a given MIME type matches any of the keys in the given
1127 * array. Basic wildcards are accepted in the array keys.
1129 * Returns the matching MIME type (or wildcard) if a match, otherwise
1132 * @param string $type
1133 * @param array $avail
1137 function mimeTypeMatch( $type, $avail ) {
1138 if( array_key_exists($type, $avail) ) {
1141 $parts = explode( '/', $type );
1142 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1143 return $parts[0] . '/*';
1144 } elseif( array_key_exists( '*/*', $avail ) ) {
1153 * Returns the 'best' match between a client's requested internet media types
1154 * and the server's list of available types. Each list should be an associative
1155 * array of type to preference (preference is a float between 0.0 and 1.0).
1156 * Wildcards in the types are acceptable.
1158 * @param array $cprefs Client's acceptable type list
1159 * @param array $sprefs Server's offered types
1162 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1163 * XXX: generalize to negotiate other stuff
1165 function wfNegotiateType( $cprefs, $sprefs ) {
1168 foreach( array_keys($sprefs) as $type ) {
1169 $parts = explode( '/', $type );
1170 if( $parts[1] != '*' ) {
1171 $ckey = mimeTypeMatch( $type, $cprefs );
1173 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1178 foreach( array_keys( $cprefs ) as $type ) {
1179 $parts = explode( '/', $type );
1180 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1181 $skey = mimeTypeMatch( $type, $sprefs );
1183 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1191 foreach( array_keys( $combine ) as $type ) {
1192 if( $combine[$type] > $bestq ) {
1194 $bestq = $combine[$type];
1203 * Returns an array where the values in the first array are replaced by the
1204 * values in the second array with the corresponding keys
1208 function wfArrayLookup( $a, $b ) {
1209 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1213 * Convenience function; returns MediaWiki timestamp for the present time.
1216 function wfTimestampNow() {
1218 return wfTimestamp( TS_MW
, time() );
1222 * Reference-counted warning suppression
1224 function wfSuppressWarnings( $end = false ) {
1225 static $suppressCount = 0;
1226 static $originalLevel = false;
1229 if ( $suppressCount ) {
1231 if ( !$suppressCount ) {
1232 error_reporting( $originalLevel );
1236 if ( !$suppressCount ) {
1237 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1244 * Restore error level to previous value
1246 function wfRestoreWarnings() {
1247 wfSuppressWarnings( true );
1250 # Autodetect, convert and provide timestamps of various types
1253 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1255 define('TS_UNIX', 0);
1258 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1263 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1268 * RFC 2822 format, for E-mail and HTTP headers
1270 define('TS_RFC2822', 3);
1273 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1275 * This is used by Special:Export
1277 define('TS_ISO_8601', 4);
1280 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1282 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1283 * DateTime tag and page 36 for the DateTimeOriginal and
1284 * DateTimeDigitized tags.
1286 define('TS_EXIF', 5);
1289 * Oracle format time.
1291 define('TS_ORACLE', 6);
1294 * @param mixed $outputtype A timestamp in one of the supported formats, the
1295 * function will autodetect which format is supplied
1296 * and act accordingly.
1297 * @return string Time in the format specified in $outputtype
1299 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1303 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1305 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1306 (int)$da[2],(int)$da[3],(int)$da[1]);
1307 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1309 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1310 (int)$da[2],(int)$da[3],(int)$da[1]);
1311 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1313 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1314 (int)$da[2],(int)$da[3],(int)$da[1]);
1315 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1318 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1320 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1321 str_replace("+00:00", "UTC", $ts)));
1322 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1324 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1325 (int)$da[2],(int)$da[3],(int)$da[1]);
1327 # Bogus value; fall back to the epoch...
1328 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1333 switch($outputtype) {
1337 return gmdate( 'YmdHis', $uts );
1339 return gmdate( 'Y-m-d H:i:s', $uts );
1341 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1342 // This shouldn't ever be used, but is included for completeness
1344 return gmdate( 'Y:m:d H:i:s', $uts );
1346 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1348 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1350 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1355 * Return a formatted timestamp, or null if input is null.
1356 * For dealing with nullable timestamp columns in the database.
1357 * @param int $outputtype
1361 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1362 if( is_null( $ts ) ) {
1365 return wfTimestamp( $outputtype, $ts );
1370 * Check if the operating system is Windows
1372 * @return bool True if it's Windows, False otherwise.
1374 function wfIsWindows() {
1375 if (substr(php_uname(), 0, 7) == 'Windows') {
1383 * Swap two variables
1385 function swap( &$x, &$y ) {
1391 function wfGetCachedNotice( $name ) {
1392 global $wgOut, $parserMemc, $wgDBname;
1393 $fname = 'wfGetCachedNotice';
1394 wfProfileIn( $fname );
1397 $notice = wfMsgForContent( $name );
1398 if( $notice == '<'. $name . ';>' ||
$notice == '-' ) {
1399 wfProfileOut( $fname );
1403 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1404 if( is_array( $cachedNotice ) ) {
1405 if( md5( $notice ) == $cachedNotice['hash'] ) {
1406 $notice = $cachedNotice['html'];
1415 if( is_object( $wgOut ) ) {
1416 $parsed = $wgOut->parse( $notice );
1417 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1420 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1425 wfProfileOut( $fname );
1429 function wfGetNamespaceNotice() {
1433 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1436 $fname = 'wfGetNamespaceNotice';
1437 wfProfileIn( $fname );
1439 $key = "namespacenotice-" . $wgTitle->getNsText();
1440 $namespaceNotice = wfGetCachedNotice( $key );
1441 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1442 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1444 $namespaceNotice = "";
1447 wfProfileOut( $fname );
1448 return $namespaceNotice;
1451 function wfGetSiteNotice() {
1452 global $wgUser, $wgSiteNotice;
1453 $fname = 'wfGetSiteNotice';
1454 wfProfileIn( $fname );
1456 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1457 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1458 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1460 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1461 if( !$anonNotice ) {
1462 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1463 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1465 $siteNotice = $anonNotice;
1469 wfProfileOut( $fname );
1470 return( $siteNotice );
1473 /** Global singleton instance of MimeMagic. This is initialized on demand,
1474 * please always use the wfGetMimeMagic() function to get the instance.
1480 /** Factory functions for the global MimeMagic object.
1481 * This function always returns the same singleton instance of MimeMagic.
1482 * That objects will be instantiated on the first call to this function.
1483 * If needed, the MimeMagic.php file is automatically included by this function.
1484 * @return MimeMagic the global MimeMagic objects.
1486 function &wfGetMimeMagic() {
1487 global $wgMimeMagic;
1489 if (!is_null($wgMimeMagic)) {
1490 return $wgMimeMagic;
1493 if (!class_exists("MimeMagic")) {
1495 require_once("MimeMagic.php");
1498 $wgMimeMagic= new MimeMagic();
1500 return $wgMimeMagic;
1505 * Tries to get the system directory for temporary files.
1506 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1507 * and if none are set /tmp is returned as the generic Unix default.
1509 * NOTE: When possible, use the tempfile() function to create temporary
1510 * files to avoid race conditions on file creation, etc.
1514 function wfTempDir() {
1515 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1516 $tmp = getenv( $var );
1517 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1521 # Hope this is Unix of some kind!
1526 * Make directory, and make all parent directories if they don't exist
1528 function wfMkdirParents( $fullDir, $mode ) {
1529 $parts = explode( '/', $fullDir );
1532 foreach ( $parts as $dir ) {
1533 $path .= $dir . '/';
1534 if ( !is_dir( $path ) ) {
1535 if ( !mkdir( $path, $mode ) ) {
1544 * Increment a statistics counter
1546 function wfIncrStats( $key ) {
1547 global $wgDBname, $wgMemc;
1548 $key = "$wgDBname:stats:$key";
1549 if ( is_null( $wgMemc->incr( $key ) ) ) {
1550 $wgMemc->add( $key, 1 );
1555 * @param mixed $nr The number to format
1556 * @param int $acc The number of digits after the decimal point, default 2
1557 * @param bool $round Whether or not to round the value, default true
1560 function wfPercent( $nr, $acc = 2, $round = true ) {
1561 $ret = sprintf( "%.${acc}f", $nr );
1562 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1566 * Encrypt a username/password.
1568 * @param string $userid ID of the user
1569 * @param string $password Password of the user
1570 * @return string Hashed password
1572 function wfEncryptPassword( $userid, $password ) {
1573 global $wgPasswordSalt;
1574 $p = md5( $password);
1577 return md5( "{$userid}-{$p}" );
1583 * Appends to second array if $value differs from that in $default
1585 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1586 if ( is_null( $changed ) ) {
1587 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1589 if ( $default[$key] !== $value ) {
1590 $changed[$key] = $value;
1595 * Since wfMsg() and co suck, they don't return false if the message key they
1596 * looked up didn't exist but a XHTML string, this function checks for the
1597 * nonexistance of messages by looking at wfMsg() output
1599 * @param $msg The message key looked up
1600 * @param $wfMsgOut The output of wfMsg*()
1603 function wfEmptyMsg( $msg, $wfMsgOut ) {
1604 return $wfMsgOut === "<$msg>";
1608 * Find out whether or not a mixed variable exists in a string
1610 * @param mixed needle
1611 * @param string haystack
1614 function in_string( $needle, $str ) {
1615 return strpos( $str, $needle ) !== false;
1619 * Returns a regular expression of url protocols
1623 function wfUrlProtocols() {
1624 global $wgUrlProtocols;
1626 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1627 // with LocalSettings files from 1.5
1628 if ( is_array( $wgUrlProtocols ) ) {
1629 $protocols = array();
1630 foreach ($wgUrlProtocols as $protocol)
1631 $protocols[] = preg_quote( $protocol, '/' );
1633 return implode( '|', $protocols );
1635 return $wgUrlProtocols;
1640 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1643 function wfShellExec( $cmd )
1647 if ( php_uname( 's' ) == 'Linux' ) {
1648 $time = ini_get( 'max_execution_time' );
1649 $mem = ini_get( 'memory_limit' );
1650 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1651 $mem = intval( $m[1] * (1024*1024) );
1653 if ( $time > 0 && $mem > 0 ) {
1654 $script = "$IP/bin/ulimit.sh";
1655 if ( is_executable( $script ) ) {
1656 $memKB = intval( $mem / 1024 );
1657 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1660 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1661 # This is a hack to work around PHP's flawed invocation of cmd.exe
1662 # http://news.php.net/php.internals/21796
1663 $cmd = '"' . $cmd . '"';
1665 wfDebug( "wfShellExec: $cmd\n" );
1666 return shell_exec( $cmd );
1670 * This function works like "use VERSION" in Perl, the program will die with a
1671 * backtrace if the current version of PHP is less than the version provided
1673 * This is useful for extensions which due to their nature are not kept in sync
1674 * with releases, and might depend on other versions of PHP than the main code
1676 * Note: PHP might die due to parsing errors in some cases before it ever
1677 * manages to call this function, such is life
1679 * @see perldoc -f use
1681 * @param mixed $version The version to check, can be a string, an integer, or
1684 function wfUsePHP( $req_ver ) {
1685 $php_ver = PHP_VERSION
;
1687 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1688 wfDebugDieBacktrace( "PHP $req_ver required--this is only $php_ver" );
1692 * This function works like "use VERSION" in Perl except it checks the version
1693 * of MediaWiki, the program will die with a backtrace if the current version
1694 * of MediaWiki is less than the version provided.
1696 * This is useful for extensions which due to their nature are not kept in sync
1699 * @see perldoc -f use
1701 * @param mixed $version The version to check, can be a string, an integer, or
1704 function wfUseMW( $req_ver ) {
1707 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1708 wfDebugDieBacktrace( "MediaWiki $req_ver required--this is only $wgVersion" );
1712 * Escape a string to make it suitable for inclusion in a preg_replace()
1713 * replacement parameter.
1715 * @param string $string
1718 function wfRegexReplacement( $string ) {
1719 $string = str_replace( '\\', '\\\\', $string );
1720 $string = str_replace( '$', '\\$', $string );
1725 * Return the final portion of a pathname.
1726 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1727 * http://bugs.php.net/bug.php?id=33898
1729 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1730 * We'll consider it so always, as we don't want \s in our Unix paths either.
1732 * @param string $path
1735 function wfBaseName( $path ) {
1736 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1744 * Make a URL index, appropriate for the el_index field of externallinks.
1746 function wfMakeUrlIndex( $url ) {
1747 wfSuppressWarnings();
1748 $bits = parse_url( $url );
1749 wfRestoreWarnings();
1750 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1753 // Reverse the labels in the hostname, convert to lower case
1754 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1755 // Add an extra dot to the end
1756 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1757 $reversedHost .= '.';
1759 // Reconstruct the pseudo-URL
1760 $index = "http://$reversedHost";
1761 // Leave out user and password. Add the port, path, query and fragment
1762 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1763 if ( isset( $bits['path'] ) ) {
1764 $index .= $bits['path'];
1768 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1769 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1774 * Do any deferred updates and clear the list
1775 * TODO: This could be in Wiki.php if that class made any sense at all
1777 function wfDoUpdates()
1779 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1780 foreach ( $wgDeferredUpdateList as $update ) {
1781 $update->doUpdate();
1783 foreach ( $wgPostCommitUpdateList as $update ) {
1784 $update->doUpdate();
1786 $wgDeferredUpdateList = array();
1787 $wgPostCommitUpdateList = array();
1791 * More or less "markup-safe" explode()
1792 * Ignores any instances of the separator inside <...>
1793 * @param string $separator
1794 * @param string $text
1797 function wfExplodeMarkup( $separator, $text ) {
1798 $placeholder = "\x00";
1801 $text = str_replace( $placeholder, '', $text );
1804 $replacer = new ReplacerCallback( $separator, $placeholder );
1805 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1807 $items = explode( $separator, $cleaned );
1808 foreach( $items as $i => $str ) {
1809 $items[$i] = str_replace( $placeholder, $separator, $str );
1815 class ReplacerCallback
{
1816 function ReplacerCallback( $from, $to ) {
1817 $this->from
= $from;
1821 function go( $matches ) {
1822 return str_replace( $this->from
, $this->to
, $matches[1] );