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 ) {
865 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
866 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
869 $wgOut->addHTML( $s );
874 * Provide a simple HTTP error.
876 function wfHttpError( $code, $label, $desc ) {
879 header( "HTTP/1.0 $code $label" );
880 header( "Status: $code $label" );
881 $wgOut->sendCacheControl();
883 header( 'Content-type: text/html; charset=utf-8' );
884 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
885 "<html><head><title>" .
886 htmlspecialchars( $label ) .
887 "</title></head><body><h1>" .
888 htmlspecialchars( $label ) .
890 nl2br( htmlspecialchars( $desc ) ) .
891 "</p></body></html>\n";
895 * Clear away any user-level output buffers, discarding contents.
897 * Suitable for 'starting afresh', for instance when streaming
898 * relatively large amounts of data without buffering, or wanting to
899 * output image files without ob_gzhandler's compression.
901 * The optional $resetGzipEncoding parameter controls suppression of
902 * the Content-Encoding header sent by ob_gzhandler; by default it
903 * is left. See comments for wfClearOutputBuffers() for why it would
906 * Note that some PHP configuration options may add output buffer
907 * layers which cannot be removed; these are left in place.
909 * @param bool $resetGzipEncoding
911 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
912 if( $resetGzipEncoding ) {
913 // Suppress Content-Encoding and Content-Length
914 // headers from 1.10+s wfOutputHandler
915 global $wgDisableOutputCompression;
916 $wgDisableOutputCompression = true;
918 while( $status = ob_get_status() ) {
919 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
920 // Probably from zlib.output_compression or other
921 // PHP-internal setting which can't be removed.
923 // Give up, and hope the result doesn't break
927 if( !ob_end_clean() ) {
928 // Could not remove output buffer handler; abort now
929 // to avoid getting in some kind of infinite loop.
932 if( $resetGzipEncoding ) {
933 if( $status['name'] == 'ob_gzhandler' ) {
934 // Reset the 'Content-Encoding' field set by this handler
935 // so we can start fresh.
936 header( 'Content-Encoding:' );
943 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
945 * Clear away output buffers, but keep the Content-Encoding header
946 * produced by ob_gzhandler, if any.
948 * This should be used for HTTP 304 responses, where you need to
949 * preserve the Content-Encoding header of the real result, but
950 * also need to suppress the output of ob_gzhandler to keep to spec
951 * and avoid breaking Firefox in rare cases where the headers and
952 * body are broken over two packets.
954 function wfClearOutputBuffers() {
955 wfResetOutputBuffers( false );
959 * Converts an Accept-* header into an array mapping string values to quality
962 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
963 # No arg means accept anything (per HTTP spec)
965 return array( $def => 1.0 );
970 $parts = explode( ',', $accept );
972 foreach( $parts as $part ) {
973 # FIXME: doesn't deal with params like 'text/html; level=1'
974 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
976 if( !isset( $qpart ) ) {
977 $prefs[$value] = 1.0;
978 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
979 $prefs[$value] = floatval($match[1]);
987 * Checks if a given MIME type matches any of the keys in the given
988 * array. Basic wildcards are accepted in the array keys.
990 * Returns the matching MIME type (or wildcard) if a match, otherwise
993 * @param string $type
994 * @param array $avail
998 function mimeTypeMatch( $type, $avail ) {
999 if( array_key_exists($type, $avail) ) {
1002 $parts = explode( '/', $type );
1003 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1004 return $parts[0] . '/*';
1005 } elseif( array_key_exists( '*/*', $avail ) ) {
1014 * Returns the 'best' match between a client's requested internet media types
1015 * and the server's list of available types. Each list should be an associative
1016 * array of type to preference (preference is a float between 0.0 and 1.0).
1017 * Wildcards in the types are acceptable.
1019 * @param array $cprefs Client's acceptable type list
1020 * @param array $sprefs Server's offered types
1023 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1024 * XXX: generalize to negotiate other stuff
1026 function wfNegotiateType( $cprefs, $sprefs ) {
1029 foreach( array_keys($sprefs) as $type ) {
1030 $parts = explode( '/', $type );
1031 if( $parts[1] != '*' ) {
1032 $ckey = mimeTypeMatch( $type, $cprefs );
1034 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1039 foreach( array_keys( $cprefs ) as $type ) {
1040 $parts = explode( '/', $type );
1041 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1042 $skey = mimeTypeMatch( $type, $sprefs );
1044 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1052 foreach( array_keys( $combine ) as $type ) {
1053 if( $combine[$type] > $bestq ) {
1055 $bestq = $combine[$type];
1064 * Returns an array where the values in the first array are replaced by the
1065 * values in the second array with the corresponding keys
1069 function wfArrayLookup( $a, $b ) {
1070 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1074 * Convenience function; returns MediaWiki timestamp for the present time.
1077 function wfTimestampNow() {
1079 return wfTimestamp( TS_MW
, time() );
1083 * Reference-counted warning suppression
1085 function wfSuppressWarnings( $end = false ) {
1086 static $suppressCount = 0;
1087 static $originalLevel = false;
1090 if ( $suppressCount ) {
1092 if ( !$suppressCount ) {
1093 error_reporting( $originalLevel );
1097 if ( !$suppressCount ) {
1098 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1105 * Restore error level to previous value
1107 function wfRestoreWarnings() {
1108 wfSuppressWarnings( true );
1111 # Autodetect, convert and provide timestamps of various types
1114 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1116 define('TS_UNIX', 0);
1119 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1124 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1129 * RFC 2822 format, for E-mail and HTTP headers
1131 define('TS_RFC2822', 3);
1134 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1136 * This is used by Special:Export
1138 define('TS_ISO_8601', 4);
1141 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1143 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1144 * DateTime tag and page 36 for the DateTimeOriginal and
1145 * DateTimeDigitized tags.
1147 define('TS_EXIF', 5);
1150 * Oracle format time.
1152 define('TS_ORACLE', 6);
1155 * Postgres format time.
1157 define('TS_POSTGRES', 7);
1160 * @param mixed $outputtype A timestamp in one of the supported formats, the
1161 * function will autodetect which format is supplied
1162 * and act accordingly.
1163 * @return string Time in the format specified in $outputtype
1165 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1170 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1172 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1174 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1176 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1179 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1181 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1182 str_replace("+00:00", "UTC", $ts)));
1183 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1185 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1187 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1190 # Bogus value; fall back to the epoch...
1191 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1195 if (count( $da ) ) {
1196 // Warning! gmmktime() acts oddly if the month or day is set to 0
1197 // We may want to handle that explicitly at some point
1198 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1199 (int)$da[2],(int)$da[3],(int)$da[1]);
1202 switch($outputtype) {
1206 return gmdate( 'YmdHis', $uts );
1208 return gmdate( 'Y-m-d H:i:s', $uts );
1210 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1211 // This shouldn't ever be used, but is included for completeness
1213 return gmdate( 'Y:m:d H:i:s', $uts );
1215 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1217 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1219 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1221 throw new MWException( 'wfTimestamp() called with illegal output type.');
1226 * Return a formatted timestamp, or null if input is null.
1227 * For dealing with nullable timestamp columns in the database.
1228 * @param int $outputtype
1232 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1233 if( is_null( $ts ) ) {
1236 return wfTimestamp( $outputtype, $ts );
1241 * Check if the operating system is Windows
1243 * @return bool True if it's Windows, False otherwise.
1245 function wfIsWindows() {
1246 if (substr(php_uname(), 0, 7) == 'Windows') {
1254 * Swap two variables
1256 function swap( &$x, &$y ) {
1262 function wfGetCachedNotice( $name ) {
1263 global $wgOut, $parserMemc;
1264 $fname = 'wfGetCachedNotice';
1265 wfProfileIn( $fname );
1269 if( $name === 'default' ) {
1271 global $wgSiteNotice;
1272 $notice = $wgSiteNotice;
1273 if( empty( $notice ) ) {
1274 wfProfileOut( $fname );
1278 $notice = wfMsgForContentNoTrans( $name );
1279 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1280 wfProfileOut( $fname );
1285 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1286 if( is_array( $cachedNotice ) ) {
1287 if( md5( $notice ) == $cachedNotice['hash'] ) {
1288 $notice = $cachedNotice['html'];
1297 if( is_object( $wgOut ) ) {
1298 $parsed = $wgOut->parse( $notice );
1299 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1302 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1307 wfProfileOut( $fname );
1311 function wfGetNamespaceNotice() {
1315 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1318 $fname = 'wfGetNamespaceNotice';
1319 wfProfileIn( $fname );
1321 $key = "namespacenotice-" . $wgTitle->getNsText();
1322 $namespaceNotice = wfGetCachedNotice( $key );
1323 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1324 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1326 $namespaceNotice = "";
1329 wfProfileOut( $fname );
1330 return $namespaceNotice;
1333 function wfGetSiteNotice() {
1334 global $wgUser, $wgSiteNotice;
1335 $fname = 'wfGetSiteNotice';
1336 wfProfileIn( $fname );
1339 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1340 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1341 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1343 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1344 if( !$anonNotice ) {
1345 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1347 $siteNotice = $anonNotice;
1350 if( !$siteNotice ) {
1351 $siteNotice = wfGetCachedNotice( 'default' );
1355 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1356 wfProfileOut( $fname );
1361 * BC wrapper for MimeMagic::singleton()
1364 function &wfGetMimeMagic() {
1365 return MimeMagic
::singleton();
1369 * Tries to get the system directory for temporary files.
1370 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1371 * and if none are set /tmp is returned as the generic Unix default.
1373 * NOTE: When possible, use the tempfile() function to create temporary
1374 * files to avoid race conditions on file creation, etc.
1378 function wfTempDir() {
1379 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1380 $tmp = getenv( $var );
1381 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1385 # Hope this is Unix of some kind!
1390 * Make directory, and make all parent directories if they don't exist
1392 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1393 if( strval( $fullDir ) === '' )
1395 if( file_exists( $fullDir ) )
1398 # Go back through the paths to find the first directory that exists
1399 $currentDir = $fullDir;
1400 $createList = array();
1401 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1402 # Strip trailing slashes
1403 $currentDir = rtrim( $currentDir, '/\\' );
1405 # Add to create list
1406 $createList[] = $currentDir;
1408 # Find next delimiter searching from the end
1409 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1410 if ( $p === false ) {
1411 $currentDir = false;
1413 $currentDir = substr( $currentDir, 0, $p );
1417 if ( count( $createList ) == 0 ) {
1418 # Directory specified already exists
1420 } elseif ( $currentDir === false ) {
1421 # Went all the way back to root and it apparently doesn't exist
1422 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1425 # Now go forward creating directories
1426 $createList = array_reverse( $createList );
1428 # Is the parent directory writable?
1429 if ( $currentDir === '' ) {
1432 if ( !is_writable( $currentDir ) ) {
1433 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1437 foreach ( $createList as $dir ) {
1438 # use chmod to override the umask, as suggested by the PHP manual
1439 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1440 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1448 * Increment a statistics counter
1450 function wfIncrStats( $key ) {
1451 global $wgStatsMethod;
1453 if( $wgStatsMethod == 'udp' ) {
1454 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1457 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1458 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1459 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1461 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1462 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1463 } elseif( $wgStatsMethod == 'cache' ) {
1465 $key = wfMemcKey( 'stats', $key );
1466 if ( is_null( $wgMemc->incr( $key ) ) ) {
1467 $wgMemc->add( $key, 1 );
1475 * @param mixed $nr The number to format
1476 * @param int $acc The number of digits after the decimal point, default 2
1477 * @param bool $round Whether or not to round the value, default true
1480 function wfPercent( $nr, $acc = 2, $round = true ) {
1481 $ret = sprintf( "%.${acc}f", $nr );
1482 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1486 * Encrypt a username/password.
1488 * @param string $userid ID of the user
1489 * @param string $password Password of the user
1490 * @return string Hashed password
1491 * @deprecated Use User::crypt() or User::oldCrypt() instead
1493 function wfEncryptPassword( $userid, $password ) {
1494 wfDeprecated(__FUNCTION__
);
1495 # Just wrap around User::oldCrypt()
1496 return User
::oldCrypt($password, $userid);
1500 * Appends to second array if $value differs from that in $default
1502 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1503 if ( is_null( $changed ) ) {
1504 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1506 if ( $default[$key] !== $value ) {
1507 $changed[$key] = $value;
1512 * Since wfMsg() and co suck, they don't return false if the message key they
1513 * looked up didn't exist but a XHTML string, this function checks for the
1514 * nonexistance of messages by looking at wfMsg() output
1516 * @param $msg The message key looked up
1517 * @param $wfMsgOut The output of wfMsg*()
1520 function wfEmptyMsg( $msg, $wfMsgOut ) {
1521 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1525 * Find out whether or not a mixed variable exists in a string
1527 * @param mixed needle
1528 * @param string haystack
1531 function in_string( $needle, $str ) {
1532 return strpos( $str, $needle ) !== false;
1535 function wfSpecialList( $page, $details ) {
1537 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1538 return $page . $details;
1542 * Returns a regular expression of url protocols
1546 function wfUrlProtocols() {
1547 global $wgUrlProtocols;
1549 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1550 // with LocalSettings files from 1.5
1551 if ( is_array( $wgUrlProtocols ) ) {
1552 $protocols = array();
1553 foreach ($wgUrlProtocols as $protocol)
1554 $protocols[] = preg_quote( $protocol, '/' );
1556 return implode( '|', $protocols );
1558 return $wgUrlProtocols;
1563 * Safety wrapper around ini_get() for boolean settings.
1564 * The values returned from ini_get() are pre-normalized for settings
1565 * set via php.ini or php_flag/php_admin_flag... but *not*
1566 * for those set via php_value/php_admin_value.
1568 * It's fairly common for people to use php_value instead of php_flag,
1569 * which can leave you with an 'off' setting giving a false positive
1570 * for code that just takes the ini_get() return value as a boolean.
1572 * To make things extra interesting, setting via php_value accepts
1573 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1574 * Unrecognized values go false... again opposite PHP's own coercion
1575 * from string to bool.
1577 * Luckily, 'properly' set settings will always come back as '0' or '1',
1578 * so we only have to worry about them and the 'improper' settings.
1580 * I frickin' hate PHP... :P
1582 * @param string $setting
1585 function wfIniGetBool( $setting ) {
1586 $val = ini_get( $setting );
1587 // 'on' and 'true' can't have whitespace around them, but '1' can.
1588 return strtolower( $val ) == 'on'
1589 ||
strtolower( $val ) == 'true'
1590 ||
strtolower( $val ) == 'yes'
1591 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1595 * Execute a shell command, with time and memory limits mirrored from the PHP
1596 * configuration if supported.
1597 * @param $cmd Command line, properly escaped for shell.
1598 * @param &$retval optional, will receive the program's exit code.
1599 * (non-zero is usually failure)
1600 * @return collected stdout as a string (trailing newlines stripped)
1602 function wfShellExec( $cmd, &$retval=null ) {
1603 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1605 if( wfIniGetBool( 'safe_mode' ) ) {
1606 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1608 return "Unable to run external programs in safe mode.";
1611 if ( php_uname( 's' ) == 'Linux' ) {
1612 $time = intval( ini_get( 'max_execution_time' ) );
1613 $mem = intval( $wgMaxShellMemory );
1614 $filesize = intval( $wgMaxShellFileSize );
1616 if ( $time > 0 && $mem > 0 ) {
1617 $script = "$IP/bin/ulimit4.sh";
1618 if ( is_executable( $script ) ) {
1619 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1622 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1623 # This is a hack to work around PHP's flawed invocation of cmd.exe
1624 # http://news.php.net/php.internals/21796
1625 $cmd = '"' . $cmd . '"';
1627 wfDebug( "wfShellExec: $cmd\n" );
1629 $retval = 1; // error by default?
1631 passthru( $cmd, $retval );
1632 $output = ob_get_contents();
1639 * This function works like "use VERSION" in Perl, the program will die with a
1640 * backtrace if the current version of PHP is less than the version provided
1642 * This is useful for extensions which due to their nature are not kept in sync
1643 * with releases, and might depend on other versions of PHP than the main code
1645 * Note: PHP might die due to parsing errors in some cases before it ever
1646 * manages to call this function, such is life
1648 * @see perldoc -f use
1650 * @param mixed $version The version to check, can be a string, an integer, or
1653 function wfUsePHP( $req_ver ) {
1654 $php_ver = PHP_VERSION
;
1656 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1657 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1661 * This function works like "use VERSION" in Perl except it checks the version
1662 * of MediaWiki, the program will die with a backtrace if the current version
1663 * of MediaWiki is less than the version provided.
1665 * This is useful for extensions which due to their nature are not kept in sync
1668 * @see perldoc -f use
1670 * @param mixed $version The version to check, can be a string, an integer, or
1673 function wfUseMW( $req_ver ) {
1676 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1677 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1681 * @deprecated use StringUtils::escapeRegexReplacement
1683 function wfRegexReplacement( $string ) {
1684 return StringUtils
::escapeRegexReplacement( $string );
1688 * Return the final portion of a pathname.
1689 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1690 * http://bugs.php.net/bug.php?id=33898
1692 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1693 * We'll consider it so always, as we don't want \s in our Unix paths either.
1695 * @param string $path
1696 * @param string $suffix to remove if present
1699 function wfBaseName( $path, $suffix='' ) {
1700 $encSuffix = ($suffix == '')
1702 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1704 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1712 * Generate a relative path name to the given file.
1713 * May explode on non-matching case-insensitive paths,
1714 * funky symlinks, etc.
1716 * @param string $path Absolute destination path including target filename
1717 * @param string $from Absolute source path, directory only
1720 function wfRelativePath( $path, $from ) {
1721 // Normalize mixed input on Windows...
1722 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1723 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1725 // Trim trailing slashes -- fix for drive root
1726 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
1727 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
1729 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1730 $against = explode( DIRECTORY_SEPARATOR
, $from );
1732 if( $pieces[0] !== $against[0] ) {
1733 // Non-matching Windows drive letters?
1734 // Return a full path.
1738 // Trim off common prefix
1739 while( count( $pieces ) && count( $against )
1740 && $pieces[0] == $against[0] ) {
1741 array_shift( $pieces );
1742 array_shift( $against );
1745 // relative dots to bump us to the parent
1746 while( count( $against ) ) {
1747 array_unshift( $pieces, '..' );
1748 array_shift( $against );
1751 array_push( $pieces, wfBaseName( $path ) );
1753 return implode( DIRECTORY_SEPARATOR
, $pieces );
1757 * array_merge() does awful things with "numeric" indexes, including
1758 * string indexes when happen to look like integers. When we want
1759 * to merge arrays with arbitrary string indexes, we don't want our
1760 * arrays to be randomly corrupted just because some of them consist
1763 * Fuck you, PHP. Fuck you in the ear!
1765 * @param array $array1, [$array2, [...]]
1768 function wfArrayMerge( $array1/* ... */ ) {
1770 for( $i = 1; $i < func_num_args(); $i++
) {
1771 foreach( func_get_arg( $i ) as $key => $value ) {
1772 $out[$key] = $value;
1779 * Make a URL index, appropriate for the el_index field of externallinks.
1781 function wfMakeUrlIndex( $url ) {
1782 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1783 wfSuppressWarnings();
1784 $bits = parse_url( $url );
1785 wfRestoreWarnings();
1789 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1791 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1793 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1795 // parse_url detects for news: and mailto: the host part of an url as path
1796 // We have to correct this wrong detection
1797 if ( isset ( $bits['path'] ) ) {
1798 $bits['host'] = $bits['path'];
1805 // Reverse the labels in the hostname, convert to lower case
1806 // For emails reverse domainpart only
1807 if ( $bits['scheme'] == 'mailto' ) {
1808 $mailparts = explode( '@', $bits['host'], 2 );
1809 if ( count($mailparts) === 2 ) {
1810 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1812 // No domain specified, don't mangle it
1815 $reversedHost = $domainpart . '@' . $mailparts[0];
1817 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1819 // Add an extra dot to the end
1820 // Why? Is it in wrong place in mailto links?
1821 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1822 $reversedHost .= '.';
1824 // Reconstruct the pseudo-URL
1825 $prot = $bits['scheme'];
1826 $index = "$prot$delimiter$reversedHost";
1827 // Leave out user and password. Add the port, path, query and fragment
1828 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1829 if ( isset( $bits['path'] ) ) {
1830 $index .= $bits['path'];
1834 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1835 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1840 * Do any deferred updates and clear the list
1841 * TODO: This could be in Wiki.php if that class made any sense at all
1843 function wfDoUpdates()
1845 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1846 foreach ( $wgDeferredUpdateList as $update ) {
1847 $update->doUpdate();
1849 foreach ( $wgPostCommitUpdateList as $update ) {
1850 $update->doUpdate();
1852 $wgDeferredUpdateList = array();
1853 $wgPostCommitUpdateList = array();
1857 * @deprecated use StringUtils::explodeMarkup
1859 function wfExplodeMarkup( $separator, $text ) {
1860 return StringUtils
::explodeMarkup( $separator, $text );
1864 * Convert an arbitrarily-long digit string from one numeric base
1865 * to another, optionally zero-padding to a minimum column width.
1867 * Supports base 2 through 36; digit values 10-36 are represented
1868 * as lowercase letters a-z. Input is case-insensitive.
1870 * @param $input string of digits
1871 * @param $sourceBase int 2-36
1872 * @param $destBase int 2-36
1873 * @param $pad int 1 or greater
1874 * @param $lowercase bool
1875 * @return string or false on invalid input
1877 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
1878 $input = strval( $input );
1879 if( $sourceBase < 2 ||
1884 $sourceBase != intval( $sourceBase ) ||
1885 $destBase != intval( $destBase ) ||
1886 $pad != intval( $pad ) ||
1887 !is_string( $input ) ||
1891 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
1892 $inDigits = array();
1895 // Decode and validate input string
1896 $input = strtolower( $input );
1897 for( $i = 0; $i < strlen( $input ); $i++
) {
1898 $n = strpos( $digitChars, $input{$i} );
1899 if( $n === false ||
$n > $sourceBase ) {
1905 // Iterate over the input, modulo-ing out an output digit
1906 // at a time until input is gone.
1907 while( count( $inDigits ) ) {
1909 $workDigits = array();
1912 foreach( $inDigits as $digit ) {
1913 $work *= $sourceBase;
1916 if( $work < $destBase ) {
1917 // Gonna need to pull another digit.
1918 if( count( $workDigits ) ) {
1919 // Avoid zero-padding; this lets us find
1920 // the end of the input very easily when
1921 // length drops to zero.
1925 // Finally! Actual division!
1926 $workDigits[] = intval( $work / $destBase );
1928 // Isn't it annoying that most programming languages
1929 // don't have a single divide-and-remainder operator,
1930 // even though the CPU implements it that way?
1931 $work = $work %
$destBase;
1935 // All that division leaves us with a remainder,
1936 // which is conveniently our next output digit.
1937 $outChars .= $digitChars[$work];
1940 $inDigits = $workDigits;
1943 while( strlen( $outChars ) < $pad ) {
1947 return strrev( $outChars );
1951 * Create an object with a given name and an array of construct parameters
1952 * @param string $name
1953 * @param array $p parameters
1955 function wfCreateObject( $name, $p ){
1956 $p = array_values( $p );
1957 switch ( count( $p ) ) {
1961 return new $name( $p[0] );
1963 return new $name( $p[0], $p[1] );
1965 return new $name( $p[0], $p[1], $p[2] );
1967 return new $name( $p[0], $p[1], $p[2], $p[3] );
1969 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1971 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
1973 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
1978 * Alias for modularized function
1979 * @deprecated Use Http::get() instead
1981 function wfGetHTTP( $url, $timeout = 'default' ) {
1982 wfDeprecated(__FUNCTION__
);
1983 return Http
::get( $url, $timeout );
1987 * Alias for modularized function
1988 * @deprecated Use Http::isLocalURL() instead
1990 function wfIsLocalURL( $url ) {
1991 wfDeprecated(__FUNCTION__
);
1992 return Http
::isLocalURL( $url );
1995 function wfHttpOnlySafe() {
1996 global $wgHttpOnlyBlacklist;
1997 if( !version_compare("5.2", PHP_VERSION
, "<") )
2000 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2001 foreach( $wgHttpOnlyBlacklist as $regex ) {
2002 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2012 * Initialise php session
2014 function wfSetupSession() {
2015 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2016 if( $wgSessionsInMemcached ) {
2017 require_once( 'MemcachedSessions.php' );
2018 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2019 # If it's left on 'user' or another setting from another
2020 # application, it will end up failing. Try to recover.
2021 ini_set ( 'session.save_handler', 'files' );
2023 $httpOnlySafe = wfHttpOnlySafe();
2024 wfDebugLog( 'cookie',
2025 'session_set_cookie_params: "' . implode( '", "',
2031 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2032 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2033 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2035 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2036 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2038 session_cache_limiter( 'private, must-revalidate' );
2039 wfSuppressWarnings();
2041 wfRestoreWarnings();
2045 * Get an object from the precompiled serialized directory
2047 * @return mixed The variable on success, false on failure
2049 function wfGetPrecompiledData( $name ) {
2052 $file = "$IP/serialized/$name";
2053 if ( file_exists( $file ) ) {
2054 $blob = file_get_contents( $file );
2056 return unserialize( $blob );
2062 function wfGetCaller( $level = 2 ) {
2063 $backtrace = wfDebugBacktrace();
2064 if ( isset( $backtrace[$level] ) ) {
2065 return wfFormatStackFrame($backtrace[$level]);
2067 $caller = 'unknown';
2072 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2073 function wfGetAllCallers() {
2074 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2077 /** Return a string representation of frame */
2078 function wfFormatStackFrame($frame) {
2079 return isset( $frame["class"] )?
2080 $frame["class"]."::".$frame["function"]:
2087 function wfMemcKey( /*... */ ) {
2088 $args = func_get_args();
2089 $key = wfWikiID() . ':' . implode( ':', $args );
2094 * Get a cache key for a foreign DB
2096 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2097 $args = array_slice( func_get_args(), 2 );
2099 $key = "$db-$prefix:" . implode( ':', $args );
2101 $key = $db . ':' . implode( ':', $args );
2107 * Get an ASCII string identifying this wiki
2108 * This is used as a prefix in memcached keys
2110 function wfWikiID( $db = null ) {
2111 if( $db instanceof Database
) {
2112 return $db->getWikiID();
2114 global $wgDBprefix, $wgDBname;
2115 if ( $wgDBprefix ) {
2116 return "$wgDBname-$wgDBprefix";
2124 * Split a wiki ID into DB name and table prefix
2126 function wfSplitWikiID( $wiki ) {
2127 $bits = explode( '-', $wiki, 2 );
2128 if ( count( $bits ) < 2 ) {
2135 * Get a Database object.
2136 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2137 * master (for write queries), DB_SLAVE for potentially lagged
2138 * read queries, or an integer >= 0 for a particular server.
2140 * @param mixed $groups Query groups. An array of group names that this query
2141 * belongs to. May contain a single string if the query is only
2144 * @param string $wiki The wiki ID, or false for the current wiki
2146 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2147 * will always return the same object, unless the underlying connection or load
2148 * balancer is manually destroyed.
2150 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2151 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2155 * Get a load balancer object.
2157 * @param array $groups List of query groups
2158 * @param string $wiki Wiki ID, or false for the current wiki
2159 * @return LoadBalancer
2161 function wfGetLB( $wiki = false ) {
2162 return wfGetLBFactory()->getMainLB( $wiki );
2166 * Get the load balancer factory object
2168 function &wfGetLBFactory() {
2169 return LBFactory
::singleton();
2174 * Shortcut for RepoGroup::singleton()->findFile()
2175 * @param mixed $title Title object or string. May be interwiki.
2176 * @param mixed $time Requested time for an archived image, or false for the
2177 * current version. An image object will be returned which
2178 * was created at the specified time.
2179 * @param mixed $flags FileRepo::FIND_ flags
2180 * @return File, or false if the file does not exist
2182 function wfFindFile( $title, $time = false, $flags = 0 ) {
2183 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2187 * Get an object referring to a locally registered file.
2188 * Returns a valid placeholder object if the file does not exist.
2190 function wfLocalFile( $title ) {
2191 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2195 * Should low-performance queries be disabled?
2199 function wfQueriesMustScale() {
2200 global $wgMiserMode;
2202 ||
( SiteStats
::pages() > 100000
2203 && SiteStats
::edits() > 1000000
2204 && SiteStats
::users() > 10000 );
2208 * Get the path to a specified script file, respecting file
2209 * extensions; this is a wrapper around $wgScriptExtension etc.
2211 * @param string $script Script filename, sans extension
2214 function wfScript( $script = 'index' ) {
2215 global $wgScriptPath, $wgScriptExtension;
2216 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2220 * Convenience function converts boolean values into "true"
2221 * or "false" (string) values
2223 * @param bool $value
2226 function wfBoolToStr( $value ) {
2227 return $value ?
'true' : 'false';
2231 * Load an extension messages file
2233 * @param string $extensionName Name of extension to load messages from\for.
2234 * @param string $langcode Language to load messages for, or false for default
2235 * behvaiour (en, content language and user language).
2237 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2238 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2240 #For recording whether extension message files have been loaded in a given language.
2241 static $loaded = array();
2243 if( !array_key_exists( $extensionName, $loaded ) ) {
2244 $loaded[$extensionName] = array();
2247 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2248 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2251 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2252 # Just do en, content language and user language.
2253 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2254 # Mark that they have been loaded.
2255 $loaded[$extensionName]['en'] = true;
2256 $loaded[$extensionName][$wgLang->getCode()] = true;
2257 $loaded[$extensionName][$wgContLang->getCode()] = true;
2258 # Mark that this part has been done to avoid weird if statements.
2259 $loaded[$extensionName]['*'] = true;
2260 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2261 # Load messages for specified language.
2262 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2263 # Mark that they have been loaded.
2264 $loaded[$extensionName][$langcode] = true;
2269 * Get a platform-independent path to the null file, e.g.
2274 function wfGetNull() {
2275 return wfIsWindows()
2281 * Displays a maxlag error
2283 * @param string $host Server that lags the most
2284 * @param int $lag Maxlag (actual)
2285 * @param int $maxLag Maxlag (requested)
2287 function wfMaxlagError( $host, $lag, $maxLag ) {
2288 global $wgShowHostnames;
2289 header( 'HTTP/1.1 503 Service Unavailable' );
2290 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2291 header( 'X-Database-Lag: ' . intval( $lag ) );
2292 header( 'Content-Type: text/plain' );
2293 if( $wgShowHostnames ) {
2294 echo "Waiting for $host: $lag seconds lagged\n";
2296 echo "Waiting for a database server: $lag seconds lagged\n";
2301 * Throws an E_USER_NOTICE saying that $function is deprecated
2302 * @param string $function
2305 function wfDeprecated( $function ) {
2306 global $wgDebugLogFile;
2307 if ( !$wgDebugLogFile ) {
2310 $callers = wfDebugBacktrace();
2311 if( isset( $callers[2] ) ){
2312 $callerfunc = $callers[2];
2313 $callerfile = $callers[1];
2314 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2315 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2317 $file = '(internal function)';
2320 if( isset( $callerfunc['class'] ) )
2321 $func .= $callerfunc['class'] . '::';
2322 $func .= @$callerfunc['function'];
2323 $msg = "Use of $function is deprecated. Called from $func in $file";
2325 $msg = "Use of $function is deprecated.";
2327 wfDebug( "$msg\n" );
2331 * Sleep until the worst slave's replication lag is less than or equal to
2332 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2333 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2334 * a no-op if there are no slaves.
2336 * Every time the function has to wait for a slave, it will print a message to
2337 * that effect (and then sleep for a little while), so it's probably not best
2338 * to use this outside maintenance scripts in its present form.
2340 * @param int $maxLag
2343 function wfWaitForSlaves( $maxLag ) {
2346 list( $host, $lag ) = $lb->getMaxLag();
2347 while( $lag > $maxLag ) {
2348 $name = @gethostbyaddr
( $host );
2349 if( $name !== false ) {
2352 print "Waiting for $host (lagged $lag seconds)...\n";
2354 list( $host, $lag ) = $lb->getMaxLag();
2359 /** Generate a random 32-character hexadecimal token.
2360 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2362 function wfGenerateToken( $salt = '' ) {
2363 $salt = serialize($salt);
2365 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2369 * Replace all invalid characters with -
2370 * @param mixed $title Filename to process
2372 function wfStripIllegalFilenameChars( $name ) {
2373 $name = wfBaseName( $name );
2374 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );