3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
11 require_once dirname(__FILE__
) . '/LogPage.php';
12 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__
) . '/XmlFunctions.php';
14 require_once dirname(__FILE__
) . '/MessageFunctions.php';
17 * Compatibility functions
19 * We more or less support PHP 5.0.x and up.
20 * Re-implementations of newer functions or functions in non-standard
21 * PHP extensions may be included here.
23 if( !function_exists('iconv') ) {
24 # iconv support is not in the default configuration and so may not be present.
25 # Assume will only ever use utf-8 and iso-8859-1.
26 # This will *not* work in all circumstances.
27 function iconv( $from, $to, $string ) {
28 if(strcasecmp( $from, $to ) == 0) return $string;
29 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
30 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
35 # UTF-8 substr function based on a PHP manual comment
36 if ( !function_exists( 'mb_substr' ) ) {
37 function mb_substr( $str, $start ) {
39 preg_match_all( '/./us', $str, $ar );
41 if( func_num_args() >= 3 ) {
42 $end = func_get_arg( 2 );
43 return join( '', array_slice( $ar[0], $start, $end ) );
45 return join( '', array_slice( $ar[0], $start ) );
50 if ( !function_exists( 'mb_strlen' ) ) {
52 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
54 * @param string $enc optional encoding; ignored
57 function mb_strlen( $str, $enc="" ) {
58 $counts = count_chars( $str );
62 for( $i = 0; $i < 0x80; $i++
) {
63 $total +
= $counts[$i];
66 // Count multibyte sequence heads
67 for( $i = 0xc0; $i < 0xff; $i++
) {
68 $total +
= $counts[$i];
74 if ( !function_exists( 'array_diff_key' ) ) {
76 * Exists in PHP 5.1.0+
77 * Not quite compatible, two-argument version only
78 * Null values will cause problems due to this use of isset()
80 function array_diff_key( $left, $right ) {
82 foreach ( $left as $key => $unused ) {
83 if ( isset( $right[$key] ) ) {
84 unset( $result[$key] );
92 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
94 function wfArrayDiff2( $a, $b ) {
95 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
97 function wfArrayDiff2_cmp( $a, $b ) {
98 if ( !is_array( $a ) ) {
99 return strcmp( $a, $b );
100 } elseif ( count( $a ) !== count( $b ) ) {
101 return count( $a ) < count( $b ) ?
-1 : 1;
105 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
106 $cmp = strcmp( $valueA, $valueB );
116 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
117 * PHP 5 won't let you declare a 'clone' function, even conditionally,
118 * so it has to be a wrapper with a different name.
120 function wfClone( $object ) {
121 return clone( $object );
125 * Seed Mersenne Twister
126 * No-op for compatibility; only necessary in PHP < 4.2.0
128 function wfSeedRandom() {
133 * Get a random decimal value between 0 and 1, in a way
134 * not likely to give duplicate values for any realistic
135 * number of articles.
139 function wfRandom() {
140 # The maximum random value is "only" 2^31-1, so get two random
141 # values to reduce the chance of dupes
142 $max = mt_getrandmax() +
1;
143 $rand = number_format( (mt_rand() * $max +
mt_rand())
144 / $max / $max, 12, '.', '' );
149 * We want / and : to be included as literal characters in our title URLs.
150 * %2F in the page titles seems to fatally break for some reason.
155 function wfUrlencode ( $s ) {
156 $s = urlencode( $s );
157 $s = preg_replace( '/%3[Aa]/', ':', $s );
158 $s = preg_replace( '/%2[Ff]/', '/', $s );
164 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
165 * In normal operation this is a NOP.
167 * Controlling globals:
168 * $wgDebugLogFile - points to the log file
169 * $wgProfileOnly - if set, normal debug messages will not be recorded.
170 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
171 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
173 * @param $text String
174 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
176 function wfDebug( $text, $logonly = false ) {
177 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
178 static $recursion = 0;
180 static $cache = array(); // Cache of unoutputted messages
182 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
183 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
187 if ( $wgDebugComments && !$logonly ) {
190 if ( !isset( $wgOut ) ) {
193 if ( !StubObject
::isRealObject( $wgOut ) ) {
202 // add the message and possible cached ones to the output
203 array_map( array( $wgOut, 'debug' ), $cache );
206 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
207 # Strip unprintables; they can switch terminal modes when binary data
208 # gets dumped, which is pretty annoying.
209 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
210 wfErrorLog( $text, $wgDebugLogFile );
215 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
216 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
218 * @param $logGroup String
219 * @param $text String
220 * @param $public Bool: whether to log the event in the public log if no private
221 * log file is specified, (default true)
223 function wfDebugLog( $logGroup, $text, $public = true ) {
224 global $wgDebugLogGroups;
225 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
226 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
227 $time = wfTimestamp( TS_DB
);
229 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
230 } else if ( $public === true ) {
231 wfDebug( $text, true );
236 * Log for database errors
237 * @param $text String: database error message.
239 function wfLogDBError( $text ) {
240 global $wgDBerrorLog, $wgDBname;
241 if ( $wgDBerrorLog ) {
242 $host = trim(`hostname`
);
243 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
244 wfErrorLog( $text, $wgDBerrorLog );
249 * Log to a file without getting "file size exceeded" signals
251 function wfErrorLog( $text, $file ) {
252 wfSuppressWarnings();
253 $exists = file_exists( $file );
254 $size = $exists ?
filesize( $file ) : false;
255 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
256 error_log( $text, 3, $file );
264 function wfLogProfilingData() {
265 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
266 global $wgProfiler, $wgUser;
267 if ( !isset( $wgProfiler ) )
271 $elapsed = $now - $wgRequestTime;
272 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
274 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
275 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
276 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
277 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
278 if( !empty( $_SERVER['HTTP_FROM'] ) )
279 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
281 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
282 // Don't unstub $wgUser at this late stage just for statistics purposes
283 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
285 $log = sprintf( "%s\t%04.3f\t%s\n",
286 gmdate( 'YmdHis' ), $elapsed,
287 urldecode( $wgRequest->getRequestURL() . $forward ) );
288 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
289 wfErrorLog( $log . $prof, $wgDebugLogFile );
294 * Check if the wiki read-only lock file is present. This can be used to lock
295 * off editing functions, but doesn't guarantee that the database will not be
299 function wfReadOnly() {
300 global $wgReadOnlyFile, $wgReadOnly;
302 if ( !is_null( $wgReadOnly ) ) {
303 return (bool)$wgReadOnly;
305 if ( '' == $wgReadOnlyFile ) {
308 // Set $wgReadOnly for faster access next time
309 if ( is_file( $wgReadOnlyFile ) ) {
310 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
314 return (bool)$wgReadOnly;
317 function wfReadOnlyReason() {
324 * Just like exit() but makes a note of it.
325 * Commits open transactions except if the error parameter is set
327 * @deprecated Please return control to the caller or throw an exception
329 function wfAbruptExit( $error = false ){
330 static $called = false;
336 $bt = wfDebugBacktrace();
338 for($i = 0; $i < count($bt) ; $i++
){
339 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
340 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
341 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
344 wfDebug('WARNING: Abrupt exit\n');
347 wfLogProfilingData();
350 wfGetLB()->closeAll();
356 * @deprecated Please return control the caller or throw an exception
358 function wfErrorExit() {
359 wfAbruptExit( true );
363 * Print a simple message and die, returning nonzero to the shell if any.
364 * Plain die() fails to return nonzero to the shell if you pass a string.
367 function wfDie( $msg='' ) {
373 * Throw a debugging exception. This function previously once exited the process,
374 * but now throws an exception instead, with similar results.
376 * @param string $msg Message shown when dieing.
378 function wfDebugDieBacktrace( $msg = '' ) {
379 throw new MWException( $msg );
383 * Fetch server name for use in error reporting etc.
384 * Use real server name if available, so we know which machine
385 * in a server farm generated the current page.
388 function wfHostname() {
389 if ( function_exists( 'posix_uname' ) ) {
390 // This function not present on Windows
391 $uname = @posix_uname
();
395 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
396 return $uname['nodename'];
398 # This may be a virtual server.
399 return $_SERVER['SERVER_NAME'];
404 * Returns a HTML comment with the elapsed time since request.
405 * This method has no side effects.
408 function wfReportTime() {
409 global $wgRequestTime, $wgShowHostnames;
412 $elapsed = $now - $wgRequestTime;
414 return $wgShowHostnames
415 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
416 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
420 * Safety wrapper for debug_backtrace().
422 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
423 * murky circumstances, which may be triggered in part by stub objects
424 * or other fancy talkin'.
426 * Will return an empty array if Zend Optimizer is detected, otherwise
427 * the output from debug_backtrace() (trimmed).
429 * @return array of backtrace information
431 function wfDebugBacktrace() {
432 if( extension_loaded( 'Zend Optimizer' ) ) {
433 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
436 return array_slice( debug_backtrace(), 1 );
440 function wfBacktrace() {
441 global $wgCommandLineMode;
443 if ( $wgCommandLineMode ) {
448 $backtrace = wfDebugBacktrace();
449 foreach( $backtrace as $call ) {
450 if( isset( $call['file'] ) ) {
451 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
452 $file = $f[count($f)-1];
456 if( isset( $call['line'] ) ) {
457 $line = $call['line'];
461 if ( $wgCommandLineMode ) {
462 $msg .= "$file line $line calls ";
464 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
466 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
467 $msg .= $call['function'] . '()';
469 if ( $wgCommandLineMode ) {
475 if ( $wgCommandLineMode ) {
485 /* Some generic result counters, pulled out of SearchEngine */
491 function wfShowingResults( $offset, $limit ) {
493 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
499 function wfShowingResultsNum( $offset, $limit, $num ) {
501 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
507 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
509 $fmtLimit = $wgLang->formatNum( $limit );
510 $prev = wfMsg( 'prevn', $fmtLimit );
511 $next = wfMsg( 'nextn', $fmtLimit );
513 if( is_object( $link ) ) {
516 $title = Title
::newFromText( $link );
517 if( is_null( $title ) ) {
522 if ( 0 != $offset ) {
523 $po = $offset - $limit;
524 if ( $po < 0 ) { $po = 0; }
525 $q = "limit={$limit}&offset={$po}";
526 if ( '' != $query ) { $q .= '&'.$query; }
527 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
528 } else { $plink = $prev; }
530 $no = $offset +
$limit;
531 $q = 'limit='.$limit.'&offset='.$no;
532 if ( '' != $query ) { $q .= '&'.$query; }
537 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
539 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
540 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
541 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
542 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
543 wfNumLink( $offset, 500, $title, $query );
545 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
551 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
553 if ( '' == $query ) { $q = ''; }
554 else { $q = $query.'&'; }
555 $q .= 'limit='.$limit.'&offset='.$offset;
557 $fmtLimit = $wgLang->formatNum( $limit );
558 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
564 * @todo FIXME: we may want to blacklist some broken browsers
566 * @return bool Whereas client accept gzip compression
568 function wfClientAcceptsGzip() {
571 # FIXME: we may want to blacklist some broken browsers
574 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
575 $_SERVER['HTTP_ACCEPT_ENCODING'],
577 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
578 wfDebug( " accepts gzip\n" );
586 * Obtain the offset and limit values from the request string;
587 * used in special pages
589 * @param $deflimit Default limit if none supplied
590 * @param $optionname Name of a user preference to check against
594 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
596 return $wgRequest->getLimitOffset( $deflimit, $optionname );
600 * Escapes the given text so that it may be output using addWikiText()
601 * without any linking, formatting, etc. making its way through. This
602 * is achieved by substituting certain characters with HTML entities.
603 * As required by the callers, <nowiki> is not used. It currently does
604 * not filter out characters which have special meaning only at the
605 * start of a line, such as "*".
607 * @param string $text Text to be escaped
609 function wfEscapeWikiText( $text ) {
611 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
612 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
613 htmlspecialchars($text) );
620 function wfQuotedPrintable( $string, $charset = '' ) {
621 # Probably incomplete; see RFC 2045
622 if( empty( $charset ) ) {
623 global $wgInputEncoding;
624 $charset = $wgInputEncoding;
626 $charset = strtoupper( $charset );
627 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
629 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
630 $replace = $illegal . '\t ?_';
631 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
632 $out = "=?$charset?Q?";
633 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
644 return microtime(true);
648 * Sets dest to source and returns the original value of dest
649 * If source is NULL, it just returns the value, it doesn't set the variable
651 function wfSetVar( &$dest, $source ) {
653 if ( !is_null( $source ) ) {
660 * As for wfSetVar except setting a bit
662 function wfSetBit( &$dest, $bit, $state = true ) {
663 $temp = (bool)($dest & $bit );
664 if ( !is_null( $state ) ) {
675 * This function takes two arrays as input, and returns a CGI-style string, e.g.
676 * "days=7&limit=100". Options in the first array override options in the second.
677 * Options set to "" will not be output.
679 function wfArrayToCGI( $array1, $array2 = NULL )
681 if ( !is_null( $array2 ) ) {
682 $array1 = $array1 +
$array2;
686 foreach ( $array1 as $key => $value ) {
687 if ( '' !== $value ) {
694 foreach($value as $v)
696 $cgi .= ($firstTime ?
'' : '&') .
697 urlencode( $key . '[]' ) . '=' .
703 $cgi .= urlencode( $key ) . '=' .
711 * Append a query string to an existing URL, which may or may not already
712 * have query string parameters already. If so, they will be combined.
715 * @param string $query
718 function wfAppendQuery( $url, $query ) {
720 if( false === strpos( $url, '?' ) ) {
731 * Expand a potentially local URL to a fully-qualified URL.
732 * Assumes $wgServer is correct. :)
733 * @param string $url, either fully-qualified or a local path + query
734 * @return string Fully-qualified URL
736 function wfExpandUrl( $url ) {
737 if( substr( $url, 0, 1 ) == '/' ) {
739 return $wgServer . $url;
746 * This is obsolete, use SquidUpdate::purge()
749 function wfPurgeSquidServers ($urlArr) {
750 SquidUpdate
::purge( $urlArr );
754 * Windows-compatible version of escapeshellarg()
755 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
756 * function puts single quotes in regardless of OS
758 function wfEscapeShellArg( ) {
759 $args = func_get_args();
762 foreach ( $args as $arg ) {
769 if ( wfIsWindows() ) {
770 // Escaping for an MSVC-style command line parser
771 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
772 // Double the backslashes before any double quotes. Escape the double quotes.
773 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
776 foreach ( $tokens as $token ) {
778 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
784 // Double the backslashes before the end of the string, because
785 // we will soon add a quote
787 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
788 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
791 // Add surrounding quotes
792 $retVal .= '"' . $arg . '"';
794 $retVal .= escapeshellarg( $arg );
801 * wfMerge attempts to merge differences between three texts.
802 * Returns true for a clean merge and false for failure or a conflict.
804 function wfMerge( $old, $mine, $yours, &$result ){
807 # This check may also protect against code injection in
808 # case of broken installations.
809 if(! file_exists( $wgDiff3 ) ){
810 wfDebug( "diff3 not found\n" );
814 # Make temporary files
816 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
817 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
818 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
820 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
821 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
822 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
824 # Check for a conflict
825 $cmd = $wgDiff3 . ' -a --overlap-only ' .
826 wfEscapeShellArg( $mytextName ) . ' ' .
827 wfEscapeShellArg( $oldtextName ) . ' ' .
828 wfEscapeShellArg( $yourtextName );
829 $handle = popen( $cmd, 'r' );
831 if( fgets( $handle, 1024 ) ){
839 $cmd = $wgDiff3 . ' -a -e --merge ' .
840 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
841 $handle = popen( $cmd, 'r' );
844 $data = fread( $handle, 8192 );
845 if ( strlen( $data ) == 0 ) {
851 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
853 if ( $result === '' && $old !== '' && $conflict == false ) {
854 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
863 function wfVarDump( $var ) {
867 $s = str_replace("\n","<br />\n", ob_get_contents() . "\n");
869 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
872 $wgOut->addHTML( $s );
877 * Provide a simple HTTP error.
879 function wfHttpError( $code, $label, $desc ) {
882 header( "HTTP/1.0 $code $label" );
883 header( "Status: $code $label" );
884 $wgOut->sendCacheControl();
886 header( 'Content-type: text/html; charset=utf-8' );
887 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
888 "<html><head><title>" .
889 htmlspecialchars( $label ) .
890 "</title></head><body><h1>" .
891 htmlspecialchars( $label ) .
893 nl2br( htmlspecialchars( $desc ) ) .
894 "</p></body></html>\n";
898 * Clear away any user-level output buffers, discarding contents.
900 * Suitable for 'starting afresh', for instance when streaming
901 * relatively large amounts of data without buffering, or wanting to
902 * output image files without ob_gzhandler's compression.
904 * The optional $resetGzipEncoding parameter controls suppression of
905 * the Content-Encoding header sent by ob_gzhandler; by default it
906 * is left. See comments for wfClearOutputBuffers() for why it would
909 * Note that some PHP configuration options may add output buffer
910 * layers which cannot be removed; these are left in place.
912 * @param bool $resetGzipEncoding
914 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
915 if( $resetGzipEncoding ) {
916 // Suppress Content-Encoding and Content-Length
917 // headers from 1.10+s wfOutputHandler
918 global $wgDisableOutputCompression;
919 $wgDisableOutputCompression = true;
921 while( $status = ob_get_status() ) {
922 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
923 // Probably from zlib.output_compression or other
924 // PHP-internal setting which can't be removed.
926 // Give up, and hope the result doesn't break
930 if( !ob_end_clean() ) {
931 // Could not remove output buffer handler; abort now
932 // to avoid getting in some kind of infinite loop.
935 if( $resetGzipEncoding ) {
936 if( $status['name'] == 'ob_gzhandler' ) {
937 // Reset the 'Content-Encoding' field set by this handler
938 // so we can start fresh.
939 header( 'Content-Encoding:' );
946 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
948 * Clear away output buffers, but keep the Content-Encoding header
949 * produced by ob_gzhandler, if any.
951 * This should be used for HTTP 304 responses, where you need to
952 * preserve the Content-Encoding header of the real result, but
953 * also need to suppress the output of ob_gzhandler to keep to spec
954 * and avoid breaking Firefox in rare cases where the headers and
955 * body are broken over two packets.
957 function wfClearOutputBuffers() {
958 wfResetOutputBuffers( false );
962 * Converts an Accept-* header into an array mapping string values to quality
965 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
966 # No arg means accept anything (per HTTP spec)
968 return array( $def => 1.0 );
973 $parts = explode( ',', $accept );
975 foreach( $parts as $part ) {
976 # FIXME: doesn't deal with params like 'text/html; level=1'
977 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
979 if( !isset( $qpart ) ) {
980 $prefs[$value] = 1.0;
981 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
982 $prefs[$value] = floatval($match[1]);
990 * Checks if a given MIME type matches any of the keys in the given
991 * array. Basic wildcards are accepted in the array keys.
993 * Returns the matching MIME type (or wildcard) if a match, otherwise
996 * @param string $type
997 * @param array $avail
1001 function mimeTypeMatch( $type, $avail ) {
1002 if( array_key_exists($type, $avail) ) {
1005 $parts = explode( '/', $type );
1006 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1007 return $parts[0] . '/*';
1008 } elseif( array_key_exists( '*/*', $avail ) ) {
1017 * Returns the 'best' match between a client's requested internet media types
1018 * and the server's list of available types. Each list should be an associative
1019 * array of type to preference (preference is a float between 0.0 and 1.0).
1020 * Wildcards in the types are acceptable.
1022 * @param array $cprefs Client's acceptable type list
1023 * @param array $sprefs Server's offered types
1026 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1027 * XXX: generalize to negotiate other stuff
1029 function wfNegotiateType( $cprefs, $sprefs ) {
1032 foreach( array_keys($sprefs) as $type ) {
1033 $parts = explode( '/', $type );
1034 if( $parts[1] != '*' ) {
1035 $ckey = mimeTypeMatch( $type, $cprefs );
1037 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1042 foreach( array_keys( $cprefs ) as $type ) {
1043 $parts = explode( '/', $type );
1044 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1045 $skey = mimeTypeMatch( $type, $sprefs );
1047 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1055 foreach( array_keys( $combine ) as $type ) {
1056 if( $combine[$type] > $bestq ) {
1058 $bestq = $combine[$type];
1067 * Returns an array where the values in the first array are replaced by the
1068 * values in the second array with the corresponding keys
1072 function wfArrayLookup( $a, $b ) {
1073 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1077 * Convenience function; returns MediaWiki timestamp for the present time.
1080 function wfTimestampNow() {
1082 return wfTimestamp( TS_MW
, time() );
1086 * Reference-counted warning suppression
1088 function wfSuppressWarnings( $end = false ) {
1089 static $suppressCount = 0;
1090 static $originalLevel = false;
1093 if ( $suppressCount ) {
1095 if ( !$suppressCount ) {
1096 error_reporting( $originalLevel );
1100 if ( !$suppressCount ) {
1101 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1108 * Restore error level to previous value
1110 function wfRestoreWarnings() {
1111 wfSuppressWarnings( true );
1114 # Autodetect, convert and provide timestamps of various types
1117 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1119 define('TS_UNIX', 0);
1122 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1127 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1132 * RFC 2822 format, for E-mail and HTTP headers
1134 define('TS_RFC2822', 3);
1137 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1139 * This is used by Special:Export
1141 define('TS_ISO_8601', 4);
1144 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1146 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1147 * DateTime tag and page 36 for the DateTimeOriginal and
1148 * DateTimeDigitized tags.
1150 define('TS_EXIF', 5);
1153 * Oracle format time.
1155 define('TS_ORACLE', 6);
1158 * Postgres format time.
1160 define('TS_POSTGRES', 7);
1163 * @param mixed $outputtype A timestamp in one of the supported formats, the
1164 * function will autodetect which format is supplied
1165 * and act accordingly.
1166 * @return string Time in the format specified in $outputtype
1168 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1173 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1175 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1177 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1179 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1182 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1184 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1185 str_replace("+00:00", "UTC", $ts)));
1186 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1188 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1190 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1193 # Bogus value; fall back to the epoch...
1194 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1198 if (count( $da ) ) {
1199 // Warning! gmmktime() acts oddly if the month or day is set to 0
1200 // We may want to handle that explicitly at some point
1201 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1202 (int)$da[2],(int)$da[3],(int)$da[1]);
1205 switch($outputtype) {
1209 return gmdate( 'YmdHis', $uts );
1211 return gmdate( 'Y-m-d H:i:s', $uts );
1213 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1214 // This shouldn't ever be used, but is included for completeness
1216 return gmdate( 'Y:m:d H:i:s', $uts );
1218 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1220 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1222 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1224 throw new MWException( 'wfTimestamp() called with illegal output type.');
1229 * Return a formatted timestamp, or null if input is null.
1230 * For dealing with nullable timestamp columns in the database.
1231 * @param int $outputtype
1235 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1236 if( is_null( $ts ) ) {
1239 return wfTimestamp( $outputtype, $ts );
1244 * Check if the operating system is Windows
1246 * @return bool True if it's Windows, False otherwise.
1248 function wfIsWindows() {
1249 if (substr(php_uname(), 0, 7) == 'Windows') {
1257 * Swap two variables
1259 function swap( &$x, &$y ) {
1265 function wfGetCachedNotice( $name ) {
1266 global $wgOut, $parserMemc;
1267 $fname = 'wfGetCachedNotice';
1268 wfProfileIn( $fname );
1272 if( $name === 'default' ) {
1274 global $wgSiteNotice;
1275 $notice = $wgSiteNotice;
1276 if( empty( $notice ) ) {
1277 wfProfileOut( $fname );
1281 $notice = wfMsgForContentNoTrans( $name );
1282 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1283 wfProfileOut( $fname );
1288 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1289 if( is_array( $cachedNotice ) ) {
1290 if( md5( $notice ) == $cachedNotice['hash'] ) {
1291 $notice = $cachedNotice['html'];
1300 if( is_object( $wgOut ) ) {
1301 $parsed = $wgOut->parse( $notice );
1302 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1305 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1310 wfProfileOut( $fname );
1314 function wfGetNamespaceNotice() {
1318 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1321 $fname = 'wfGetNamespaceNotice';
1322 wfProfileIn( $fname );
1324 $key = "namespacenotice-" . $wgTitle->getNsText();
1325 $namespaceNotice = wfGetCachedNotice( $key );
1326 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1327 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1329 $namespaceNotice = "";
1332 wfProfileOut( $fname );
1333 return $namespaceNotice;
1336 function wfGetSiteNotice() {
1337 global $wgUser, $wgSiteNotice;
1338 $fname = 'wfGetSiteNotice';
1339 wfProfileIn( $fname );
1342 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1343 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1344 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1346 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1347 if( !$anonNotice ) {
1348 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1350 $siteNotice = $anonNotice;
1353 if( !$siteNotice ) {
1354 $siteNotice = wfGetCachedNotice( 'default' );
1358 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1359 wfProfileOut( $fname );
1364 * BC wrapper for MimeMagic::singleton()
1367 function &wfGetMimeMagic() {
1368 return MimeMagic
::singleton();
1372 * Tries to get the system directory for temporary files.
1373 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1374 * and if none are set /tmp is returned as the generic Unix default.
1376 * NOTE: When possible, use the tempfile() function to create temporary
1377 * files to avoid race conditions on file creation, etc.
1381 function wfTempDir() {
1382 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1383 $tmp = getenv( $var );
1384 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1388 # Hope this is Unix of some kind!
1393 * Make directory, and make all parent directories if they don't exist
1395 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1396 if( strval( $fullDir ) === '' )
1398 if( file_exists( $fullDir ) )
1401 # Go back through the paths to find the first directory that exists
1402 $currentDir = $fullDir;
1403 $createList = array();
1404 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1405 # Strip trailing slashes
1406 $currentDir = rtrim( $currentDir, '/\\' );
1408 # Add to create list
1409 $createList[] = $currentDir;
1411 # Find next delimiter searching from the end
1412 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1413 if ( $p === false ) {
1414 $currentDir = false;
1416 $currentDir = substr( $currentDir, 0, $p );
1420 if ( count( $createList ) == 0 ) {
1421 # Directory specified already exists
1423 } elseif ( $currentDir === false ) {
1424 # Went all the way back to root and it apparently doesn't exist
1425 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1428 # Now go forward creating directories
1429 $createList = array_reverse( $createList );
1431 # Is the parent directory writable?
1432 if ( $currentDir === '' ) {
1435 if ( !is_writable( $currentDir ) ) {
1436 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1440 foreach ( $createList as $dir ) {
1441 # use chmod to override the umask, as suggested by the PHP manual
1442 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1443 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1451 * Increment a statistics counter
1453 function wfIncrStats( $key ) {
1454 global $wgStatsMethod;
1456 if( $wgStatsMethod == 'udp' ) {
1457 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1460 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1461 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1462 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1464 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1465 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1466 } elseif( $wgStatsMethod == 'cache' ) {
1468 $key = wfMemcKey( 'stats', $key );
1469 if ( is_null( $wgMemc->incr( $key ) ) ) {
1470 $wgMemc->add( $key, 1 );
1478 * @param mixed $nr The number to format
1479 * @param int $acc The number of digits after the decimal point, default 2
1480 * @param bool $round Whether or not to round the value, default true
1483 function wfPercent( $nr, $acc = 2, $round = true ) {
1484 $ret = sprintf( "%.${acc}f", $nr );
1485 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1489 * Encrypt a username/password.
1491 * @param string $userid ID of the user
1492 * @param string $password Password of the user
1493 * @return string Hashed password
1494 * @deprecated Use User::crypt() or User::oldCrypt() instead
1496 function wfEncryptPassword( $userid, $password ) {
1497 wfDeprecated(__FUNCTION__
);
1498 # Just wrap around User::oldCrypt()
1499 return User
::oldCrypt($password, $userid);
1503 * Appends to second array if $value differs from that in $default
1505 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1506 if ( is_null( $changed ) ) {
1507 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1509 if ( $default[$key] !== $value ) {
1510 $changed[$key] = $value;
1515 * Since wfMsg() and co suck, they don't return false if the message key they
1516 * looked up didn't exist but a XHTML string, this function checks for the
1517 * nonexistance of messages by looking at wfMsg() output
1519 * @param $msg The message key looked up
1520 * @param $wfMsgOut The output of wfMsg*()
1523 function wfEmptyMsg( $msg, $wfMsgOut ) {
1524 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1528 * Find out whether or not a mixed variable exists in a string
1530 * @param mixed needle
1531 * @param string haystack
1534 function in_string( $needle, $str ) {
1535 return strpos( $str, $needle ) !== false;
1538 function wfSpecialList( $page, $details ) {
1540 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1541 return $page . $details;
1545 * Returns a regular expression of url protocols
1549 function wfUrlProtocols() {
1550 global $wgUrlProtocols;
1552 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1553 // with LocalSettings files from 1.5
1554 if ( is_array( $wgUrlProtocols ) ) {
1555 $protocols = array();
1556 foreach ($wgUrlProtocols as $protocol)
1557 $protocols[] = preg_quote( $protocol, '/' );
1559 return implode( '|', $protocols );
1561 return $wgUrlProtocols;
1566 * Safety wrapper around ini_get() for boolean settings.
1567 * The values returned from ini_get() are pre-normalized for settings
1568 * set via php.ini or php_flag/php_admin_flag... but *not*
1569 * for those set via php_value/php_admin_value.
1571 * It's fairly common for people to use php_value instead of php_flag,
1572 * which can leave you with an 'off' setting giving a false positive
1573 * for code that just takes the ini_get() return value as a boolean.
1575 * To make things extra interesting, setting via php_value accepts
1576 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1577 * Unrecognized values go false... again opposite PHP's own coercion
1578 * from string to bool.
1580 * Luckily, 'properly' set settings will always come back as '0' or '1',
1581 * so we only have to worry about them and the 'improper' settings.
1583 * I frickin' hate PHP... :P
1585 * @param string $setting
1588 function wfIniGetBool( $setting ) {
1589 $val = ini_get( $setting );
1590 // 'on' and 'true' can't have whitespace around them, but '1' can.
1591 return strtolower( $val ) == 'on'
1592 ||
strtolower( $val ) == 'true'
1593 ||
strtolower( $val ) == 'yes'
1594 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1598 * Execute a shell command, with time and memory limits mirrored from the PHP
1599 * configuration if supported.
1600 * @param $cmd Command line, properly escaped for shell.
1601 * @param &$retval optional, will receive the program's exit code.
1602 * (non-zero is usually failure)
1603 * @return collected stdout as a string (trailing newlines stripped)
1605 function wfShellExec( $cmd, &$retval=null ) {
1606 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1608 if( wfIniGetBool( 'safe_mode' ) ) {
1609 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1611 return "Unable to run external programs in safe mode.";
1614 if ( php_uname( 's' ) == 'Linux' ) {
1615 $time = intval( ini_get( 'max_execution_time' ) );
1616 $mem = intval( $wgMaxShellMemory );
1617 $filesize = intval( $wgMaxShellFileSize );
1619 if ( $time > 0 && $mem > 0 ) {
1620 $script = "$IP/bin/ulimit4.sh";
1621 if ( is_executable( $script ) ) {
1622 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1625 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1626 # This is a hack to work around PHP's flawed invocation of cmd.exe
1627 # http://news.php.net/php.internals/21796
1628 $cmd = '"' . $cmd . '"';
1630 wfDebug( "wfShellExec: $cmd\n" );
1632 $retval = 1; // error by default?
1634 passthru( $cmd, $retval );
1635 $output = ob_get_contents();
1642 * This function works like "use VERSION" in Perl, the program will die with a
1643 * backtrace if the current version of PHP is less than the version provided
1645 * This is useful for extensions which due to their nature are not kept in sync
1646 * with releases, and might depend on other versions of PHP than the main code
1648 * Note: PHP might die due to parsing errors in some cases before it ever
1649 * manages to call this function, such is life
1651 * @see perldoc -f use
1653 * @param mixed $version The version to check, can be a string, an integer, or
1656 function wfUsePHP( $req_ver ) {
1657 $php_ver = PHP_VERSION
;
1659 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1660 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1664 * This function works like "use VERSION" in Perl except it checks the version
1665 * of MediaWiki, the program will die with a backtrace if the current version
1666 * of MediaWiki is less than the version provided.
1668 * This is useful for extensions which due to their nature are not kept in sync
1671 * @see perldoc -f use
1673 * @param mixed $version The version to check, can be a string, an integer, or
1676 function wfUseMW( $req_ver ) {
1679 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1680 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1684 * @deprecated use StringUtils::escapeRegexReplacement
1686 function wfRegexReplacement( $string ) {
1687 return StringUtils
::escapeRegexReplacement( $string );
1691 * Return the final portion of a pathname.
1692 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1693 * http://bugs.php.net/bug.php?id=33898
1695 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1696 * We'll consider it so always, as we don't want \s in our Unix paths either.
1698 * @param string $path
1699 * @param string $suffix to remove if present
1702 function wfBaseName( $path, $suffix='' ) {
1703 $encSuffix = ($suffix == '')
1705 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1707 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1715 * Generate a relative path name to the given file.
1716 * May explode on non-matching case-insensitive paths,
1717 * funky symlinks, etc.
1719 * @param string $path Absolute destination path including target filename
1720 * @param string $from Absolute source path, directory only
1723 function wfRelativePath( $path, $from ) {
1724 // Normalize mixed input on Windows...
1725 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1726 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1728 // Trim trailing slashes -- fix for drive root
1729 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
1730 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
1732 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1733 $against = explode( DIRECTORY_SEPARATOR
, $from );
1735 if( $pieces[0] !== $against[0] ) {
1736 // Non-matching Windows drive letters?
1737 // Return a full path.
1741 // Trim off common prefix
1742 while( count( $pieces ) && count( $against )
1743 && $pieces[0] == $against[0] ) {
1744 array_shift( $pieces );
1745 array_shift( $against );
1748 // relative dots to bump us to the parent
1749 while( count( $against ) ) {
1750 array_unshift( $pieces, '..' );
1751 array_shift( $against );
1754 array_push( $pieces, wfBaseName( $path ) );
1756 return implode( DIRECTORY_SEPARATOR
, $pieces );
1760 * array_merge() does awful things with "numeric" indexes, including
1761 * string indexes when happen to look like integers. When we want
1762 * to merge arrays with arbitrary string indexes, we don't want our
1763 * arrays to be randomly corrupted just because some of them consist
1766 * Fuck you, PHP. Fuck you in the ear!
1768 * @param array $array1, [$array2, [...]]
1771 function wfArrayMerge( $array1/* ... */ ) {
1773 for( $i = 1; $i < func_num_args(); $i++
) {
1774 foreach( func_get_arg( $i ) as $key => $value ) {
1775 $out[$key] = $value;
1782 * Make a URL index, appropriate for the el_index field of externallinks.
1784 function wfMakeUrlIndex( $url ) {
1785 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1786 wfSuppressWarnings();
1787 $bits = parse_url( $url );
1788 wfRestoreWarnings();
1792 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1794 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1796 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1798 // parse_url detects for news: and mailto: the host part of an url as path
1799 // We have to correct this wrong detection
1800 if ( isset ( $bits['path'] ) ) {
1801 $bits['host'] = $bits['path'];
1808 // Reverse the labels in the hostname, convert to lower case
1809 // For emails reverse domainpart only
1810 if ( $bits['scheme'] == 'mailto' ) {
1811 $mailparts = explode( '@', $bits['host'], 2 );
1812 if ( count($mailparts) === 2 ) {
1813 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1815 // No domain specified, don't mangle it
1818 $reversedHost = $domainpart . '@' . $mailparts[0];
1820 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1822 // Add an extra dot to the end
1823 // Why? Is it in wrong place in mailto links?
1824 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1825 $reversedHost .= '.';
1827 // Reconstruct the pseudo-URL
1828 $prot = $bits['scheme'];
1829 $index = "$prot$delimiter$reversedHost";
1830 // Leave out user and password. Add the port, path, query and fragment
1831 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1832 if ( isset( $bits['path'] ) ) {
1833 $index .= $bits['path'];
1837 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1838 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1843 * Do any deferred updates and clear the list
1844 * TODO: This could be in Wiki.php if that class made any sense at all
1846 function wfDoUpdates()
1848 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1849 foreach ( $wgDeferredUpdateList as $update ) {
1850 $update->doUpdate();
1852 foreach ( $wgPostCommitUpdateList as $update ) {
1853 $update->doUpdate();
1855 $wgDeferredUpdateList = array();
1856 $wgPostCommitUpdateList = array();
1860 * @deprecated use StringUtils::explodeMarkup
1862 function wfExplodeMarkup( $separator, $text ) {
1863 return StringUtils
::explodeMarkup( $separator, $text );
1867 * Convert an arbitrarily-long digit string from one numeric base
1868 * to another, optionally zero-padding to a minimum column width.
1870 * Supports base 2 through 36; digit values 10-36 are represented
1871 * as lowercase letters a-z. Input is case-insensitive.
1873 * @param $input string of digits
1874 * @param $sourceBase int 2-36
1875 * @param $destBase int 2-36
1876 * @param $pad int 1 or greater
1877 * @param $lowercase bool
1878 * @return string or false on invalid input
1880 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
1881 $input = strval( $input );
1882 if( $sourceBase < 2 ||
1887 $sourceBase != intval( $sourceBase ) ||
1888 $destBase != intval( $destBase ) ||
1889 $pad != intval( $pad ) ||
1890 !is_string( $input ) ||
1894 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
1895 $inDigits = array();
1898 // Decode and validate input string
1899 $input = strtolower( $input );
1900 for( $i = 0; $i < strlen( $input ); $i++
) {
1901 $n = strpos( $digitChars, $input{$i} );
1902 if( $n === false ||
$n > $sourceBase ) {
1908 // Iterate over the input, modulo-ing out an output digit
1909 // at a time until input is gone.
1910 while( count( $inDigits ) ) {
1912 $workDigits = array();
1915 foreach( $inDigits as $digit ) {
1916 $work *= $sourceBase;
1919 if( $work < $destBase ) {
1920 // Gonna need to pull another digit.
1921 if( count( $workDigits ) ) {
1922 // Avoid zero-padding; this lets us find
1923 // the end of the input very easily when
1924 // length drops to zero.
1928 // Finally! Actual division!
1929 $workDigits[] = intval( $work / $destBase );
1931 // Isn't it annoying that most programming languages
1932 // don't have a single divide-and-remainder operator,
1933 // even though the CPU implements it that way?
1934 $work = $work %
$destBase;
1938 // All that division leaves us with a remainder,
1939 // which is conveniently our next output digit.
1940 $outChars .= $digitChars[$work];
1943 $inDigits = $workDigits;
1946 while( strlen( $outChars ) < $pad ) {
1950 return strrev( $outChars );
1954 * Create an object with a given name and an array of construct parameters
1955 * @param string $name
1956 * @param array $p parameters
1958 function wfCreateObject( $name, $p ){
1959 $p = array_values( $p );
1960 switch ( count( $p ) ) {
1964 return new $name( $p[0] );
1966 return new $name( $p[0], $p[1] );
1968 return new $name( $p[0], $p[1], $p[2] );
1970 return new $name( $p[0], $p[1], $p[2], $p[3] );
1972 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1974 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
1976 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
1981 * Alias for modularized function
1982 * @deprecated Use Http::get() instead
1984 function wfGetHTTP( $url, $timeout = 'default' ) {
1985 wfDeprecated(__FUNCTION__
);
1986 return Http
::get( $url, $timeout );
1990 * Alias for modularized function
1991 * @deprecated Use Http::isLocalURL() instead
1993 function wfIsLocalURL( $url ) {
1994 wfDeprecated(__FUNCTION__
);
1995 return Http
::isLocalURL( $url );
1998 function wfHttpOnlySafe() {
1999 global $wgHttpOnlyBlacklist;
2000 if( !version_compare("5.2", PHP_VERSION
, "<") )
2003 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2004 foreach( $wgHttpOnlyBlacklist as $regex ) {
2005 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2015 * Initialise php session
2017 function wfSetupSession() {
2018 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2019 if( $wgSessionsInMemcached ) {
2020 require_once( 'MemcachedSessions.php' );
2021 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2022 # If it's left on 'user' or another setting from another
2023 # application, it will end up failing. Try to recover.
2024 ini_set ( 'session.save_handler', 'files' );
2026 $httpOnlySafe = wfHttpOnlySafe();
2027 wfDebugLog( 'cookie',
2028 'session_set_cookie_params: "' . implode( '", "',
2034 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2035 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2036 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2038 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2039 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2041 session_cache_limiter( 'private, must-revalidate' );
2042 wfSuppressWarnings();
2044 wfRestoreWarnings();
2048 * Get an object from the precompiled serialized directory
2050 * @return mixed The variable on success, false on failure
2052 function wfGetPrecompiledData( $name ) {
2055 $file = "$IP/serialized/$name";
2056 if ( file_exists( $file ) ) {
2057 $blob = file_get_contents( $file );
2059 return unserialize( $blob );
2065 function wfGetCaller( $level = 2 ) {
2066 $backtrace = wfDebugBacktrace();
2067 if ( isset( $backtrace[$level] ) ) {
2068 return wfFormatStackFrame($backtrace[$level]);
2070 $caller = 'unknown';
2075 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2076 function wfGetAllCallers() {
2077 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2080 /** Return a string representation of frame */
2081 function wfFormatStackFrame($frame) {
2082 return isset( $frame["class"] )?
2083 $frame["class"]."::".$frame["function"]:
2090 function wfMemcKey( /*... */ ) {
2091 $args = func_get_args();
2092 $key = wfWikiID() . ':' . implode( ':', $args );
2097 * Get a cache key for a foreign DB
2099 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2100 $args = array_slice( func_get_args(), 2 );
2102 $key = "$db-$prefix:" . implode( ':', $args );
2104 $key = $db . ':' . implode( ':', $args );
2110 * Get an ASCII string identifying this wiki
2111 * This is used as a prefix in memcached keys
2113 function wfWikiID( $db = null ) {
2114 if( $db instanceof Database
) {
2115 return $db->getWikiID();
2117 global $wgDBprefix, $wgDBname;
2118 if ( $wgDBprefix ) {
2119 return "$wgDBname-$wgDBprefix";
2127 * Split a wiki ID into DB name and table prefix
2129 function wfSplitWikiID( $wiki ) {
2130 $bits = explode( '-', $wiki, 2 );
2131 if ( count( $bits ) < 2 ) {
2138 * Get a Database object.
2139 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2140 * master (for write queries), DB_SLAVE for potentially lagged
2141 * read queries, or an integer >= 0 for a particular server.
2143 * @param mixed $groups Query groups. An array of group names that this query
2144 * belongs to. May contain a single string if the query is only
2147 * @param string $wiki The wiki ID, or false for the current wiki
2149 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2150 * will always return the same object, unless the underlying connection or load
2151 * balancer is manually destroyed.
2153 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2154 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2158 * Get a load balancer object.
2160 * @param array $groups List of query groups
2161 * @param string $wiki Wiki ID, or false for the current wiki
2162 * @return LoadBalancer
2164 function wfGetLB( $wiki = false ) {
2165 return wfGetLBFactory()->getMainLB( $wiki );
2169 * Get the load balancer factory object
2171 function &wfGetLBFactory() {
2172 return LBFactory
::singleton();
2177 * Shortcut for RepoGroup::singleton()->findFile()
2178 * @param mixed $title Title object or string. May be interwiki.
2179 * @param mixed $time Requested time for an archived image, or false for the
2180 * current version. An image object will be returned which
2181 * was created at the specified time.
2182 * @param mixed $flags FileRepo::FIND_ flags
2183 * @return File, or false if the file does not exist
2185 function wfFindFile( $title, $time = false, $flags = 0 ) {
2186 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2190 * Get an object referring to a locally registered file.
2191 * Returns a valid placeholder object if the file does not exist.
2193 function wfLocalFile( $title ) {
2194 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2198 * Should low-performance queries be disabled?
2202 function wfQueriesMustScale() {
2203 global $wgMiserMode;
2205 ||
( SiteStats
::pages() > 100000
2206 && SiteStats
::edits() > 1000000
2207 && SiteStats
::users() > 10000 );
2211 * Get the path to a specified script file, respecting file
2212 * extensions; this is a wrapper around $wgScriptExtension etc.
2214 * @param string $script Script filename, sans extension
2217 function wfScript( $script = 'index' ) {
2218 global $wgScriptPath, $wgScriptExtension;
2219 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2223 * Convenience function converts boolean values into "true"
2224 * or "false" (string) values
2226 * @param bool $value
2229 function wfBoolToStr( $value ) {
2230 return $value ?
'true' : 'false';
2234 * Load an extension messages file
2236 * @param string $extensionName Name of extension to load messages from\for.
2237 * @param string $langcode Language to load messages for, or false for default
2238 * behvaiour (en, content language and user language).
2240 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2241 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2243 #For recording whether extension message files have been loaded in a given language.
2244 static $loaded = array();
2246 if( !array_key_exists( $extensionName, $loaded ) ) {
2247 $loaded[$extensionName] = array();
2250 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2251 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2254 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2255 # Just do en, content language and user language.
2256 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2257 # Mark that they have been loaded.
2258 $loaded[$extensionName]['en'] = true;
2259 $loaded[$extensionName][$wgLang->getCode()] = true;
2260 $loaded[$extensionName][$wgContLang->getCode()] = true;
2261 # Mark that this part has been done to avoid weird if statements.
2262 $loaded[$extensionName]['*'] = true;
2263 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2264 # Load messages for specified language.
2265 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2266 # Mark that they have been loaded.
2267 $loaded[$extensionName][$langcode] = true;
2272 * Get a platform-independent path to the null file, e.g.
2277 function wfGetNull() {
2278 return wfIsWindows()
2284 * Displays a maxlag error
2286 * @param string $host Server that lags the most
2287 * @param int $lag Maxlag (actual)
2288 * @param int $maxLag Maxlag (requested)
2290 function wfMaxlagError( $host, $lag, $maxLag ) {
2291 global $wgShowHostnames;
2292 header( 'HTTP/1.1 503 Service Unavailable' );
2293 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2294 header( 'X-Database-Lag: ' . intval( $lag ) );
2295 header( 'Content-Type: text/plain' );
2296 if( $wgShowHostnames ) {
2297 echo "Waiting for $host: $lag seconds lagged\n";
2299 echo "Waiting for a database server: $lag seconds lagged\n";
2304 * Throws an E_USER_NOTICE saying that $function is deprecated
2305 * @param string $function
2308 function wfDeprecated( $function ) {
2309 global $wgDebugLogFile;
2310 if ( !$wgDebugLogFile ) {
2313 $callers = wfDebugBacktrace();
2314 if( isset( $callers[2] ) ){
2315 $callerfunc = $callers[2];
2316 $callerfile = $callers[1];
2317 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2318 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2320 $file = '(internal function)';
2323 if( isset( $callerfunc['class'] ) )
2324 $func .= $callerfunc['class'] . '::';
2325 $func .= @$callerfunc['function'];
2326 $msg = "Use of $function is deprecated. Called from $func in $file";
2328 $msg = "Use of $function is deprecated.";
2330 wfDebug( "$msg\n" );
2334 * Sleep until the worst slave's replication lag is less than or equal to
2335 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2336 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2337 * a no-op if there are no slaves.
2339 * Every time the function has to wait for a slave, it will print a message to
2340 * that effect (and then sleep for a little while), so it's probably not best
2341 * to use this outside maintenance scripts in its present form.
2343 * @param int $maxLag
2346 function wfWaitForSlaves( $maxLag ) {
2349 list( $host, $lag ) = $lb->getMaxLag();
2350 while( $lag > $maxLag ) {
2351 $name = @gethostbyaddr
( $host );
2352 if( $name !== false ) {
2355 print "Waiting for $host (lagged $lag seconds)...\n";
2357 list( $host, $lag ) = $lb->getMaxLag();
2362 /** Generate a random 32-character hexadecimal token.
2363 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2365 function wfGenerateToken( $salt = '' ) {
2366 $salt = serialize($salt);
2368 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2372 * Replace all invalid characters with -
2373 * @param mixed $title Filename to process
2375 function wfStripIllegalFilenameChars( $name ) {
2376 $name = wfBaseName( $name );
2377 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );