3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
12 * Some globals and requires needed
15 /** Total number of articles */
16 $wgNumberOfArticles = -1; # Unset
18 /** Total number of views */
21 /** Total number of edits */
26 require_once dirname(__FILE__
) . '/LogPage.php';
27 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
28 require_once dirname(__FILE__
) . '/XmlFunctions.php';
31 * Compatibility functions
33 * We more or less support PHP 5.0.x and up.
34 * Re-implementations of newer functions or functions in non-standard
35 * PHP extensions may be included here.
37 if( !function_exists('iconv') ) {
38 # iconv support is not in the default configuration and so may not be present.
39 # Assume will only ever use utf-8 and iso-8859-1.
40 # This will *not* work in all circumstances.
41 function iconv( $from, $to, $string ) {
42 if(strcasecmp( $from, $to ) == 0) return $string;
43 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
44 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
49 # UTF-8 substr function based on a PHP manual comment
50 if ( !function_exists( 'mb_substr' ) ) {
51 function mb_substr( $str, $start ) {
53 preg_match_all( '/./us', $str, $ar );
55 if( func_num_args() >= 3 ) {
56 $end = func_get_arg( 2 );
57 return join( '', array_slice( $ar[0], $start, $end ) );
59 return join( '', array_slice( $ar[0], $start ) );
64 if ( !function_exists( 'array_diff_key' ) ) {
66 * Exists in PHP 5.1.0+
67 * Not quite compatible, two-argument version only
68 * Null values will cause problems due to this use of isset()
70 function array_diff_key( $left, $right ) {
72 foreach ( $left as $key => $unused ) {
73 if ( isset( $right[$key] ) ) {
74 unset( $result[$key] );
83 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
84 * PHP 5 won't let you declare a 'clone' function, even conditionally,
85 * so it has to be a wrapper with a different name.
87 function wfClone( $object ) {
88 return clone( $object );
92 * Where as we got a random seed
94 $wgRandomSeeded = false;
97 * Seed Mersenne Twister
98 * No-op for compatibility; only necessary in PHP < 4.2.0
100 function wfSeedRandom() {
105 * Get a random decimal value between 0 and 1, in a way
106 * not likely to give duplicate values for any realistic
107 * number of articles.
111 function wfRandom() {
112 # The maximum random value is "only" 2^31-1, so get two random
113 # values to reduce the chance of dupes
114 $max = mt_getrandmax() +
1;
115 $rand = number_format( (mt_rand() * $max +
mt_rand())
116 / $max / $max, 12, '.', '' );
121 * We want / and : to be included as literal characters in our title URLs.
122 * %2F in the page titles seems to fatally break for some reason.
127 function wfUrlencode ( $s ) {
128 $s = urlencode( $s );
129 $s = preg_replace( '/%3[Aa]/', ':', $s );
130 $s = preg_replace( '/%2[Ff]/', '/', $s );
136 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
137 * In normal operation this is a NOP.
139 * Controlling globals:
140 * $wgDebugLogFile - points to the log file
141 * $wgProfileOnly - if set, normal debug messages will not be recorded.
142 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
143 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
145 * @param $text String
146 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
148 function wfDebug( $text, $logonly = false ) {
149 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
150 static $recursion = 0;
152 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
153 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
157 if ( $wgDebugComments && !$logonly ) {
158 if ( !isset( $wgOut ) ) {
161 if ( !StubObject
::isRealObject( $wgOut ) ) {
169 $wgOut->debug( $text );
171 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
172 # Strip unprintables; they can switch terminal modes when binary data
173 # gets dumped, which is pretty annoying.
174 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
175 wfErrorLog( $text, $wgDebugLogFile );
180 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
181 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
183 * @param $logGroup String
184 * @param $text String
185 * @param $public Bool: whether to log the event in the public log if no private
186 * log file is specified, (default true)
188 function wfDebugLog( $logGroup, $text, $public = true ) {
189 global $wgDebugLogGroups;
190 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
191 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
192 $time = wfTimestamp( TS_DB
);
194 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
195 } else if ( $public === true ) {
196 wfDebug( $text, true );
201 * Log for database errors
202 * @param $text String: database error message.
204 function wfLogDBError( $text ) {
205 global $wgDBerrorLog, $wgDBname;
206 if ( $wgDBerrorLog ) {
207 $host = trim(`hostname`
);
208 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
209 wfErrorLog( $text, $wgDBerrorLog );
214 * Log to a file without getting "file size exceeded" signals
216 function wfErrorLog( $text, $file ) {
217 wfSuppressWarnings();
218 $exists = file_exists( $file );
219 $size = filesize( $file );
220 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
221 error_log( $text, 3, $file );
229 function wfLogProfilingData() {
230 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
231 global $wgProfiling, $wgUser;
232 if ( $wgProfiling ) {
234 $elapsed = $now - $wgRequestTime;
235 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
237 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
238 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
239 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
240 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
241 if( !empty( $_SERVER['HTTP_FROM'] ) )
242 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
244 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
245 // Don't unstub $wgUser at this late stage just for statistics purposes
246 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
248 $log = sprintf( "%s\t%04.3f\t%s\n",
249 gmdate( 'YmdHis' ), $elapsed,
250 urldecode( $wgRequest->getRequestURL() . $forward ) );
251 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
252 wfErrorLog( $log . $prof, $wgDebugLogFile );
258 * Check if the wiki read-only lock file is present. This can be used to lock
259 * off editing functions, but doesn't guarantee that the database will not be
263 function wfReadOnly() {
264 global $wgReadOnlyFile, $wgReadOnly;
266 if ( !is_null( $wgReadOnly ) ) {
267 return (bool)$wgReadOnly;
269 if ( '' == $wgReadOnlyFile ) {
272 // Set $wgReadOnly for faster access next time
273 if ( is_file( $wgReadOnlyFile ) ) {
274 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
278 return (bool)$wgReadOnly;
283 * Get a message from anywhere, for the current user language.
285 * Use wfMsgForContent() instead if the message should NOT
286 * change depending on the user preferences.
288 * Note that the message may contain HTML, and is therefore
289 * not safe for insertion anywhere. Some functions such as
290 * addWikiText will do the escaping for you. Use wfMsgHtml()
291 * if you need an escaped message.
293 * @param $key String: lookup key for the message, usually
294 * defined in languages/Language.php
296 * This function also takes extra optional parameters (not
297 * shown in the function definition), which can by used to
298 * insert variable text into the predefined message.
300 function wfMsg( $key ) {
301 $args = func_get_args();
302 array_shift( $args );
303 return wfMsgReal( $key, $args, true );
307 * Same as above except doesn't transform the message
309 function wfMsgNoTrans( $key ) {
310 $args = func_get_args();
311 array_shift( $args );
312 return wfMsgReal( $key, $args, true, false, false );
316 * Get a message from anywhere, for the current global language
317 * set with $wgLanguageCode.
319 * Use this if the message should NOT change dependent on the
320 * language set in the user's preferences. This is the case for
321 * most text written into logs, as well as link targets (such as
322 * the name of the copyright policy page). Link titles, on the
323 * other hand, should be shown in the UI language.
325 * Note that MediaWiki allows users to change the user interface
326 * language in their preferences, but a single installation
327 * typically only contains content in one language.
329 * Be wary of this distinction: If you use wfMsg() where you should
330 * use wfMsgForContent(), a user of the software may have to
331 * customize over 70 messages in order to, e.g., fix a link in every
334 * @param $key String: lookup key for the message, usually
335 * defined in languages/Language.php
337 function wfMsgForContent( $key ) {
338 global $wgForceUIMsgAsContentMsg;
339 $args = func_get_args();
340 array_shift( $args );
342 if( is_array( $wgForceUIMsgAsContentMsg ) &&
343 in_array( $key, $wgForceUIMsgAsContentMsg ) )
345 return wfMsgReal( $key, $args, true, $forcontent );
349 * Same as above except doesn't transform the message
351 function wfMsgForContentNoTrans( $key ) {
352 global $wgForceUIMsgAsContentMsg;
353 $args = func_get_args();
354 array_shift( $args );
356 if( is_array( $wgForceUIMsgAsContentMsg ) &&
357 in_array( $key, $wgForceUIMsgAsContentMsg ) )
359 return wfMsgReal( $key, $args, true, $forcontent, false );
363 * Get a message from the language file, for the UI elements
365 function wfMsgNoDB( $key ) {
366 $args = func_get_args();
367 array_shift( $args );
368 return wfMsgReal( $key, $args, false );
372 * Get a message from the language file, for the content
374 function wfMsgNoDBForContent( $key ) {
375 global $wgForceUIMsgAsContentMsg;
376 $args = func_get_args();
377 array_shift( $args );
379 if( is_array( $wgForceUIMsgAsContentMsg ) &&
380 in_array( $key, $wgForceUIMsgAsContentMsg ) )
382 return wfMsgReal( $key, $args, false, $forcontent );
387 * Really get a message
388 * @param $key String: key to get.
390 * @param $useDB Boolean
391 * @param $transform Boolean: Whether or not to transform the message.
392 * @param $forContent Boolean
393 * @return String: the requested message.
395 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
396 $fname = 'wfMsgReal';
397 wfProfileIn( $fname );
398 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
399 $message = wfMsgReplaceArgs( $message, $args );
400 wfProfileOut( $fname );
405 * This function provides the message source for messages to be edited which are *not* stored in the database.
406 * @param $key String:
408 function wfMsgWeirdKey ( $key ) {
409 $subsource = str_replace ( ' ' , '_' , $key ) ;
410 $source = wfMsgForContentNoTrans( $subsource ) ;
411 if ( wfEmptyMsg( $subsource, $source) ) {
412 # Try again with first char lower case
413 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
414 $source = wfMsgForContentNoTrans( $subsource ) ;
416 if ( wfEmptyMsg( $subsource, $source ) ) {
417 # Didn't work either, return blank text
424 * Fetch a message string value, but don't replace any keys yet.
427 * @param bool $forContent
431 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
432 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
434 if ( is_object( $wgMessageCache ) )
435 $transstat = $wgMessageCache->getTransform();
437 if( is_object( $wgMessageCache ) ) {
439 $wgMessageCache->disableTransform();
440 $message = $wgMessageCache->get( $key, $useDB, $forContent );
443 $lang = &$wgContLang;
448 wfSuppressWarnings();
450 if( is_object( $lang ) ) {
451 $message = $lang->getMessage( $key );
456 if($message === false)
457 $message = Language
::getMessage($key);
458 if ( $transform && strstr( $message, '{{' ) !== false ) {
459 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
463 if ( is_object( $wgMessageCache ) && ! $transform )
464 $wgMessageCache->setTransform( $transstat );
470 * Replace message parameter keys on the given formatted output.
472 * @param string $message
477 function wfMsgReplaceArgs( $message, $args ) {
478 # Fix windows line-endings
479 # Some messages are split with explode("\n", $msg)
480 $message = str_replace( "\r", '', $message );
483 if ( count( $args ) ) {
484 if ( is_array( $args[0] ) ) {
485 foreach ( $args[0] as $key => $val ) {
486 $message = str_replace( '$' . $key, $val, $message );
489 foreach( $args as $n => $param ) {
490 $replacementKeys['$' . ($n +
1)] = $param;
492 $message = strtr( $message, $replacementKeys );
500 * Return an HTML-escaped version of a message.
501 * Parameter replacements, if any, are done *after* the HTML-escaping,
502 * so parameters may contain HTML (eg links or form controls). Be sure
503 * to pre-escape them if you really do want plaintext, or just wrap
504 * the whole thing in htmlspecialchars().
507 * @param string ... parameters
510 function wfMsgHtml( $key ) {
511 $args = func_get_args();
512 array_shift( $args );
513 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
517 * Return an HTML version of message
518 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
519 * so parameters may contain HTML (eg links or form controls). Be sure
520 * to pre-escape them if you really do want plaintext, or just wrap
521 * the whole thing in htmlspecialchars().
524 * @param string ... parameters
527 function wfMsgWikiHtml( $key ) {
529 $args = func_get_args();
530 array_shift( $args );
531 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
535 * Returns message in the requested format
536 * @param string $key Key of the message
537 * @param array $options Processing rules:
538 * <i>parse<i>: parses wikitext to html
539 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
540 * <i>escape<i>: filters message trough htmlspecialchars
541 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
542 * <i>parsemag<i>: transform the message using magic phrases
544 function wfMsgExt( $key, $options ) {
545 global $wgOut, $wgParser;
547 $args = func_get_args();
548 array_shift( $args );
549 array_shift( $args );
551 if( !is_array($options) ) {
552 $options = array($options);
555 $string = wfMsgGetKey( $key, true, false, false );
557 if( !in_array('replaceafter', $options) ) {
558 $string = wfMsgReplaceArgs( $string, $args );
561 if( in_array('parse', $options) ) {
562 $string = $wgOut->parse( $string, true, true );
563 } elseif ( in_array('parseinline', $options) ) {
564 $string = $wgOut->parse( $string, true, true );
566 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
569 } elseif ( in_array('parsemag', $options) ) {
570 global $wgMessageCache;
571 if ( isset( $wgMessageCache ) ) {
572 $string = $wgMessageCache->transform( $string );
576 if ( 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 * @obsolete Please return control to the caller or throw an exception
594 function wfAbruptExit( $error = false ){
595 global $wgLoadBalancer;
596 static $called = false;
602 $bt = wfDebugBacktrace();
604 for($i = 0; $i < count($bt) ; $i++
){
605 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
606 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
607 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
610 wfDebug('WARNING: Abrupt exit\n');
613 wfLogProfilingData();
616 $wgLoadBalancer->closeAll();
622 * @obsolete Please return control the caller or throw an exception
624 function wfErrorExit() {
625 wfAbruptExit( true );
629 * Print a simple message and die, returning nonzero to the shell if any.
630 * Plain die() fails to return nonzero to the shell if you pass a string.
633 function wfDie( $msg='' ) {
639 * Throw a debugging exception. This function previously once exited the process,
640 * but now throws an exception instead, with similar results.
642 * @param string $msg Message shown when dieing.
644 function wfDebugDieBacktrace( $msg = '' ) {
645 throw new MWException( $msg );
649 * Fetch server name for use in error reporting etc.
650 * Use real server name if available, so we know which machine
651 * in a server farm generated the current page.
654 function wfHostname() {
655 if ( function_exists( 'posix_uname' ) ) {
656 // This function not present on Windows
657 $uname = @posix_uname
();
661 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
662 return $uname['nodename'];
664 # This may be a virtual server.
665 return $_SERVER['SERVER_NAME'];
670 * Returns a HTML comment with the elapsed time since request.
671 * This method has no side effects.
674 function wfReportTime() {
675 global $wgRequestTime;
678 $elapsed = $now - $wgRequestTime;
680 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
681 wfHostname(), $elapsed );
686 * Safety wrapper for debug_backtrace().
688 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
689 * murky circumstances, which may be triggered in part by stub objects
690 * or other fancy talkin'.
692 * Will return an empty array if Zend Optimizer is detected, otherwise
693 * the output from debug_backtrace() (trimmed).
695 * @return array of backtrace information
697 function wfDebugBacktrace() {
698 if( extension_loaded( 'Zend Optimizer' ) ) {
699 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
702 return array_slice( debug_backtrace(), 1 );
706 function wfBacktrace() {
707 global $wgCommandLineMode;
709 if ( $wgCommandLineMode ) {
714 $backtrace = wfDebugBacktrace();
715 foreach( $backtrace as $call ) {
716 if( isset( $call['file'] ) ) {
717 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
718 $file = $f[count($f)-1];
722 if( isset( $call['line'] ) ) {
723 $line = $call['line'];
727 if ( $wgCommandLineMode ) {
728 $msg .= "$file line $line calls ";
730 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
732 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
733 $msg .= $call['function'] . '()';
735 if ( $wgCommandLineMode ) {
741 if ( $wgCommandLineMode ) {
751 /* Some generic result counters, pulled out of SearchEngine */
757 function wfShowingResults( $offset, $limit ) {
759 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
765 function wfShowingResultsNum( $offset, $limit, $num ) {
767 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
773 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
775 $fmtLimit = $wgLang->formatNum( $limit );
776 $prev = wfMsg( 'prevn', $fmtLimit );
777 $next = wfMsg( 'nextn', $fmtLimit );
779 if( is_object( $link ) ) {
782 $title = Title
::newFromText( $link );
783 if( is_null( $title ) ) {
788 if ( 0 != $offset ) {
789 $po = $offset - $limit;
790 if ( $po < 0 ) { $po = 0; }
791 $q = "limit={$limit}&offset={$po}";
792 if ( '' != $query ) { $q .= '&'.$query; }
793 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
794 } else { $plink = $prev; }
796 $no = $offset +
$limit;
797 $q = 'limit='.$limit.'&offset='.$no;
798 if ( '' != $query ) { $q .= '&'.$query; }
803 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
805 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
806 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
807 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
808 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
809 wfNumLink( $offset, 500, $title, $query );
811 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
817 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
819 if ( '' == $query ) { $q = ''; }
820 else { $q = $query.'&'; }
821 $q .= 'limit='.$limit.'&offset='.$offset;
823 $fmtLimit = $wgLang->formatNum( $limit );
824 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
830 * @todo FIXME: we may want to blacklist some broken browsers
832 * @return bool Whereas client accept gzip compression
834 function wfClientAcceptsGzip() {
837 # FIXME: we may want to blacklist some broken browsers
840 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
841 $_SERVER['HTTP_ACCEPT_ENCODING'],
843 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
844 wfDebug( " accepts gzip\n" );
852 * Obtain the offset and limit values from the request string;
853 * used in special pages
855 * @param $deflimit Default limit if none supplied
856 * @param $optionname Name of a user preference to check against
860 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
862 return $wgRequest->getLimitOffset( $deflimit, $optionname );
866 * Escapes the given text so that it may be output using addWikiText()
867 * without any linking, formatting, etc. making its way through. This
868 * is achieved by substituting certain characters with HTML entities.
869 * As required by the callers, <nowiki> is not used. It currently does
870 * not filter out characters which have special meaning only at the
871 * start of a line, such as "*".
873 * @param string $text Text to be escaped
875 function wfEscapeWikiText( $text ) {
877 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
878 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
879 htmlspecialchars($text) );
886 function wfQuotedPrintable( $string, $charset = '' ) {
887 # Probably incomplete; see RFC 2045
888 if( empty( $charset ) ) {
889 global $wgInputEncoding;
890 $charset = $wgInputEncoding;
892 $charset = strtoupper( $charset );
893 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
895 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
896 $replace = $illegal . '\t ?_';
897 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
898 $out = "=?$charset?Q?";
899 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
910 return microtime(true);
914 * Sets dest to source and returns the original value of dest
915 * If source is NULL, it just returns the value, it doesn't set the variable
917 function wfSetVar( &$dest, $source ) {
919 if ( !is_null( $source ) ) {
926 * As for wfSetVar except setting a bit
928 function wfSetBit( &$dest, $bit, $state = true ) {
929 $temp = (bool)($dest & $bit );
930 if ( !is_null( $state ) ) {
941 * This function takes two arrays as input, and returns a CGI-style string, e.g.
942 * "days=7&limit=100". Options in the first array override options in the second.
943 * Options set to "" will not be output.
945 function wfArrayToCGI( $array1, $array2 = NULL )
947 if ( !is_null( $array2 ) ) {
948 $array1 = $array1 +
$array2;
952 foreach ( $array1 as $key => $value ) {
953 if ( '' !== $value ) {
957 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
964 * This is obsolete, use SquidUpdate::purge()
967 function wfPurgeSquidServers ($urlArr) {
968 SquidUpdate
::purge( $urlArr );
972 * Windows-compatible version of escapeshellarg()
973 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
974 * function puts single quotes in regardless of OS
976 function wfEscapeShellArg( ) {
977 $args = func_get_args();
980 foreach ( $args as $arg ) {
987 if ( wfIsWindows() ) {
988 // Escaping for an MSVC-style command line parser
989 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
990 // Double the backslashes before any double quotes. Escape the double quotes.
991 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
994 foreach ( $tokens as $token ) {
996 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1002 // Double the backslashes before the end of the string, because
1003 // we will soon add a quote
1005 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1006 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1009 // Add surrounding quotes
1010 $retVal .= '"' . $arg . '"';
1012 $retVal .= escapeshellarg( $arg );
1019 * wfMerge attempts to merge differences between three texts.
1020 * Returns true for a clean merge and false for failure or a conflict.
1022 function wfMerge( $old, $mine, $yours, &$result ){
1025 # This check may also protect against code injection in
1026 # case of broken installations.
1027 if(! file_exists( $wgDiff3 ) ){
1028 wfDebug( "diff3 not found\n" );
1032 # Make temporary files
1034 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1035 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1036 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1038 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1039 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1040 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1042 # Check for a conflict
1043 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1044 wfEscapeShellArg( $mytextName ) . ' ' .
1045 wfEscapeShellArg( $oldtextName ) . ' ' .
1046 wfEscapeShellArg( $yourtextName );
1047 $handle = popen( $cmd, 'r' );
1049 if( fgets( $handle, 1024 ) ){
1057 $cmd = $wgDiff3 . ' -a -e --merge ' .
1058 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1059 $handle = popen( $cmd, 'r' );
1062 $data = fread( $handle, 8192 );
1063 if ( strlen( $data ) == 0 ) {
1069 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1071 if ( $result === '' && $old !== '' && $conflict == false ) {
1072 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1081 function wfVarDump( $var ) {
1083 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1084 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1087 $wgOut->addHTML( $s );
1092 * Provide a simple HTTP error.
1094 function wfHttpError( $code, $label, $desc ) {
1097 header( "HTTP/1.0 $code $label" );
1098 header( "Status: $code $label" );
1099 $wgOut->sendCacheControl();
1101 header( 'Content-type: text/html; charset=utf-8' );
1102 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1103 "<html><head><title>" .
1104 htmlspecialchars( $label ) .
1105 "</title></head><body><h1>" .
1106 htmlspecialchars( $label ) .
1108 nl2br( htmlspecialchars( $desc ) ) .
1109 "</p></body></html>\n";
1113 * Clear away any user-level output buffers, discarding contents.
1115 * Suitable for 'starting afresh', for instance when streaming
1116 * relatively large amounts of data without buffering, or wanting to
1117 * output image files without ob_gzhandler's compression.
1119 * The optional $resetGzipEncoding parameter controls suppression of
1120 * the Content-Encoding header sent by ob_gzhandler; by default it
1121 * is left. See comments for wfClearOutputBuffers() for why it would
1124 * Note that some PHP configuration options may add output buffer
1125 * layers which cannot be removed; these are left in place.
1127 * @parameter bool $resetGzipEncoding
1129 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1130 if( $resetGzipEncoding ) {
1131 // Suppress Content-Encoding and Content-Length
1132 // headers from 1.10+s wfOutputHandler
1133 global $wgDisableOutputCompression;
1134 $wgDisableOutputCompression = true;
1136 while( $status = ob_get_status() ) {
1137 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1138 // Probably from zlib.output_compression or other
1139 // PHP-internal setting which can't be removed.
1141 // Give up, and hope the result doesn't break
1145 if( !ob_end_clean() ) {
1146 // Could not remove output buffer handler; abort now
1147 // to avoid getting in some kind of infinite loop.
1150 if( $resetGzipEncoding ) {
1151 if( $status['name'] == 'ob_gzhandler' ) {
1152 // Reset the 'Content-Encoding' field set by this handler
1153 // so we can start fresh.
1154 header( 'Content-Encoding:' );
1161 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1163 * Clear away output buffers, but keep the Content-Encoding header
1164 * produced by ob_gzhandler, if any.
1166 * This should be used for HTTP 304 responses, where you need to
1167 * preserve the Content-Encoding header of the real result, but
1168 * also need to suppress the output of ob_gzhandler to keep to spec
1169 * and avoid breaking Firefox in rare cases where the headers and
1170 * body are broken over two packets.
1172 function wfClearOutputBuffers() {
1173 wfResetOutputBuffers( false );
1177 * Converts an Accept-* header into an array mapping string values to quality
1180 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1181 # No arg means accept anything (per HTTP spec)
1183 return array( $def => 1 );
1188 $parts = explode( ',', $accept );
1190 foreach( $parts as $part ) {
1191 # FIXME: doesn't deal with params like 'text/html; level=1'
1192 @list
( $value, $qpart ) = explode( ';', $part );
1194 if( !isset( $qpart ) ) {
1196 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1197 $prefs[$value] = $match[1];
1205 * Checks if a given MIME type matches any of the keys in the given
1206 * array. Basic wildcards are accepted in the array keys.
1208 * Returns the matching MIME type (or wildcard) if a match, otherwise
1211 * @param string $type
1212 * @param array $avail
1216 function mimeTypeMatch( $type, $avail ) {
1217 if( array_key_exists($type, $avail) ) {
1220 $parts = explode( '/', $type );
1221 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1222 return $parts[0] . '/*';
1223 } elseif( array_key_exists( '*/*', $avail ) ) {
1232 * Returns the 'best' match between a client's requested internet media types
1233 * and the server's list of available types. Each list should be an associative
1234 * array of type to preference (preference is a float between 0.0 and 1.0).
1235 * Wildcards in the types are acceptable.
1237 * @param array $cprefs Client's acceptable type list
1238 * @param array $sprefs Server's offered types
1241 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1242 * XXX: generalize to negotiate other stuff
1244 function wfNegotiateType( $cprefs, $sprefs ) {
1247 foreach( array_keys($sprefs) as $type ) {
1248 $parts = explode( '/', $type );
1249 if( $parts[1] != '*' ) {
1250 $ckey = mimeTypeMatch( $type, $cprefs );
1252 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1257 foreach( array_keys( $cprefs ) as $type ) {
1258 $parts = explode( '/', $type );
1259 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1260 $skey = mimeTypeMatch( $type, $sprefs );
1262 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1270 foreach( array_keys( $combine ) as $type ) {
1271 if( $combine[$type] > $bestq ) {
1273 $bestq = $combine[$type];
1282 * Returns an array where the values in the first array are replaced by the
1283 * values in the second array with the corresponding keys
1287 function wfArrayLookup( $a, $b ) {
1288 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1292 * Convenience function; returns MediaWiki timestamp for the present time.
1295 function wfTimestampNow() {
1297 return wfTimestamp( TS_MW
, time() );
1301 * Reference-counted warning suppression
1303 function wfSuppressWarnings( $end = false ) {
1304 static $suppressCount = 0;
1305 static $originalLevel = false;
1308 if ( $suppressCount ) {
1310 if ( !$suppressCount ) {
1311 error_reporting( $originalLevel );
1315 if ( !$suppressCount ) {
1316 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1323 * Restore error level to previous value
1325 function wfRestoreWarnings() {
1326 wfSuppressWarnings( true );
1329 # Autodetect, convert and provide timestamps of various types
1332 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1334 define('TS_UNIX', 0);
1337 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1342 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1347 * RFC 2822 format, for E-mail and HTTP headers
1349 define('TS_RFC2822', 3);
1352 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1354 * This is used by Special:Export
1356 define('TS_ISO_8601', 4);
1359 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1361 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1362 * DateTime tag and page 36 for the DateTimeOriginal and
1363 * DateTimeDigitized tags.
1365 define('TS_EXIF', 5);
1368 * Oracle format time.
1370 define('TS_ORACLE', 6);
1373 * Postgres format time.
1375 define('TS_POSTGRES', 7);
1378 * @param mixed $outputtype A timestamp in one of the supported formats, the
1379 * function will autodetect which format is supplied
1380 * and act accordingly.
1381 * @return string Time in the format specified in $outputtype
1383 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1388 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1390 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1391 (int)$da[2],(int)$da[3],(int)$da[1]);
1392 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1394 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1395 (int)$da[2],(int)$da[3],(int)$da[1]);
1396 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1398 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1399 (int)$da[2],(int)$da[3],(int)$da[1]);
1400 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1403 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1405 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1406 str_replace("+00:00", "UTC", $ts)));
1407 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1409 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1410 (int)$da[2],(int)$da[3],(int)$da[1]);
1411 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1413 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1414 (int)$da[2],(int)$da[3],(int)$da[1]);
1415 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1417 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1418 (int)$da[2],(int)$da[3],(int)$da[1]);
1420 # Bogus value; fall back to the epoch...
1421 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1426 switch($outputtype) {
1430 return gmdate( 'YmdHis', $uts );
1432 return gmdate( 'Y-m-d H:i:s', $uts );
1434 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1435 // This shouldn't ever be used, but is included for completeness
1437 return gmdate( 'Y:m:d H:i:s', $uts );
1439 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1441 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1443 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1445 throw new MWException( 'wfTimestamp() called with illegal output type.');
1450 * Return a formatted timestamp, or null if input is null.
1451 * For dealing with nullable timestamp columns in the database.
1452 * @param int $outputtype
1456 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1457 if( is_null( $ts ) ) {
1460 return wfTimestamp( $outputtype, $ts );
1465 * Check if the operating system is Windows
1467 * @return bool True if it's Windows, False otherwise.
1469 function wfIsWindows() {
1470 if (substr(php_uname(), 0, 7) == 'Windows') {
1478 * Swap two variables
1480 function swap( &$x, &$y ) {
1486 function wfGetCachedNotice( $name ) {
1487 global $wgOut, $parserMemc;
1488 $fname = 'wfGetCachedNotice';
1489 wfProfileIn( $fname );
1493 if( $name === 'default' ) {
1495 global $wgSiteNotice;
1496 $notice = $wgSiteNotice;
1497 if( empty( $notice ) ) {
1498 wfProfileOut( $fname );
1502 $notice = wfMsgForContentNoTrans( $name );
1503 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1504 wfProfileOut( $fname );
1509 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1510 if( is_array( $cachedNotice ) ) {
1511 if( md5( $notice ) == $cachedNotice['hash'] ) {
1512 $notice = $cachedNotice['html'];
1521 if( is_object( $wgOut ) ) {
1522 $parsed = $wgOut->parse( $notice );
1523 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1526 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1531 wfProfileOut( $fname );
1535 function wfGetNamespaceNotice() {
1539 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1542 $fname = 'wfGetNamespaceNotice';
1543 wfProfileIn( $fname );
1545 $key = "namespacenotice-" . $wgTitle->getNsText();
1546 $namespaceNotice = wfGetCachedNotice( $key );
1547 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1548 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1550 $namespaceNotice = "";
1553 wfProfileOut( $fname );
1554 return $namespaceNotice;
1557 function wfGetSiteNotice() {
1558 global $wgUser, $wgSiteNotice;
1559 $fname = 'wfGetSiteNotice';
1560 wfProfileIn( $fname );
1563 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1564 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1565 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1567 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1568 if( !$anonNotice ) {
1569 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1571 $siteNotice = $anonNotice;
1574 if( !$siteNotice ) {
1575 $siteNotice = wfGetCachedNotice( 'default' );
1579 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1580 wfProfileOut( $fname );
1585 * BC wrapper for MimeMagic::singleton()
1588 function &wfGetMimeMagic() {
1589 return MimeMagic
::singleton();
1593 * Tries to get the system directory for temporary files.
1594 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1595 * and if none are set /tmp is returned as the generic Unix default.
1597 * NOTE: When possible, use the tempfile() function to create temporary
1598 * files to avoid race conditions on file creation, etc.
1602 function wfTempDir() {
1603 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1604 $tmp = getenv( $var );
1605 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1609 # Hope this is Unix of some kind!
1614 * Make directory, and make all parent directories if they don't exist
1616 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1617 if ( strval( $fullDir ) === '' ) {
1621 # Go back through the paths to find the first directory that exists
1622 $currentDir = $fullDir;
1623 $createList = array();
1624 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1625 # Strip trailing slashes
1626 $currentDir = rtrim( $currentDir, '/\\' );
1628 # Add to create list
1629 $createList[] = $currentDir;
1631 # Find next delimiter searching from the end
1632 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1633 if ( $p === false ) {
1634 $currentDir = false;
1636 $currentDir = substr( $currentDir, 0, $p );
1640 if ( count( $createList ) == 0 ) {
1641 # Directory specified already exists
1643 } elseif ( $currentDir === false ) {
1644 # Went all the way back to root and it apparently doesn't exist
1648 # Now go forward creating directories
1649 $createList = array_reverse( $createList );
1650 foreach ( $createList as $dir ) {
1651 # use chmod to override the umask, as suggested by the PHP manual
1652 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1653 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1661 * Increment a statistics counter
1663 function wfIncrStats( $key ) {
1665 $key = wfMemcKey( 'stats', $key );
1666 if ( is_null( $wgMemc->incr( $key ) ) ) {
1667 $wgMemc->add( $key, 1 );
1672 * @param mixed $nr The number to format
1673 * @param int $acc The number of digits after the decimal point, default 2
1674 * @param bool $round Whether or not to round the value, default true
1677 function wfPercent( $nr, $acc = 2, $round = true ) {
1678 $ret = sprintf( "%.${acc}f", $nr );
1679 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1683 * Encrypt a username/password.
1685 * @param string $userid ID of the user
1686 * @param string $password Password of the user
1687 * @return string Hashed password
1689 function wfEncryptPassword( $userid, $password ) {
1690 global $wgPasswordSalt;
1691 $p = md5( $password);
1694 return md5( "{$userid}-{$p}" );
1700 * Appends to second array if $value differs from that in $default
1702 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1703 if ( is_null( $changed ) ) {
1704 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1706 if ( $default[$key] !== $value ) {
1707 $changed[$key] = $value;
1712 * Since wfMsg() and co suck, they don't return false if the message key they
1713 * looked up didn't exist but a XHTML string, this function checks for the
1714 * nonexistance of messages by looking at wfMsg() output
1716 * @param $msg The message key looked up
1717 * @param $wfMsgOut The output of wfMsg*()
1720 function wfEmptyMsg( $msg, $wfMsgOut ) {
1721 return $wfMsgOut === "<$msg>";
1725 * Find out whether or not a mixed variable exists in a string
1727 * @param mixed needle
1728 * @param string haystack
1731 function in_string( $needle, $str ) {
1732 return strpos( $str, $needle ) !== false;
1735 function wfSpecialList( $page, $details ) {
1737 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1738 return $page . $details;
1742 * Returns a regular expression of url protocols
1746 function wfUrlProtocols() {
1747 global $wgUrlProtocols;
1749 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1750 // with LocalSettings files from 1.5
1751 if ( is_array( $wgUrlProtocols ) ) {
1752 $protocols = array();
1753 foreach ($wgUrlProtocols as $protocol)
1754 $protocols[] = preg_quote( $protocol, '/' );
1756 return implode( '|', $protocols );
1758 return $wgUrlProtocols;
1763 * Execute a shell command, with time and memory limits mirrored from the PHP
1764 * configuration if supported.
1765 * @param $cmd Command line, properly escaped for shell.
1766 * @param &$retval optional, will receive the program's exit code.
1767 * (non-zero is usually failure)
1768 * @return collected stdout as a string (trailing newlines stripped)
1770 function wfShellExec( $cmd, &$retval=null ) {
1771 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1773 if( ini_get( 'safe_mode' ) ) {
1774 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1776 return "Unable to run external programs in safe mode.";
1779 if ( php_uname( 's' ) == 'Linux' ) {
1780 $time = ini_get( 'max_execution_time' );
1781 $mem = intval( $wgMaxShellMemory );
1782 $filesize = intval( $wgMaxShellFileSize );
1784 if ( $time > 0 && $mem > 0 ) {
1785 $script = "$IP/bin/ulimit-tvf.sh";
1786 if ( is_executable( $script ) ) {
1787 $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
1790 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1791 # This is a hack to work around PHP's flawed invocation of cmd.exe
1792 # http://news.php.net/php.internals/21796
1793 $cmd = '"' . $cmd . '"';
1795 wfDebug( "wfShellExec: $cmd\n" );
1798 $retval = 1; // error by default?
1799 exec( $cmd, $output, $retval ); // returns the last line of output.
1800 return implode( "\n", $output );
1805 * This function works like "use VERSION" in Perl, the program will die with a
1806 * backtrace if the current version of PHP is less than the version provided
1808 * This is useful for extensions which due to their nature are not kept in sync
1809 * with releases, and might depend on other versions of PHP than the main code
1811 * Note: PHP might die due to parsing errors in some cases before it ever
1812 * manages to call this function, such is life
1814 * @see perldoc -f use
1816 * @param mixed $version The version to check, can be a string, an integer, or
1819 function wfUsePHP( $req_ver ) {
1820 $php_ver = PHP_VERSION
;
1822 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1823 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1827 * This function works like "use VERSION" in Perl except it checks the version
1828 * of MediaWiki, the program will die with a backtrace if the current version
1829 * of MediaWiki is less than the version provided.
1831 * This is useful for extensions which due to their nature are not kept in sync
1834 * @see perldoc -f use
1836 * @param mixed $version The version to check, can be a string, an integer, or
1839 function wfUseMW( $req_ver ) {
1842 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1843 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1847 * @deprecated use StringUtils::escapeRegexReplacement
1849 function wfRegexReplacement( $string ) {
1850 return StringUtils
::escapeRegexReplacement( $string );
1854 * Return the final portion of a pathname.
1855 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1856 * http://bugs.php.net/bug.php?id=33898
1858 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1859 * We'll consider it so always, as we don't want \s in our Unix paths either.
1861 * @param string $path
1864 function wfBaseName( $path ) {
1866 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1874 * Generate a relative path name to the given file.
1875 * May explode on non-matching case-insensitive paths,
1876 * funky symlinks, etc.
1878 * @param string $path Absolute destination path including target filename
1879 * @param string $from Absolute source path, directory only
1882 function wfRelativePath( $path, $from ) {
1883 // Normalize mixed input on Windows...
1884 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1885 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1887 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1888 $against = explode( DIRECTORY_SEPARATOR
, $from );
1890 // Trim off common prefix
1891 while( count( $pieces ) && count( $against )
1892 && $pieces[0] == $against[0] ) {
1893 array_shift( $pieces );
1894 array_shift( $against );
1897 // relative dots to bump us to the parent
1898 while( count( $against ) ) {
1899 array_unshift( $pieces, '..' );
1900 array_shift( $against );
1903 array_push( $pieces, wfBaseName( $path ) );
1905 return implode( DIRECTORY_SEPARATOR
, $pieces );
1909 * Make a URL index, appropriate for the el_index field of externallinks.
1911 function wfMakeUrlIndex( $url ) {
1912 wfSuppressWarnings();
1913 $bits = parse_url( $url );
1914 wfRestoreWarnings();
1915 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1918 // Reverse the labels in the hostname, convert to lower case
1919 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1920 // Add an extra dot to the end
1921 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1922 $reversedHost .= '.';
1924 // Reconstruct the pseudo-URL
1925 $index = "http://$reversedHost";
1926 // Leave out user and password. Add the port, path, query and fragment
1927 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1928 if ( isset( $bits['path'] ) ) {
1929 $index .= $bits['path'];
1933 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1934 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1939 * Do any deferred updates and clear the list
1940 * TODO: This could be in Wiki.php if that class made any sense at all
1942 function wfDoUpdates()
1944 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1945 foreach ( $wgDeferredUpdateList as $update ) {
1946 $update->doUpdate();
1948 foreach ( $wgPostCommitUpdateList as $update ) {
1949 $update->doUpdate();
1951 $wgDeferredUpdateList = array();
1952 $wgPostCommitUpdateList = array();
1956 * @deprecated use StringUtils::explodeMarkup
1958 function wfExplodeMarkup( $separator, $text ) {
1959 return StringUtils
::explodeMarkup( $separator, $text );
1963 * Convert an arbitrarily-long digit string from one numeric base
1964 * to another, optionally zero-padding to a minimum column width.
1966 * Supports base 2 through 36; digit values 10-36 are represented
1967 * as lowercase letters a-z. Input is case-insensitive.
1969 * @param $input string of digits
1970 * @param $sourceBase int 2-36
1971 * @param $destBase int 2-36
1972 * @param $pad int 1 or greater
1973 * @return string or false on invalid input
1975 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1976 if( $sourceBase < 2 ||
1981 $sourceBase != intval( $sourceBase ) ||
1982 $destBase != intval( $destBase ) ||
1983 $pad != intval( $pad ) ||
1984 !is_string( $input ) ||
1989 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1990 $inDigits = array();
1993 // Decode and validate input string
1994 $input = strtolower( $input );
1995 for( $i = 0; $i < strlen( $input ); $i++
) {
1996 $n = strpos( $digitChars, $input{$i} );
1997 if( $n === false ||
$n > $sourceBase ) {
2003 // Iterate over the input, modulo-ing out an output digit
2004 // at a time until input is gone.
2005 while( count( $inDigits ) ) {
2007 $workDigits = array();
2010 foreach( $inDigits as $digit ) {
2011 $work *= $sourceBase;
2014 if( $work < $destBase ) {
2015 // Gonna need to pull another digit.
2016 if( count( $workDigits ) ) {
2017 // Avoid zero-padding; this lets us find
2018 // the end of the input very easily when
2019 // length drops to zero.
2023 // Finally! Actual division!
2024 $workDigits[] = intval( $work / $destBase );
2026 // Isn't it annoying that most programming languages
2027 // don't have a single divide-and-remainder operator,
2028 // even though the CPU implements it that way?
2029 $work = $work %
$destBase;
2033 // All that division leaves us with a remainder,
2034 // which is conveniently our next output digit.
2035 $outChars .= $digitChars[$work];
2038 $inDigits = $workDigits;
2041 while( strlen( $outChars ) < $pad ) {
2045 return strrev( $outChars );
2049 * Create an object with a given name and an array of construct parameters
2050 * @param string $name
2051 * @param array $p parameters
2053 function wfCreateObject( $name, $p ){
2054 $p = array_values( $p );
2055 switch ( count( $p ) ) {
2059 return new $name( $p[0] );
2061 return new $name( $p[0], $p[1] );
2063 return new $name( $p[0], $p[1], $p[2] );
2065 return new $name( $p[0], $p[1], $p[2], $p[3] );
2067 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2069 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2071 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2076 * Aliases for modularized functions
2078 function wfGetHTTP( $url, $timeout = 'default' ) {
2079 return Http
::get( $url, $timeout );
2081 function wfIsLocalURL( $url ) {
2082 return Http
::isLocalURL( $url );
2086 * Initialise php session
2088 function wfSetupSession() {
2089 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2090 if( $wgSessionsInMemcached ) {
2091 require_once( 'MemcachedSessions.php' );
2092 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2093 # If it's left on 'user' or another setting from another
2094 # application, it will end up failing. Try to recover.
2095 ini_set ( 'session.save_handler', 'files' );
2097 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2098 session_cache_limiter( 'private, must-revalidate' );
2103 * Get an object from the precompiled serialized directory
2105 * @return mixed The variable on success, false on failure
2107 function wfGetPrecompiledData( $name ) {
2110 $file = "$IP/serialized/$name";
2111 if ( file_exists( $file ) ) {
2112 $blob = file_get_contents( $file );
2114 return unserialize( $blob );
2120 function wfGetCaller( $level = 2 ) {
2121 $backtrace = wfDebugBacktrace();
2122 if ( isset( $backtrace[$level] ) ) {
2123 if ( isset( $backtrace[$level]['class'] ) ) {
2124 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2126 $caller = $backtrace[$level]['function'];
2129 $caller = 'unknown';
2134 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2135 function wfGetAllCallers() {
2136 return implode('/', array_map(
2137 create_function('$frame','
2138 return isset( $frame["class"] )?
2139 $frame["class"]."::".$frame["function"]:
2142 array_reverse(wfDebugBacktrace())));
2148 function wfMemcKey( /*... */ ) {
2149 global $wgDBprefix, $wgDBname;
2150 $args = func_get_args();
2151 if ( $wgDBprefix ) {
2152 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2154 $key = $wgDBname . ':' . implode( ':', $args );
2160 * Get a cache key for a foreign DB
2162 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2163 $args = array_slice( func_get_args(), 2 );
2165 $key = "$db-$prefix:" . implode( ':', $args );
2167 $key = $db . ':' . implode( ':', $args );
2173 * Get an ASCII string identifying this wiki
2174 * This is used as a prefix in memcached keys
2176 function wfWikiID() {
2177 global $wgDBprefix, $wgDBname;
2178 if ( $wgDBprefix ) {
2179 return "$wgDBname-$wgDBprefix";
2186 * Get a Database object
2187 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2188 * master (for write queries), DB_SLAVE for potentially lagged
2189 * read queries, or an integer >= 0 for a particular server.
2191 * @param mixed $groups Query groups. An array of group names that this query
2192 * belongs to. May contain a single string if the query is only
2195 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2196 global $wgLoadBalancer;
2197 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );