dc35e828dc685efbe8d8e73f93dc66e6f3cc926b
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( 'LogPage.php' );
31 require_once( 'normal/UtfNormalUtil.php' );
32 require_once( 'XmlFunctions.php' );
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
77 return join( '', array_slice( $ar[0], $start ) );
82 if( !function_exists( 'floatval' ) ) {
84 * First defined in PHP 4.2.0
88 function floatval( $var ) {
93 if ( !function_exists( 'array_diff_key' ) ) {
95 * Exists in PHP 5.1.0+
96 * Not quite compatible, two-argument version only
97 * Null values will cause problems due to this use of isset()
99 function array_diff_key( $left, $right ) {
101 foreach ( $left as $key => $value ) {
102 if ( isset( $right[$key] ) ) {
103 unset( $result[$key] );
112 * Wrapper for clone() for PHP 4, for the moment.
113 * PHP 5 won't let you declare a 'clone' function, even conditionally,
114 * so it has to be a wrapper with a different name.
116 function wfClone( $object ) {
117 // WARNING: clone() is not a function in PHP 5, so function_exists fails.
118 if( version_compare( PHP_VERSION
, '5.0' ) < 0 ) {
121 return clone( $object );
126 * Where as we got a random seed
127 * @var bool $wgTotalViews
129 $wgRandomSeeded = false;
132 * Seed Mersenne Twister
133 * Only necessary in PHP < 4.2.0
137 function wfSeedRandom() {
138 global $wgRandomSeeded;
140 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
141 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
143 $wgRandomSeeded = true;
148 * Get a random decimal value between 0 and 1, in a way
149 * not likely to give duplicate values for any realistic
150 * number of articles.
154 function wfRandom() {
155 # The maximum random value is "only" 2^31-1, so get two random
156 # values to reduce the chance of dupes
157 $max = mt_getrandmax();
158 $rand = number_format( (mt_rand() * $max +
mt_rand())
159 / $max / $max, 12, '.', '' );
164 * We want / and : to be included as literal characters in our title URLs.
165 * %2F in the page titles seems to fatally break for some reason.
170 function wfUrlencode ( $s ) {
171 $s = urlencode( $s );
172 $s = preg_replace( '/%3[Aa]/', ':', $s );
173 $s = preg_replace( '/%2[Ff]/', '/', $s );
179 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
180 * In normal operation this is a NOP.
182 * Controlling globals:
183 * $wgDebugLogFile - points to the log file
184 * $wgProfileOnly - if set, normal debug messages will not be recorded.
185 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
186 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
188 * @param $text String
189 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
191 function wfDebug( $text, $logonly = false ) {
192 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
194 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
195 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
199 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
200 $wgOut->debug( $text );
202 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
203 # Strip unprintables; they can switch terminal modes when binary data
204 # gets dumped, which is pretty annoying.
205 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
206 @error_log
( $text, 3, $wgDebugLogFile );
211 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
212 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
214 * @param $logGroup String
215 * @param $text String
216 * @param $public Bool: whether to log the event in the public log if no private
217 * log file is specified, (default true)
219 function wfDebugLog( $logGroup, $text, $public = true ) {
220 global $wgDebugLogGroups, $wgDBname;
221 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
222 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
223 $time = wfTimestamp( TS_DB
);
224 @error_log
( "$time $wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
225 } else if ( $public === true ) {
226 wfDebug( $text, true );
231 * Log for database errors
232 * @param $text String: database error message.
234 function wfLogDBError( $text ) {
235 global $wgDBerrorLog;
236 if ( $wgDBerrorLog ) {
237 $host = trim(`hostname`
);
238 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
239 error_log( $text, 3, $wgDBerrorLog );
246 function wfLogProfilingData() {
247 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
248 global $wgProfiling, $wgUser;
249 if ( $wgProfiling ) {
251 $elapsed = $now - $wgRequestTime;
252 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
254 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
255 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
256 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
257 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
258 if( !empty( $_SERVER['HTTP_FROM'] ) )
259 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
261 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
262 if( is_object($wgUser) && $wgUser->isAnon() )
264 $log = sprintf( "%s\t%04.3f\t%s\n",
265 gmdate( 'YmdHis' ), $elapsed,
266 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
267 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
268 error_log( $log . $prof, 3, $wgDebugLogFile );
274 * Check if the wiki read-only lock file is present. This can be used to lock
275 * off editing functions, but doesn't guarantee that the database will not be
279 function wfReadOnly() {
280 global $wgReadOnlyFile, $wgReadOnly;
282 if ( !is_null( $wgReadOnly ) ) {
283 return (bool)$wgReadOnly;
285 if ( '' == $wgReadOnlyFile ) {
288 // Set $wgReadOnly for faster access next time
289 if ( is_file( $wgReadOnlyFile ) ) {
290 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
294 return (bool)$wgReadOnly;
299 * Get a message from anywhere, for the current user language.
301 * Use wfMsgForContent() instead if the message should NOT
302 * change depending on the user preferences.
304 * Note that the message may contain HTML, and is therefore
305 * not safe for insertion anywhere. Some functions such as
306 * addWikiText will do the escaping for you. Use wfMsgHtml()
307 * if you need an escaped message.
309 * @param $key String: lookup key for the message, usually
310 * defined in languages/Language.php
312 function wfMsg( $key ) {
313 $args = func_get_args();
314 array_shift( $args );
315 return wfMsgReal( $key, $args, true );
319 * Same as above except doesn't transform the message
321 function wfMsgNoTrans( $key ) {
322 $args = func_get_args();
323 array_shift( $args );
324 return wfMsgReal( $key, $args, true, false );
328 * Get a message from anywhere, for the current global language
329 * set with $wgLanguageCode.
331 * Use this if the message should NOT change dependent on the
332 * language set in the user's preferences. This is the case for
333 * most text written into logs, as well as link targets (such as
334 * the name of the copyright policy page). Link titles, on the
335 * other hand, should be shown in the UI language.
337 * Note that MediaWiki allows users to change the user interface
338 * language in their preferences, but a single installation
339 * typically only contains content in one language.
341 * Be wary of this distinction: If you use wfMsg() where you should
342 * use wfMsgForContent(), a user of the software may have to
343 * customize over 70 messages in order to, e.g., fix a link in every
346 * @param $key String: lookup key for the message, usually
347 * defined in languages/Language.php
349 function wfMsgForContent( $key ) {
350 global $wgForceUIMsgAsContentMsg;
351 $args = func_get_args();
352 array_shift( $args );
354 if( is_array( $wgForceUIMsgAsContentMsg ) &&
355 in_array( $key, $wgForceUIMsgAsContentMsg ) )
357 return wfMsgReal( $key, $args, true, $forcontent );
361 * Same as above except doesn't transform the message
363 function wfMsgForContentNoTrans( $key ) {
364 global $wgForceUIMsgAsContentMsg;
365 $args = func_get_args();
366 array_shift( $args );
368 if( is_array( $wgForceUIMsgAsContentMsg ) &&
369 in_array( $key, $wgForceUIMsgAsContentMsg ) )
371 return wfMsgReal( $key, $args, true, $forcontent, false );
375 * Get a message from the language file, for the UI elements
377 function wfMsgNoDB( $key ) {
378 $args = func_get_args();
379 array_shift( $args );
380 return wfMsgReal( $key, $args, false );
384 * Get a message from the language file, for the content
386 function wfMsgNoDBForContent( $key ) {
387 global $wgForceUIMsgAsContentMsg;
388 $args = func_get_args();
389 array_shift( $args );
391 if( is_array( $wgForceUIMsgAsContentMsg ) &&
392 in_array( $key, $wgForceUIMsgAsContentMsg ) )
394 return wfMsgReal( $key, $args, false, $forcontent );
399 * Really get a message
400 * @return $key String: key to get.
402 * @return $useDB Boolean
403 * @return String: the requested message.
405 function wfMsgReal( $key, $args, $useDB = true, $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.
415 * @param $key String:
417 function wfMsgWeirdKey ( $key ) {
418 $subsource = str_replace ( ' ' , '_' , $key ) ;
419 $source = wfMsgForContentNoTrans( $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 = wfMsgForContentNoTrans( $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 ) {
553 global $wgOut, $wgMsgParserOptions, $wgParser;
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, false, false );
565 if( !in_array('replaceafter', $options) ) {
566 $string = wfMsgReplaceArgs( $string, $args );
569 if( in_array('parse', $options) ) {
570 $string = $wgOut->parse( $string, true, true );
571 } elseif ( in_array('parseinline', $options) ) {
572 $string = $wgOut->parse( $string, true, true );
574 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
577 } elseif ( in_array('parsemag', $options) ) {
579 $parser = new Parser();
580 $parserOptions = new ParserOptions();
581 $parserOptions->setInterfaceMessage( true );
582 $parser->startExternalParse( $wgTitle, $parserOptions, OT_MSG
);
583 $string = $parser->transformMsg( $string, $parserOptions );
586 if ( in_array('escape', $options) ) {
587 $string = htmlspecialchars ( $string );
590 if( in_array('replaceafter', $options) ) {
591 $string = wfMsgReplaceArgs( $string, $args );
599 * Just like exit() but makes a note of it.
600 * Commits open transactions except if the error parameter is set
602 * @obsolete Please return control to the caller or throw an exception
604 function wfAbruptExit( $error = false ){
605 global $wgLoadBalancer;
606 static $called = false;
612 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
613 $bt = debug_backtrace();
614 for($i = 0; $i < count($bt) ; $i++
){
615 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
616 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
617 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
620 wfDebug('WARNING: Abrupt exit\n');
623 wfLogProfilingData();
626 $wgLoadBalancer->closeAll();
632 * @obsolete Please return control the caller or throw an exception
634 function wfErrorExit() {
635 wfAbruptExit( true );
639 * Print a simple message and die, returning nonzero to the shell if any.
640 * Plain die() fails to return nonzero to the shell if you pass a string.
643 function wfDie( $msg='' ) {
649 * Throw a debugging exception. This function previously once exited the process,
650 * but now throws an exception instead, with similar results.
652 * @param string $msg Message shown when dieing.
654 function wfDebugDieBacktrace( $msg = '' ) {
655 throw new MWException( $msg );
659 * Fetch server name for use in error reporting etc.
660 * Use real server name if available, so we know which machine
661 * in a server farm generated the current page.
664 function wfHostname() {
665 if ( function_exists( 'posix_uname' ) ) {
666 // This function not present on Windows
667 $uname = @posix_uname
();
671 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
672 return $uname['nodename'];
674 # This may be a virtual server.
675 return $_SERVER['SERVER_NAME'];
680 * Returns a HTML comment with the elapsed time since request.
681 * This method has no side effects.
684 function wfReportTime() {
685 global $wgRequestTime;
688 $elapsed = $now - $wgRequestTime;
690 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
691 wfHostname(), $elapsed );
695 function wfBacktrace() {
696 global $wgCommandLineMode;
697 if ( !function_exists( 'debug_backtrace' ) ) {
701 if ( $wgCommandLineMode ) {
706 $backtrace = debug_backtrace();
707 foreach( $backtrace as $call ) {
708 if( isset( $call['file'] ) ) {
709 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
710 $file = $f[count($f)-1];
714 if( isset( $call['line'] ) ) {
715 $line = $call['line'];
719 if ( $wgCommandLineMode ) {
720 $msg .= "$file line $line calls ";
722 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
724 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
725 $msg .= $call['function'] . '()';
727 if ( $wgCommandLineMode ) {
733 if ( $wgCommandLineMode ) {
743 /* Some generic result counters, pulled out of SearchEngine */
749 function wfShowingResults( $offset, $limit ) {
751 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
757 function wfShowingResultsNum( $offset, $limit, $num ) {
759 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
765 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
767 $fmtLimit = $wgLang->formatNum( $limit );
768 $prev = wfMsg( 'prevn', $fmtLimit );
769 $next = wfMsg( 'nextn', $fmtLimit );
771 if( is_object( $link ) ) {
774 $title = Title
::newFromText( $link );
775 if( is_null( $title ) ) {
780 if ( 0 != $offset ) {
781 $po = $offset - $limit;
782 if ( $po < 0 ) { $po = 0; }
783 $q = "limit={$limit}&offset={$po}";
784 if ( '' != $query ) { $q .= '&'.$query; }
785 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
786 } else { $plink = $prev; }
788 $no = $offset +
$limit;
789 $q = 'limit='.$limit.'&offset='.$no;
790 if ( '' != $query ) { $q .= '&'.$query; }
795 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
797 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
798 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
799 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
800 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
801 wfNumLink( $offset, 500, $title, $query );
803 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
809 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
811 if ( '' == $query ) { $q = ''; }
812 else { $q = $query.'&'; }
813 $q .= 'limit='.$limit.'&offset='.$offset;
815 $fmtLimit = $wgLang->formatNum( $limit );
816 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
822 * @todo FIXME: we may want to blacklist some broken browsers
824 * @return bool Whereas client accept gzip compression
826 function wfClientAcceptsGzip() {
829 # FIXME: we may want to blacklist some broken browsers
831 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
832 $_SERVER['HTTP_ACCEPT_ENCODING'],
834 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
835 wfDebug( " accepts gzip\n" );
843 * Obtain the offset and limit values from the request string;
844 * used in special pages
846 * @param $deflimit Default limit if none supplied
847 * @param $optionname Name of a user preference to check against
851 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
853 return $wgRequest->getLimitOffset( $deflimit, $optionname );
857 * Escapes the given text so that it may be output using addWikiText()
858 * without any linking, formatting, etc. making its way through. This
859 * is achieved by substituting certain characters with HTML entities.
860 * As required by the callers, <nowiki> is not used. It currently does
861 * not filter out characters which have special meaning only at the
862 * start of a line, such as "*".
864 * @param string $text Text to be escaped
866 function wfEscapeWikiText( $text ) {
868 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
869 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
870 htmlspecialchars($text) );
877 function wfQuotedPrintable( $string, $charset = '' ) {
878 # Probably incomplete; see RFC 2045
879 if( empty( $charset ) ) {
880 global $wgInputEncoding;
881 $charset = $wgInputEncoding;
883 $charset = strtoupper( $charset );
884 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
886 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
887 $replace = $illegal . '\t ?_';
888 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
889 $out = "=?$charset?Q?";
890 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
901 return microtime(true);
905 * Sets dest to source and returns the original value of dest
906 * If source is NULL, it just returns the value, it doesn't set the variable
908 function wfSetVar( &$dest, $source ) {
910 if ( !is_null( $source ) ) {
917 * As for wfSetVar except setting a bit
919 function wfSetBit( &$dest, $bit, $state = true ) {
920 $temp = (bool)($dest & $bit );
921 if ( !is_null( $state ) ) {
932 * This function takes two arrays as input, and returns a CGI-style string, e.g.
933 * "days=7&limit=100". Options in the first array override options in the second.
934 * Options set to "" will not be output.
936 function wfArrayToCGI( $array1, $array2 = NULL )
938 if ( !is_null( $array2 ) ) {
939 $array1 = $array1 +
$array2;
943 foreach ( $array1 as $key => $value ) {
944 if ( '' !== $value ) {
948 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
955 * This is obsolete, use SquidUpdate::purge()
958 function wfPurgeSquidServers ($urlArr) {
959 SquidUpdate
::purge( $urlArr );
963 * Windows-compatible version of escapeshellarg()
964 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
965 * function puts single quotes in regardless of OS
967 function wfEscapeShellArg( ) {
968 $args = func_get_args();
971 foreach ( $args as $arg ) {
978 if ( wfIsWindows() ) {
979 // Escaping for an MSVC-style command line parser
980 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
981 // Double the backslashes before any double quotes. Escape the double quotes.
982 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
985 foreach ( $tokens as $token ) {
987 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
993 // Double the backslashes before the end of the string, because
994 // we will soon add a quote
995 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
996 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
999 // Add surrounding quotes
1000 $retVal .= '"' . $arg . '"';
1002 $retVal .= escapeshellarg( $arg );
1009 * wfMerge attempts to merge differences between three texts.
1010 * Returns true for a clean merge and false for failure or a conflict.
1012 function wfMerge( $old, $mine, $yours, &$result ){
1015 # This check may also protect against code injection in
1016 # case of broken installations.
1017 if(! file_exists( $wgDiff3 ) ){
1018 wfDebug( "diff3 not found\n" );
1022 # Make temporary files
1024 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1025 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1026 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1028 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1029 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1030 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1032 # Check for a conflict
1033 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1034 wfEscapeShellArg( $mytextName ) . ' ' .
1035 wfEscapeShellArg( $oldtextName ) . ' ' .
1036 wfEscapeShellArg( $yourtextName );
1037 $handle = popen( $cmd, 'r' );
1039 if( fgets( $handle, 1024 ) ){
1047 $cmd = $wgDiff3 . ' -a -e --merge ' .
1048 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1049 $handle = popen( $cmd, 'r' );
1052 $data = fread( $handle, 8192 );
1053 if ( strlen( $data ) == 0 ) {
1059 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1061 if ( $result === '' && $old !== '' && $conflict == false ) {
1062 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1071 function wfVarDump( $var ) {
1073 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1074 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1077 $wgOut->addHTML( $s );
1082 * Provide a simple HTTP error.
1084 function wfHttpError( $code, $label, $desc ) {
1087 header( "HTTP/1.0 $code $label" );
1088 header( "Status: $code $label" );
1089 $wgOut->sendCacheControl();
1091 header( 'Content-type: text/html' );
1092 print "<html><head><title>" .
1093 htmlspecialchars( $label ) .
1094 "</title></head><body><h1>" .
1095 htmlspecialchars( $label ) .
1097 htmlspecialchars( $desc ) .
1098 "</p></body></html>\n";
1102 * Converts an Accept-* header into an array mapping string values to quality
1105 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1106 # No arg means accept anything (per HTTP spec)
1108 return array( $def => 1 );
1113 $parts = explode( ',', $accept );
1115 foreach( $parts as $part ) {
1116 # FIXME: doesn't deal with params like 'text/html; level=1'
1117 @list
( $value, $qpart ) = explode( ';', $part );
1118 if( !isset( $qpart ) ) {
1120 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1121 $prefs[$value] = $match[1];
1129 * Checks if a given MIME type matches any of the keys in the given
1130 * array. Basic wildcards are accepted in the array keys.
1132 * Returns the matching MIME type (or wildcard) if a match, otherwise
1135 * @param string $type
1136 * @param array $avail
1140 function mimeTypeMatch( $type, $avail ) {
1141 if( array_key_exists($type, $avail) ) {
1144 $parts = explode( '/', $type );
1145 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1146 return $parts[0] . '/*';
1147 } elseif( array_key_exists( '*/*', $avail ) ) {
1156 * Returns the 'best' match between a client's requested internet media types
1157 * and the server's list of available types. Each list should be an associative
1158 * array of type to preference (preference is a float between 0.0 and 1.0).
1159 * Wildcards in the types are acceptable.
1161 * @param array $cprefs Client's acceptable type list
1162 * @param array $sprefs Server's offered types
1165 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1166 * XXX: generalize to negotiate other stuff
1168 function wfNegotiateType( $cprefs, $sprefs ) {
1171 foreach( array_keys($sprefs) as $type ) {
1172 $parts = explode( '/', $type );
1173 if( $parts[1] != '*' ) {
1174 $ckey = mimeTypeMatch( $type, $cprefs );
1176 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1181 foreach( array_keys( $cprefs ) as $type ) {
1182 $parts = explode( '/', $type );
1183 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1184 $skey = mimeTypeMatch( $type, $sprefs );
1186 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1194 foreach( array_keys( $combine ) as $type ) {
1195 if( $combine[$type] > $bestq ) {
1197 $bestq = $combine[$type];
1206 * Returns an array where the values in the first array are replaced by the
1207 * values in the second array with the corresponding keys
1211 function wfArrayLookup( $a, $b ) {
1212 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1216 * Convenience function; returns MediaWiki timestamp for the present time.
1219 function wfTimestampNow() {
1221 return wfTimestamp( TS_MW
, time() );
1225 * Reference-counted warning suppression
1227 function wfSuppressWarnings( $end = false ) {
1228 static $suppressCount = 0;
1229 static $originalLevel = false;
1232 if ( $suppressCount ) {
1234 if ( !$suppressCount ) {
1235 error_reporting( $originalLevel );
1239 if ( !$suppressCount ) {
1240 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1247 * Restore error level to previous value
1249 function wfRestoreWarnings() {
1250 wfSuppressWarnings( true );
1253 # Autodetect, convert and provide timestamps of various types
1256 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1258 define('TS_UNIX', 0);
1261 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1266 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1271 * RFC 2822 format, for E-mail and HTTP headers
1273 define('TS_RFC2822', 3);
1276 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1278 * This is used by Special:Export
1280 define('TS_ISO_8601', 4);
1283 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1285 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1286 * DateTime tag and page 36 for the DateTimeOriginal and
1287 * DateTimeDigitized tags.
1289 define('TS_EXIF', 5);
1292 * Oracle format time.
1294 define('TS_ORACLE', 6);
1297 * Postgres format time.
1299 define('TS_POSTGRES', 7);
1302 * @param mixed $outputtype A timestamp in one of the supported formats, the
1303 * function will autodetect which format is supplied
1304 * and act accordingly.
1305 * @return string Time in the format specified in $outputtype
1307 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1312 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1314 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1315 (int)$da[2],(int)$da[3],(int)$da[1]);
1316 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1318 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1319 (int)$da[2],(int)$da[3],(int)$da[1]);
1320 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D",$ts,$da)) {
1322 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1323 (int)$da[2],(int)$da[3],(int)$da[1]);
1324 } elseif (preg_match("/^(\d{1,13})$/D",$ts,$datearray)) {
1327 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1329 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1330 str_replace("+00:00", "UTC", $ts)));
1331 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1333 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1334 (int)$da[2],(int)$da[3],(int)$da[1]);
1335 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/",$ts,$da)) {
1337 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1338 (int)$da[2],(int)$da[3],(int)$da[1]);
1340 # Bogus value; fall back to the epoch...
1341 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1346 switch($outputtype) {
1350 return gmdate( 'YmdHis', $uts );
1352 return gmdate( 'Y-m-d H:i:s', $uts );
1354 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1355 // This shouldn't ever be used, but is included for completeness
1357 return gmdate( 'Y:m:d H:i:s', $uts );
1359 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1361 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1363 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1365 throw new MWException( 'wfTimestamp() called with illegal output type.');
1370 * Return a formatted timestamp, or null if input is null.
1371 * For dealing with nullable timestamp columns in the database.
1372 * @param int $outputtype
1376 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1377 if( is_null( $ts ) ) {
1380 return wfTimestamp( $outputtype, $ts );
1385 * Check if the operating system is Windows
1387 * @return bool True if it's Windows, False otherwise.
1389 function wfIsWindows() {
1390 if (substr(php_uname(), 0, 7) == 'Windows') {
1398 * Swap two variables
1400 function swap( &$x, &$y ) {
1406 function wfGetCachedNotice( $name ) {
1407 global $wgOut, $parserMemc, $wgDBname;
1408 $fname = 'wfGetCachedNotice';
1409 wfProfileIn( $fname );
1412 $notice = wfMsgForContent( $name );
1413 if( $notice == '<'. $name . ';>' ||
$notice == '-' ) {
1414 wfProfileOut( $fname );
1418 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1419 if( is_array( $cachedNotice ) ) {
1420 if( md5( $notice ) == $cachedNotice['hash'] ) {
1421 $notice = $cachedNotice['html'];
1430 if( is_object( $wgOut ) ) {
1431 $parsed = $wgOut->parse( $notice );
1432 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1435 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1440 wfProfileOut( $fname );
1444 function wfGetNamespaceNotice() {
1448 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1451 $fname = 'wfGetNamespaceNotice';
1452 wfProfileIn( $fname );
1454 $key = "namespacenotice-" . $wgTitle->getNsText();
1455 $namespaceNotice = wfGetCachedNotice( $key );
1456 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1457 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1459 $namespaceNotice = "";
1462 wfProfileOut( $fname );
1463 return $namespaceNotice;
1466 function wfGetSiteNotice() {
1467 global $wgUser, $wgSiteNotice;
1468 $fname = 'wfGetSiteNotice';
1469 wfProfileIn( $fname );
1472 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1473 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1474 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1475 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1477 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1478 if( !$anonNotice ) {
1479 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1480 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1482 $siteNotice = $anonNotice;
1487 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1488 wfProfileOut( $fname );
1492 /** Global singleton instance of MimeMagic. This is initialized on demand,
1493 * please always use the wfGetMimeMagic() function to get the instance.
1499 /** Factory functions for the global MimeMagic object.
1500 * This function always returns the same singleton instance of MimeMagic.
1501 * That objects will be instantiated on the first call to this function.
1502 * If needed, the MimeMagic.php file is automatically included by this function.
1503 * @return MimeMagic the global MimeMagic objects.
1505 function &wfGetMimeMagic() {
1506 global $wgMimeMagic;
1508 if (!is_null($wgMimeMagic)) {
1509 return $wgMimeMagic;
1512 if (!class_exists("MimeMagic")) {
1514 require_once("MimeMagic.php");
1517 $wgMimeMagic= new MimeMagic();
1519 return $wgMimeMagic;
1524 * Tries to get the system directory for temporary files.
1525 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1526 * and if none are set /tmp is returned as the generic Unix default.
1528 * NOTE: When possible, use the tempfile() function to create temporary
1529 * files to avoid race conditions on file creation, etc.
1533 function wfTempDir() {
1534 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1535 $tmp = getenv( $var );
1536 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1540 # Hope this is Unix of some kind!
1545 * Make directory, and make all parent directories if they don't exist
1547 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1548 if ( strval( $fullDir ) === '' ) {
1552 # Go back through the paths to find the first directory that exists
1553 $currentDir = $fullDir;
1554 $createList = array();
1555 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1556 # Strip trailing slashes
1557 $currentDir = rtrim( $currentDir, '/\\' );
1559 # Add to create list
1560 $createList[] = $currentDir;
1562 # Find next delimiter searching from the end
1563 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1564 if ( $p === false ) {
1565 $currentDir = false;
1567 $currentDir = substr( $currentDir, 0, $p );
1571 if ( count( $createList ) == 0 ) {
1572 # Directory specified already exists
1574 } elseif ( $currentDir === false ) {
1575 # Went all the way back to root and it apparently doesn't exist
1579 # Now go forward creating directories
1580 $createList = array_reverse( $createList );
1581 foreach ( $createList as $dir ) {
1582 # use chmod to override the umask, as suggested by the PHP manual
1583 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1591 * Increment a statistics counter
1593 function wfIncrStats( $key ) {
1594 global $wgDBname, $wgMemc;
1595 $key = "$wgDBname:stats:$key";
1596 if ( is_null( $wgMemc->incr( $key ) ) ) {
1597 $wgMemc->add( $key, 1 );
1602 * @param mixed $nr The number to format
1603 * @param int $acc The number of digits after the decimal point, default 2
1604 * @param bool $round Whether or not to round the value, default true
1607 function wfPercent( $nr, $acc = 2, $round = true ) {
1608 $ret = sprintf( "%.${acc}f", $nr );
1609 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1613 * Encrypt a username/password.
1615 * @param string $userid ID of the user
1616 * @param string $password Password of the user
1617 * @return string Hashed password
1619 function wfEncryptPassword( $userid, $password ) {
1620 global $wgPasswordSalt;
1621 $p = md5( $password);
1624 return md5( "{$userid}-{$p}" );
1630 * Appends to second array if $value differs from that in $default
1632 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1633 if ( is_null( $changed ) ) {
1634 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1636 if ( $default[$key] !== $value ) {
1637 $changed[$key] = $value;
1642 * Since wfMsg() and co suck, they don't return false if the message key they
1643 * looked up didn't exist but a XHTML string, this function checks for the
1644 * nonexistance of messages by looking at wfMsg() output
1646 * @param $msg The message key looked up
1647 * @param $wfMsgOut The output of wfMsg*()
1650 function wfEmptyMsg( $msg, $wfMsgOut ) {
1651 return $wfMsgOut === "<$msg>";
1655 * Find out whether or not a mixed variable exists in a string
1657 * @param mixed needle
1658 * @param string haystack
1661 function in_string( $needle, $str ) {
1662 return strpos( $str, $needle ) !== false;
1665 function wfSpecialList( $page, $details ) {
1667 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1668 return $page . $details;
1672 * Returns a regular expression of url protocols
1676 function wfUrlProtocols() {
1677 global $wgUrlProtocols;
1679 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1680 // with LocalSettings files from 1.5
1681 if ( is_array( $wgUrlProtocols ) ) {
1682 $protocols = array();
1683 foreach ($wgUrlProtocols as $protocol)
1684 $protocols[] = preg_quote( $protocol, '/' );
1686 return implode( '|', $protocols );
1688 return $wgUrlProtocols;
1693 * Execute a shell command, with time and memory limits mirrored from the PHP
1694 * configuration if supported.
1695 * @param $cmd Command line, properly escaped for shell.
1696 * @param &$retval optional, will receive the program's exit code.
1697 * (non-zero is usually failure)
1698 * @return collected stdout as a string (trailing newlines stripped)
1700 function wfShellExec( $cmd, &$retval=null ) {
1701 global $IP, $wgMaxShellMemory;
1703 if( ini_get( 'safe_mode' ) ) {
1704 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1706 return "Unable to run external programs in safe mode.";
1709 if ( php_uname( 's' ) == 'Linux' ) {
1710 $time = ini_get( 'max_execution_time' );
1711 $mem = intval( $wgMaxShellMemory );
1713 if ( $time > 0 && $mem > 0 ) {
1714 $script = "$IP/bin/ulimit.sh";
1715 if ( is_executable( $script ) ) {
1716 $cmd = escapeshellarg( $script ) . " $time $mem $cmd";
1719 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1720 # This is a hack to work around PHP's flawed invocation of cmd.exe
1721 # http://news.php.net/php.internals/21796
1722 $cmd = '"' . $cmd . '"';
1724 wfDebug( "wfShellExec: $cmd\n" );
1727 $retval = 1; // error by default?
1728 $lastline = exec( $cmd, $output, $retval );
1729 return implode( "\n", $output );
1734 * This function works like "use VERSION" in Perl, the program will die with a
1735 * backtrace if the current version of PHP is less than the version provided
1737 * This is useful for extensions which due to their nature are not kept in sync
1738 * with releases, and might depend on other versions of PHP than the main code
1740 * Note: PHP might die due to parsing errors in some cases before it ever
1741 * manages to call this function, such is life
1743 * @see perldoc -f use
1745 * @param mixed $version The version to check, can be a string, an integer, or
1748 function wfUsePHP( $req_ver ) {
1749 $php_ver = PHP_VERSION
;
1751 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1752 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1756 * This function works like "use VERSION" in Perl except it checks the version
1757 * of MediaWiki, the program will die with a backtrace if the current version
1758 * of MediaWiki is less than the version provided.
1760 * This is useful for extensions which due to their nature are not kept in sync
1763 * @see perldoc -f use
1765 * @param mixed $version The version to check, can be a string, an integer, or
1768 function wfUseMW( $req_ver ) {
1771 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1772 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1776 * Escape a string to make it suitable for inclusion in a preg_replace()
1777 * replacement parameter.
1779 * @param string $string
1782 function wfRegexReplacement( $string ) {
1783 $string = str_replace( '\\', '\\\\', $string );
1784 $string = str_replace( '$', '\\$', $string );
1789 * Return the final portion of a pathname.
1790 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1791 * http://bugs.php.net/bug.php?id=33898
1793 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1794 * We'll consider it so always, as we don't want \s in our Unix paths either.
1796 * @param string $path
1799 function wfBaseName( $path ) {
1800 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1808 * Make a URL index, appropriate for the el_index field of externallinks.
1810 function wfMakeUrlIndex( $url ) {
1811 wfSuppressWarnings();
1812 $bits = parse_url( $url );
1813 wfRestoreWarnings();
1814 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1817 // Reverse the labels in the hostname, convert to lower case
1818 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1819 // Add an extra dot to the end
1820 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1821 $reversedHost .= '.';
1823 // Reconstruct the pseudo-URL
1824 $index = "http://$reversedHost";
1825 // Leave out user and password. Add the port, path, query and fragment
1826 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1827 if ( isset( $bits['path'] ) ) {
1828 $index .= $bits['path'];
1832 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1833 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1838 * Do any deferred updates and clear the list
1839 * TODO: This could be in Wiki.php if that class made any sense at all
1841 function wfDoUpdates()
1843 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1844 foreach ( $wgDeferredUpdateList as $update ) {
1845 $update->doUpdate();
1847 foreach ( $wgPostCommitUpdateList as $update ) {
1848 $update->doUpdate();
1850 $wgDeferredUpdateList = array();
1851 $wgPostCommitUpdateList = array();
1855 * More or less "markup-safe" explode()
1856 * Ignores any instances of the separator inside <...>
1857 * @param string $separator
1858 * @param string $text
1861 function wfExplodeMarkup( $separator, $text ) {
1862 $placeholder = "\x00";
1865 $text = str_replace( $placeholder, '', $text );
1868 $replacer = new ReplacerCallback( $separator, $placeholder );
1869 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1871 $items = explode( $separator, $cleaned );
1872 foreach( $items as $i => $str ) {
1873 $items[$i] = str_replace( $placeholder, $separator, $str );
1879 class ReplacerCallback
{
1880 function ReplacerCallback( $from, $to ) {
1881 $this->from
= $from;
1885 function go( $matches ) {
1886 return str_replace( $this->from
, $this->to
, $matches[1] );
1892 * Convert an arbitrarily-long digit string from one numeric base
1893 * to another, optionally zero-padding to a minimum column width.
1895 * Supports base 2 through 36; digit values 10-36 are represented
1896 * as lowercase letters a-z. Input is case-insensitive.
1898 * @param $input string of digits
1899 * @param $sourceBase int 2-36
1900 * @param $destBase int 2-36
1901 * @param $pad int 1 or greater
1902 * @return string or false on invalid input
1904 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1905 if( $sourceBase < 2 ||
1910 $sourceBase != intval( $sourceBase ) ||
1911 $destBase != intval( $destBase ) ||
1912 $pad != intval( $pad ) ||
1913 !is_string( $input ) ||
1918 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1919 $inDigits = array();
1922 // Decode and validate input string
1923 $input = strtolower( $input );
1924 for( $i = 0; $i < strlen( $input ); $i++
) {
1925 $n = strpos( $digitChars, $input{$i} );
1926 if( $n === false ||
$n > $sourceBase ) {
1932 // Iterate over the input, modulo-ing out an output digit
1933 // at a time until input is gone.
1934 while( count( $inDigits ) ) {
1936 $workDigits = array();
1939 foreach( $inDigits as $digit ) {
1940 $work *= $sourceBase;
1943 if( $work < $destBase ) {
1944 // Gonna need to pull another digit.
1945 if( count( $workDigits ) ) {
1946 // Avoid zero-padding; this lets us find
1947 // the end of the input very easily when
1948 // length drops to zero.
1952 // Finally! Actual division!
1953 $workDigits[] = intval( $work / $destBase );
1955 // Isn't it annoying that most programming languages
1956 // don't have a single divide-and-remainder operator,
1957 // even though the CPU implements it that way?
1958 $work = $work %
$destBase;
1962 // All that division leaves us with a remainder,
1963 // which is conveniently our next output digit.
1964 $outChars .= $digitChars[$work];
1967 $inDigits = $workDigits;
1970 while( strlen( $outChars ) < $pad ) {
1974 return strrev( $outChars );
1978 * Create an object with a given name and an array of construct parameters
1979 * @param string $name
1980 * @param array $p parameters
1982 function wfCreateObject( $name, $p ){
1983 $p = array_values( $p );
1984 switch ( count( $p ) ) {
1988 return new $name( $p[0] );
1990 return new $name( $p[0], $p[1] );
1992 return new $name( $p[0], $p[1], $p[2] );
1994 return new $name( $p[0], $p[1], $p[2], $p[3] );
1996 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1998 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2000 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2005 * Aliases for modularized functions
2007 function wfGetHTTP( $url, $timeout = 'default' ) {
2008 return Http
::get( $url, $timeout );
2010 function wfIsLocalURL( $url ) {
2011 return Http
::isLocalURL( $url );