Some tweaks to the doxygen doc:
[mediawiki.git] / includes / GlobalFunctions.php
blobc9e186ab2055d2684cf19436b462b34154ccf65f
1 <?php
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
7 /**
8 * Global functions used everywhere
9 */
11 require_once dirname(__FILE__) . '/LogPage.php';
12 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__) . '/XmlFunctions.php';
15 /**
16 * Compatibility functions
18 * We more or less support PHP 5.0.x and up.
19 * Re-implementations of newer functions or functions in non-standard
20 * PHP extensions may be included here.
22 if( !function_exists('iconv') ) {
23 # iconv support is not in the default configuration and so may not be present.
24 # Assume will only ever use utf-8 and iso-8859-1.
25 # This will *not* work in all circumstances.
26 function iconv( $from, $to, $string ) {
27 if(strcasecmp( $from, $to ) == 0) return $string;
28 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
29 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
30 return $string;
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
37 $ar = array();
38 preg_match_all( '/./us', $str, $ar );
40 if( func_num_args() >= 3 ) {
41 $end = func_get_arg( 2 );
42 return join( '', array_slice( $ar[0], $start, $end ) );
43 } else {
44 return join( '', array_slice( $ar[0], $start ) );
49 if ( !function_exists( 'mb_strlen' ) ) {
50 /**
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
52 * @param string $str
53 * @param string $enc optional encoding; ignored
54 * @return int
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
58 $total = 0;
60 // Count ASCII bytes
61 for( $i = 0; $i < 0x80; $i++ ) {
62 $total += $counts[$i];
65 // Count multibyte sequence heads
66 for( $i = 0xc0; $i < 0xff; $i++ ) {
67 $total += $counts[$i];
69 return $total;
73 if ( !function_exists( 'array_diff_key' ) ) {
74 /**
75 * Exists in PHP 5.1.0+
76 * Not quite compatible, two-argument version only
77 * Null values will cause problems due to this use of isset()
79 function array_diff_key( $left, $right ) {
80 $result = $left;
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
86 return $result;
90 /**
91 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
93 function wfArrayDiff2( $a, $b ) {
94 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
96 function wfArrayDiff2_cmp( $a, $b ) {
97 if ( !is_array( $a ) ) {
98 return strcmp( $a, $b );
99 } elseif ( count( $a ) !== count( $b ) ) {
100 return count( $a ) < count( $b ) ? -1 : 1;
101 } else {
102 reset( $a );
103 reset( $b );
104 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
105 $cmp = strcmp( $valueA, $valueB );
106 if ( $cmp !== 0 ) {
107 return $cmp;
110 return 0;
115 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
116 * PHP 5 won't let you declare a 'clone' function, even conditionally,
117 * so it has to be a wrapper with a different name.
119 function wfClone( $object ) {
120 return clone( $object );
124 * Seed Mersenne Twister
125 * No-op for compatibility; only necessary in PHP < 4.2.0
127 function wfSeedRandom() {
128 /* No-op */
132 * Get a random decimal value between 0 and 1, in a way
133 * not likely to give duplicate values for any realistic
134 * number of articles.
136 * @return string
138 function wfRandom() {
139 # The maximum random value is "only" 2^31-1, so get two random
140 # values to reduce the chance of dupes
141 $max = mt_getrandmax() + 1;
142 $rand = number_format( (mt_rand() * $max + mt_rand())
143 / $max / $max, 12, '.', '' );
144 return $rand;
148 * We want / and : to be included as literal characters in our title URLs.
149 * %2F in the page titles seems to fatally break for some reason.
151 * @param $s String:
152 * @return string
154 function wfUrlencode ( $s ) {
155 $s = urlencode( $s );
156 $s = preg_replace( '/%3[Aa]/', ':', $s );
157 $s = preg_replace( '/%2[Ff]/', '/', $s );
159 return $s;
163 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
164 * In normal operation this is a NOP.
166 * Controlling globals:
167 * $wgDebugLogFile - points to the log file
168 * $wgProfileOnly - if set, normal debug messages will not be recorded.
169 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
170 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
172 * @param $text String
173 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
175 function wfDebug( $text, $logonly = false ) {
176 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
177 static $recursion = 0;
179 static $cache = array(); // Cache of unoutputted messages
181 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
182 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
183 return;
186 if ( $wgDebugComments && !$logonly ) {
187 $cache[] = $text;
189 if ( !isset( $wgOut ) ) {
190 return;
192 if ( !StubObject::isRealObject( $wgOut ) ) {
193 if ( $recursion ) {
194 return;
196 $recursion++;
197 $wgOut->_unstub();
198 $recursion--;
201 // add the message and possible cached ones to the output
202 array_map( array( $wgOut, 'debug' ), $cache );
203 $cache = array();
205 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
206 # Strip unprintables; they can switch terminal modes when binary data
207 # gets dumped, which is pretty annoying.
208 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
209 wfErrorLog( $text, $wgDebugLogFile );
214 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
215 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
217 * @param $logGroup String
218 * @param $text String
219 * @param $public Bool: whether to log the event in the public log if no private
220 * log file is specified, (default true)
222 function wfDebugLog( $logGroup, $text, $public = true ) {
223 global $wgDebugLogGroups;
224 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
225 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
226 $time = wfTimestamp( TS_DB );
227 $wiki = wfWikiID();
228 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
229 } else if ( $public === true ) {
230 wfDebug( $text, true );
235 * Log for database errors
236 * @param $text String: database error message.
238 function wfLogDBError( $text ) {
239 global $wgDBerrorLog, $wgDBname;
240 if ( $wgDBerrorLog ) {
241 $host = trim(`hostname`);
242 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
243 wfErrorLog( $text, $wgDBerrorLog );
248 * Log to a file without getting "file size exceeded" signals
250 function wfErrorLog( $text, $file ) {
251 wfSuppressWarnings();
252 $exists = file_exists( $file );
253 $size = $exists ? filesize( $file ) : false;
254 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
255 error_log( $text, 3, $file );
257 wfRestoreWarnings();
261 * @todo document
263 function wfLogProfilingData() {
264 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
265 global $wgProfiler, $wgUser;
266 if ( !isset( $wgProfiler ) )
267 return;
269 $now = wfTime();
270 $elapsed = $now - $wgRequestTime;
271 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
272 $forward = '';
273 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
274 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
275 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
276 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
277 if( !empty( $_SERVER['HTTP_FROM'] ) )
278 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
279 if( $forward )
280 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
281 // Don't unstub $wgUser at this late stage just for statistics purposes
282 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
283 $forward .= ' anon';
284 $log = sprintf( "%s\t%04.3f\t%s\n",
285 gmdate( 'YmdHis' ), $elapsed,
286 urldecode( $wgRequest->getRequestURL() . $forward ) );
287 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
288 wfErrorLog( $log . $prof, $wgDebugLogFile );
293 * Check if the wiki read-only lock file is present. This can be used to lock
294 * off editing functions, but doesn't guarantee that the database will not be
295 * modified.
296 * @return bool
298 function wfReadOnly() {
299 global $wgReadOnlyFile, $wgReadOnly;
301 if ( !is_null( $wgReadOnly ) ) {
302 return (bool)$wgReadOnly;
304 if ( '' == $wgReadOnlyFile ) {
305 return false;
307 // Set $wgReadOnly for faster access next time
308 if ( is_file( $wgReadOnlyFile ) ) {
309 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
310 } else {
311 $wgReadOnly = false;
313 return (bool)$wgReadOnly;
316 function wfReadOnlyReason() {
317 global $wgReadOnly;
318 wfReadOnly();
319 return $wgReadOnly;
323 * Get a message from anywhere, for the current user language.
325 * Use wfMsgForContent() instead if the message should NOT
326 * change depending on the user preferences.
328 * @param $key String: lookup key for the message, usually
329 * defined in languages/Language.php
331 * This function also takes extra optional parameters (not
332 * shown in the function definition), which can by used to
333 * insert variable text into the predefined message.
335 function wfMsg( $key ) {
336 $args = func_get_args();
337 array_shift( $args );
338 return wfMsgReal( $key, $args, true );
342 * Same as above except doesn't transform the message
344 function wfMsgNoTrans( $key ) {
345 $args = func_get_args();
346 array_shift( $args );
347 return wfMsgReal( $key, $args, true, false, false );
351 * Get a message from anywhere, for the current global language
352 * set with $wgLanguageCode.
354 * Use this if the message should NOT change dependent on the
355 * language set in the user's preferences. This is the case for
356 * most text written into logs, as well as link targets (such as
357 * the name of the copyright policy page). Link titles, on the
358 * other hand, should be shown in the UI language.
360 * Note that MediaWiki allows users to change the user interface
361 * language in their preferences, but a single installation
362 * typically only contains content in one language.
364 * Be wary of this distinction: If you use wfMsg() where you should
365 * use wfMsgForContent(), a user of the software may have to
366 * customize over 70 messages in order to, e.g., fix a link in every
367 * possible language.
369 * @param $key String: lookup key for the message, usually
370 * defined in languages/Language.php
372 function wfMsgForContent( $key ) {
373 global $wgForceUIMsgAsContentMsg;
374 $args = func_get_args();
375 array_shift( $args );
376 $forcontent = true;
377 if( is_array( $wgForceUIMsgAsContentMsg ) &&
378 in_array( $key, $wgForceUIMsgAsContentMsg ) )
379 $forcontent = false;
380 return wfMsgReal( $key, $args, true, $forcontent );
384 * Same as above except doesn't transform the message
386 function wfMsgForContentNoTrans( $key ) {
387 global $wgForceUIMsgAsContentMsg;
388 $args = func_get_args();
389 array_shift( $args );
390 $forcontent = true;
391 if( is_array( $wgForceUIMsgAsContentMsg ) &&
392 in_array( $key, $wgForceUIMsgAsContentMsg ) )
393 $forcontent = false;
394 return wfMsgReal( $key, $args, true, $forcontent, false );
398 * Get a message from the language file, for the UI elements
400 function wfMsgNoDB( $key ) {
401 $args = func_get_args();
402 array_shift( $args );
403 return wfMsgReal( $key, $args, false );
407 * Get a message from the language file, for the content
409 function wfMsgNoDBForContent( $key ) {
410 global $wgForceUIMsgAsContentMsg;
411 $args = func_get_args();
412 array_shift( $args );
413 $forcontent = true;
414 if( is_array( $wgForceUIMsgAsContentMsg ) &&
415 in_array( $key, $wgForceUIMsgAsContentMsg ) )
416 $forcontent = false;
417 return wfMsgReal( $key, $args, false, $forcontent );
422 * Really get a message
423 * @param $key String: key to get.
424 * @param $args
425 * @param $useDB Boolean
426 * @param $transform Boolean: Whether or not to transform the message.
427 * @param $forContent Boolean
428 * @return String: the requested message.
430 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
431 wfProfileIn( __METHOD__ );
432 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
433 $message = wfMsgReplaceArgs( $message, $args );
434 wfProfileOut( __METHOD__ );
435 return $message;
439 * This function provides the message source for messages to be edited which are *not* stored in the database.
440 * @param $key String:
442 function wfMsgWeirdKey ( $key ) {
443 $source = wfMsgGetKey( $key, false, true, false );
444 if ( wfEmptyMsg( $key, $source ) )
445 return "";
446 else
447 return $source;
451 * Fetch a message string value, but don't replace any keys yet.
452 * @param string $key
453 * @param bool $useDB
454 * @param string $langcode Code of the language to get the message for, or
455 * behaves as a content language switch if it is a
456 * boolean.
457 * @return string
458 * @private
460 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
461 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
463 # If $wgMessageCache isn't initialised yet, try to return something sensible.
464 if( is_object( $wgMessageCache ) ) {
465 $message = $wgMessageCache->get( $key, $useDB, $langCode );
466 if ( $transform ) {
467 $message = $wgMessageCache->transform( $message );
469 } else {
470 if( $langCode === true ) {
471 $lang = &$wgContLang;
472 } elseif( $langCode === false ) {
473 $lang = &$wgLang;
474 } else {
475 $validCodes = array_keys( Language::getLanguageNames() );
476 if( in_array( $langCode, $validCodes ) ) {
477 # $langcode corresponds to a valid language.
478 $lang = Language::factory( $langCode );
479 } else {
480 # $langcode is a string, but not a valid language code; use content language.
481 $lang =& $wgContLang;
482 wfDebug( 'Invalid language code passed to wfMsgGetKey, falling back to content language.' );
486 # MessageCache::get() does this already, Language::getMessage() doesn't
487 # ISSUE: Should we try to handle "message/lang" here too?
488 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
490 if( is_object( $lang ) ) {
491 $message = $lang->getMessage( $key );
492 } else {
493 $message = false;
497 return $message;
501 * Replace message parameter keys on the given formatted output.
503 * @param string $message
504 * @param array $args
505 * @return string
506 * @private
508 function wfMsgReplaceArgs( $message, $args ) {
509 # Fix windows line-endings
510 # Some messages are split with explode("\n", $msg)
511 $message = str_replace( "\r", '', $message );
513 // Replace arguments
514 if ( count( $args ) ) {
515 if ( is_array( $args[0] ) ) {
516 $args = array_values( $args[0] );
518 $replacementKeys = array();
519 foreach( $args as $n => $param ) {
520 $replacementKeys['$' . ($n + 1)] = $param;
522 $message = strtr( $message, $replacementKeys );
525 return $message;
529 * Return an HTML-escaped version of a message.
530 * Parameter replacements, if any, are done *after* the HTML-escaping,
531 * so parameters may contain HTML (eg links or form controls). Be sure
532 * to pre-escape them if you really do want plaintext, or just wrap
533 * the whole thing in htmlspecialchars().
535 * @param string $key
536 * @param string ... parameters
537 * @return string
539 function wfMsgHtml( $key ) {
540 $args = func_get_args();
541 array_shift( $args );
542 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
546 * Return an HTML version of message
547 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
548 * so parameters may contain HTML (eg links or form controls). Be sure
549 * to pre-escape them if you really do want plaintext, or just wrap
550 * the whole thing in htmlspecialchars().
552 * @param string $key
553 * @param string ... parameters
554 * @return string
556 function wfMsgWikiHtml( $key ) {
557 global $wgOut;
558 $args = func_get_args();
559 array_shift( $args );
560 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
564 * Returns message in the requested format
565 * @param string $key Key of the message
566 * @param array $options Processing rules:
567 * <i>parse</i>: parses wikitext to html
568 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
569 * <i>escape</i>: filters message through htmlspecialchars
570 * <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
571 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
572 * <i>parsemag</i>: transform the message using magic phrases
573 * <i>content</i>: fetch message for content language instead of interface
574 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
575 * with parser, parseinline and parsemag is undefined.
576 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
578 function wfMsgExt( $key, $options ) {
579 global $wgOut, $wgParser;
581 $args = func_get_args();
582 array_shift( $args );
583 array_shift( $args );
585 if( !is_array($options) ) {
586 $options = array($options);
589 if( in_array('content', $options) ) {
590 $forContent = true;
591 $langCode = true;
592 } elseif( array_key_exists('language', $options) ) {
593 $forContent = false;
594 $langCode = $options['language'];
595 $validCodes = array_keys( Language::getLanguageNames() );
596 if( !in_array($options['language'], $validCodes) ) {
597 # Fallback to en, instead of whatever interface language we might have
598 $langCode = 'en';
600 } else {
601 $forContent = false;
602 $langCode = false;
605 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
607 if( !in_array('replaceafter', $options) ) {
608 $string = wfMsgReplaceArgs( $string, $args );
611 if( in_array('parse', $options) ) {
612 $string = $wgOut->parse( $string, true, !$forContent );
613 } elseif ( in_array('parseinline', $options) ) {
614 $string = $wgOut->parse( $string, true, !$forContent );
615 $m = array();
616 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
617 $string = $m[1];
619 } elseif ( in_array('parsemag', $options) ) {
620 global $wgMessageCache;
621 if ( isset( $wgMessageCache ) ) {
622 $string = $wgMessageCache->transform( $string, !$forContent );
626 if ( in_array('escape', $options) ) {
627 $string = htmlspecialchars ( $string );
628 } elseif ( in_array( 'escapenoentities', $options ) ) {
629 $string = htmlspecialchars( $string );
630 $string = str_replace( '&amp;', '&', $string );
631 $string = Sanitizer::normalizeCharReferences( $string );
634 if( in_array('replaceafter', $options) ) {
635 $string = wfMsgReplaceArgs( $string, $args );
638 return $string;
643 * Just like exit() but makes a note of it.
644 * Commits open transactions except if the error parameter is set
646 * @deprecated Please return control to the caller or throw an exception
648 function wfAbruptExit( $error = false ){
649 static $called = false;
650 if ( $called ){
651 exit( -1 );
653 $called = true;
655 $bt = wfDebugBacktrace();
656 if( $bt ) {
657 for($i = 0; $i < count($bt) ; $i++){
658 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
659 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
660 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
662 } else {
663 wfDebug('WARNING: Abrupt exit\n');
666 wfLogProfilingData();
668 if ( !$error ) {
669 wfGetLB()->closeAll();
671 exit( -1 );
675 * @deprecated Please return control the caller or throw an exception
677 function wfErrorExit() {
678 wfAbruptExit( true );
682 * Print a simple message and die, returning nonzero to the shell if any.
683 * Plain die() fails to return nonzero to the shell if you pass a string.
684 * @param string $msg
686 function wfDie( $msg='' ) {
687 echo $msg;
688 die( 1 );
692 * Throw a debugging exception. This function previously once exited the process,
693 * but now throws an exception instead, with similar results.
695 * @param string $msg Message shown when dieing.
697 function wfDebugDieBacktrace( $msg = '' ) {
698 throw new MWException( $msg );
702 * Fetch server name for use in error reporting etc.
703 * Use real server name if available, so we know which machine
704 * in a server farm generated the current page.
705 * @return string
707 function wfHostname() {
708 if ( function_exists( 'posix_uname' ) ) {
709 // This function not present on Windows
710 $uname = @posix_uname();
711 } else {
712 $uname = false;
714 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
715 return $uname['nodename'];
716 } else {
717 # This may be a virtual server.
718 return $_SERVER['SERVER_NAME'];
723 * Returns a HTML comment with the elapsed time since request.
724 * This method has no side effects.
725 * @return string
727 function wfReportTime() {
728 global $wgRequestTime, $wgShowHostnames;
730 $now = wfTime();
731 $elapsed = $now - $wgRequestTime;
733 return $wgShowHostnames
734 ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
735 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
739 * Safety wrapper for debug_backtrace().
741 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
742 * murky circumstances, which may be triggered in part by stub objects
743 * or other fancy talkin'.
745 * Will return an empty array if Zend Optimizer is detected, otherwise
746 * the output from debug_backtrace() (trimmed).
748 * @return array of backtrace information
750 function wfDebugBacktrace() {
751 if( extension_loaded( 'Zend Optimizer' ) ) {
752 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
753 return array();
754 } else {
755 return array_slice( debug_backtrace(), 1 );
759 function wfBacktrace() {
760 global $wgCommandLineMode;
762 if ( $wgCommandLineMode ) {
763 $msg = '';
764 } else {
765 $msg = "<ul>\n";
767 $backtrace = wfDebugBacktrace();
768 foreach( $backtrace as $call ) {
769 if( isset( $call['file'] ) ) {
770 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
771 $file = $f[count($f)-1];
772 } else {
773 $file = '-';
775 if( isset( $call['line'] ) ) {
776 $line = $call['line'];
777 } else {
778 $line = '-';
780 if ( $wgCommandLineMode ) {
781 $msg .= "$file line $line calls ";
782 } else {
783 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
785 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
786 $msg .= $call['function'] . '()';
788 if ( $wgCommandLineMode ) {
789 $msg .= "\n";
790 } else {
791 $msg .= "</li>\n";
794 if ( $wgCommandLineMode ) {
795 $msg .= "\n";
796 } else {
797 $msg .= "</ul>\n";
800 return $msg;
804 /* Some generic result counters, pulled out of SearchEngine */
808 * @todo document
810 function wfShowingResults( $offset, $limit ) {
811 global $wgLang;
812 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
816 * @todo document
818 function wfShowingResultsNum( $offset, $limit, $num ) {
819 global $wgLang;
820 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
824 * @todo document
826 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
827 global $wgLang;
828 $fmtLimit = $wgLang->formatNum( $limit );
829 $prev = wfMsg( 'prevn', $fmtLimit );
830 $next = wfMsg( 'nextn', $fmtLimit );
832 if( is_object( $link ) ) {
833 $title =& $link;
834 } else {
835 $title = Title::newFromText( $link );
836 if( is_null( $title ) ) {
837 return false;
841 if ( 0 != $offset ) {
842 $po = $offset - $limit;
843 if ( $po < 0 ) { $po = 0; }
844 $q = "limit={$limit}&offset={$po}";
845 if ( '' != $query ) { $q .= '&'.$query; }
846 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
847 } else { $plink = $prev; }
849 $no = $offset + $limit;
850 $q = 'limit='.$limit.'&offset='.$no;
851 if ( '' != $query ) { $q .= '&'.$query; }
853 if ( $atend ) {
854 $nlink = $next;
855 } else {
856 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
858 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
859 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
860 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
861 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
862 wfNumLink( $offset, 500, $title, $query );
864 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
868 * @todo document
870 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
871 global $wgLang;
872 if ( '' == $query ) { $q = ''; }
873 else { $q = $query.'&'; }
874 $q .= 'limit='.$limit.'&offset='.$offset;
876 $fmtLimit = $wgLang->formatNum( $limit );
877 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
878 return $s;
882 * @todo document
883 * @todo FIXME: we may want to blacklist some broken browsers
885 * @return bool Whereas client accept gzip compression
887 function wfClientAcceptsGzip() {
888 global $wgUseGzip;
889 if( $wgUseGzip ) {
890 # FIXME: we may want to blacklist some broken browsers
891 $m = array();
892 if( preg_match(
893 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
894 $_SERVER['HTTP_ACCEPT_ENCODING'],
895 $m ) ) {
896 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
897 wfDebug( " accepts gzip\n" );
898 return true;
901 return false;
905 * Obtain the offset and limit values from the request string;
906 * used in special pages
908 * @param $deflimit Default limit if none supplied
909 * @param $optionname Name of a user preference to check against
910 * @return array
913 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
914 global $wgRequest;
915 return $wgRequest->getLimitOffset( $deflimit, $optionname );
919 * Escapes the given text so that it may be output using addWikiText()
920 * without any linking, formatting, etc. making its way through. This
921 * is achieved by substituting certain characters with HTML entities.
922 * As required by the callers, <nowiki> is not used. It currently does
923 * not filter out characters which have special meaning only at the
924 * start of a line, such as "*".
926 * @param string $text Text to be escaped
928 function wfEscapeWikiText( $text ) {
929 $text = str_replace(
930 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
931 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
932 htmlspecialchars($text) );
933 return $text;
937 * @todo document
939 function wfQuotedPrintable( $string, $charset = '' ) {
940 # Probably incomplete; see RFC 2045
941 if( empty( $charset ) ) {
942 global $wgInputEncoding;
943 $charset = $wgInputEncoding;
945 $charset = strtoupper( $charset );
946 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
948 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
949 $replace = $illegal . '\t ?_';
950 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
951 $out = "=?$charset?Q?";
952 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
953 $out .= '?=';
954 return $out;
959 * @todo document
960 * @return float
962 function wfTime() {
963 return microtime(true);
967 * Sets dest to source and returns the original value of dest
968 * If source is NULL, it just returns the value, it doesn't set the variable
970 function wfSetVar( &$dest, $source ) {
971 $temp = $dest;
972 if ( !is_null( $source ) ) {
973 $dest = $source;
975 return $temp;
979 * As for wfSetVar except setting a bit
981 function wfSetBit( &$dest, $bit, $state = true ) {
982 $temp = (bool)($dest & $bit );
983 if ( !is_null( $state ) ) {
984 if ( $state ) {
985 $dest |= $bit;
986 } else {
987 $dest &= ~$bit;
990 return $temp;
994 * This function takes two arrays as input, and returns a CGI-style string, e.g.
995 * "days=7&limit=100". Options in the first array override options in the second.
996 * Options set to "" will not be output.
998 function wfArrayToCGI( $array1, $array2 = NULL )
1000 if ( !is_null( $array2 ) ) {
1001 $array1 = $array1 + $array2;
1004 $cgi = '';
1005 foreach ( $array1 as $key => $value ) {
1006 if ( '' !== $value ) {
1007 if ( '' != $cgi ) {
1008 $cgi .= '&';
1010 if(is_array($value))
1012 $firstTime = true;
1013 foreach($value as $v)
1015 $cgi .= ($firstTime ? '' : '&') .
1016 urlencode( $key . '[]' ) . '=' .
1017 urlencode( $v );
1018 $firstTime = false;
1021 else
1022 $cgi .= urlencode( $key ) . '=' .
1023 urlencode( $value );
1026 return $cgi;
1030 * Append a query string to an existing URL, which may or may not already
1031 * have query string parameters already. If so, they will be combined.
1033 * @param string $url
1034 * @param string $query
1035 * @return string
1037 function wfAppendQuery( $url, $query ) {
1038 if( $query != '' ) {
1039 if( false === strpos( $url, '?' ) ) {
1040 $url .= '?';
1041 } else {
1042 $url .= '&';
1044 $url .= $query;
1046 return $url;
1050 * Expand a potentially local URL to a fully-qualified URL.
1051 * Assumes $wgServer is correct. :)
1052 * @param string $url, either fully-qualified or a local path + query
1053 * @return string Fully-qualified URL
1055 function wfExpandUrl( $url ) {
1056 if( substr( $url, 0, 1 ) == '/' ) {
1057 global $wgServer;
1058 return $wgServer . $url;
1059 } else {
1060 return $url;
1065 * This is obsolete, use SquidUpdate::purge()
1066 * @deprecated
1068 function wfPurgeSquidServers ($urlArr) {
1069 SquidUpdate::purge( $urlArr );
1073 * Windows-compatible version of escapeshellarg()
1074 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1075 * function puts single quotes in regardless of OS
1077 function wfEscapeShellArg( ) {
1078 $args = func_get_args();
1079 $first = true;
1080 $retVal = '';
1081 foreach ( $args as $arg ) {
1082 if ( !$first ) {
1083 $retVal .= ' ';
1084 } else {
1085 $first = false;
1088 if ( wfIsWindows() ) {
1089 // Escaping for an MSVC-style command line parser
1090 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1091 // Double the backslashes before any double quotes. Escape the double quotes.
1092 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1093 $arg = '';
1094 $delim = false;
1095 foreach ( $tokens as $token ) {
1096 if ( $delim ) {
1097 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1098 } else {
1099 $arg .= $token;
1101 $delim = !$delim;
1103 // Double the backslashes before the end of the string, because
1104 // we will soon add a quote
1105 $m = array();
1106 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1107 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1110 // Add surrounding quotes
1111 $retVal .= '"' . $arg . '"';
1112 } else {
1113 $retVal .= escapeshellarg( $arg );
1116 return $retVal;
1120 * wfMerge attempts to merge differences between three texts.
1121 * Returns true for a clean merge and false for failure or a conflict.
1123 function wfMerge( $old, $mine, $yours, &$result ){
1124 global $wgDiff3;
1126 # This check may also protect against code injection in
1127 # case of broken installations.
1128 if(! file_exists( $wgDiff3 ) ){
1129 wfDebug( "diff3 not found\n" );
1130 return false;
1133 # Make temporary files
1134 $td = wfTempDir();
1135 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1136 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1137 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1139 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1140 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1141 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1143 # Check for a conflict
1144 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1145 wfEscapeShellArg( $mytextName ) . ' ' .
1146 wfEscapeShellArg( $oldtextName ) . ' ' .
1147 wfEscapeShellArg( $yourtextName );
1148 $handle = popen( $cmd, 'r' );
1150 if( fgets( $handle, 1024 ) ){
1151 $conflict = true;
1152 } else {
1153 $conflict = false;
1155 pclose( $handle );
1157 # Merge differences
1158 $cmd = $wgDiff3 . ' -a -e --merge ' .
1159 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1160 $handle = popen( $cmd, 'r' );
1161 $result = '';
1162 do {
1163 $data = fread( $handle, 8192 );
1164 if ( strlen( $data ) == 0 ) {
1165 break;
1167 $result .= $data;
1168 } while ( true );
1169 pclose( $handle );
1170 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1172 if ( $result === '' && $old !== '' && $conflict == false ) {
1173 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1174 $conflict = true;
1176 return ! $conflict;
1180 * @todo document
1182 function wfVarDump( $var ) {
1183 global $wgOut;
1184 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1185 if ( headers_sent() || !@is_object( $wgOut ) ) {
1186 print $s;
1187 } else {
1188 $wgOut->addHTML( $s );
1193 * Provide a simple HTTP error.
1195 function wfHttpError( $code, $label, $desc ) {
1196 global $wgOut;
1197 $wgOut->disable();
1198 header( "HTTP/1.0 $code $label" );
1199 header( "Status: $code $label" );
1200 $wgOut->sendCacheControl();
1202 header( 'Content-type: text/html; charset=utf-8' );
1203 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1204 "<html><head><title>" .
1205 htmlspecialchars( $label ) .
1206 "</title></head><body><h1>" .
1207 htmlspecialchars( $label ) .
1208 "</h1><p>" .
1209 nl2br( htmlspecialchars( $desc ) ) .
1210 "</p></body></html>\n";
1214 * Clear away any user-level output buffers, discarding contents.
1216 * Suitable for 'starting afresh', for instance when streaming
1217 * relatively large amounts of data without buffering, or wanting to
1218 * output image files without ob_gzhandler's compression.
1220 * The optional $resetGzipEncoding parameter controls suppression of
1221 * the Content-Encoding header sent by ob_gzhandler; by default it
1222 * is left. See comments for wfClearOutputBuffers() for why it would
1223 * be used.
1225 * Note that some PHP configuration options may add output buffer
1226 * layers which cannot be removed; these are left in place.
1228 * @param bool $resetGzipEncoding
1230 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1231 if( $resetGzipEncoding ) {
1232 // Suppress Content-Encoding and Content-Length
1233 // headers from 1.10+s wfOutputHandler
1234 global $wgDisableOutputCompression;
1235 $wgDisableOutputCompression = true;
1237 while( $status = ob_get_status() ) {
1238 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1239 // Probably from zlib.output_compression or other
1240 // PHP-internal setting which can't be removed.
1242 // Give up, and hope the result doesn't break
1243 // output behavior.
1244 break;
1246 if( !ob_end_clean() ) {
1247 // Could not remove output buffer handler; abort now
1248 // to avoid getting in some kind of infinite loop.
1249 break;
1251 if( $resetGzipEncoding ) {
1252 if( $status['name'] == 'ob_gzhandler' ) {
1253 // Reset the 'Content-Encoding' field set by this handler
1254 // so we can start fresh.
1255 header( 'Content-Encoding:' );
1262 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1264 * Clear away output buffers, but keep the Content-Encoding header
1265 * produced by ob_gzhandler, if any.
1267 * This should be used for HTTP 304 responses, where you need to
1268 * preserve the Content-Encoding header of the real result, but
1269 * also need to suppress the output of ob_gzhandler to keep to spec
1270 * and avoid breaking Firefox in rare cases where the headers and
1271 * body are broken over two packets.
1273 function wfClearOutputBuffers() {
1274 wfResetOutputBuffers( false );
1278 * Converts an Accept-* header into an array mapping string values to quality
1279 * factors
1281 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1282 # No arg means accept anything (per HTTP spec)
1283 if( !$accept ) {
1284 return array( $def => 1.0 );
1287 $prefs = array();
1289 $parts = explode( ',', $accept );
1291 foreach( $parts as $part ) {
1292 # FIXME: doesn't deal with params like 'text/html; level=1'
1293 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1294 $match = array();
1295 if( !isset( $qpart ) ) {
1296 $prefs[$value] = 1.0;
1297 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1298 $prefs[$value] = floatval($match[1]);
1302 return $prefs;
1306 * Checks if a given MIME type matches any of the keys in the given
1307 * array. Basic wildcards are accepted in the array keys.
1309 * Returns the matching MIME type (or wildcard) if a match, otherwise
1310 * NULL if no match.
1312 * @param string $type
1313 * @param array $avail
1314 * @return string
1315 * @private
1317 function mimeTypeMatch( $type, $avail ) {
1318 if( array_key_exists($type, $avail) ) {
1319 return $type;
1320 } else {
1321 $parts = explode( '/', $type );
1322 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1323 return $parts[0] . '/*';
1324 } elseif( array_key_exists( '*/*', $avail ) ) {
1325 return '*/*';
1326 } else {
1327 return NULL;
1333 * Returns the 'best' match between a client's requested internet media types
1334 * and the server's list of available types. Each list should be an associative
1335 * array of type to preference (preference is a float between 0.0 and 1.0).
1336 * Wildcards in the types are acceptable.
1338 * @param array $cprefs Client's acceptable type list
1339 * @param array $sprefs Server's offered types
1340 * @return string
1342 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1343 * XXX: generalize to negotiate other stuff
1345 function wfNegotiateType( $cprefs, $sprefs ) {
1346 $combine = array();
1348 foreach( array_keys($sprefs) as $type ) {
1349 $parts = explode( '/', $type );
1350 if( $parts[1] != '*' ) {
1351 $ckey = mimeTypeMatch( $type, $cprefs );
1352 if( $ckey ) {
1353 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1358 foreach( array_keys( $cprefs ) as $type ) {
1359 $parts = explode( '/', $type );
1360 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1361 $skey = mimeTypeMatch( $type, $sprefs );
1362 if( $skey ) {
1363 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1368 $bestq = 0;
1369 $besttype = NULL;
1371 foreach( array_keys( $combine ) as $type ) {
1372 if( $combine[$type] > $bestq ) {
1373 $besttype = $type;
1374 $bestq = $combine[$type];
1378 return $besttype;
1382 * Array lookup
1383 * Returns an array where the values in the first array are replaced by the
1384 * values in the second array with the corresponding keys
1386 * @return array
1388 function wfArrayLookup( $a, $b ) {
1389 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1393 * Convenience function; returns MediaWiki timestamp for the present time.
1394 * @return string
1396 function wfTimestampNow() {
1397 # return NOW
1398 return wfTimestamp( TS_MW, time() );
1402 * Reference-counted warning suppression
1404 function wfSuppressWarnings( $end = false ) {
1405 static $suppressCount = 0;
1406 static $originalLevel = false;
1408 if ( $end ) {
1409 if ( $suppressCount ) {
1410 --$suppressCount;
1411 if ( !$suppressCount ) {
1412 error_reporting( $originalLevel );
1415 } else {
1416 if ( !$suppressCount ) {
1417 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1419 ++$suppressCount;
1424 * Restore error level to previous value
1426 function wfRestoreWarnings() {
1427 wfSuppressWarnings( true );
1430 # Autodetect, convert and provide timestamps of various types
1433 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1435 define('TS_UNIX', 0);
1438 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1440 define('TS_MW', 1);
1443 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1445 define('TS_DB', 2);
1448 * RFC 2822 format, for E-mail and HTTP headers
1450 define('TS_RFC2822', 3);
1453 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1455 * This is used by Special:Export
1457 define('TS_ISO_8601', 4);
1460 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1462 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1463 * DateTime tag and page 36 for the DateTimeOriginal and
1464 * DateTimeDigitized tags.
1466 define('TS_EXIF', 5);
1469 * Oracle format time.
1471 define('TS_ORACLE', 6);
1474 * Postgres format time.
1476 define('TS_POSTGRES', 7);
1479 * @param mixed $outputtype A timestamp in one of the supported formats, the
1480 * function will autodetect which format is supplied
1481 * and act accordingly.
1482 * @return string Time in the format specified in $outputtype
1484 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1485 $uts = 0;
1486 $da = array();
1487 if ($ts==0) {
1488 $uts=time();
1489 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1490 # TS_DB
1491 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1492 # TS_EXIF
1493 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1494 # TS_MW
1495 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1496 # TS_UNIX
1497 $uts = $ts;
1498 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1499 # TS_ORACLE
1500 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1501 str_replace("+00:00", "UTC", $ts)));
1502 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1503 # TS_ISO_8601
1504 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1505 # TS_POSTGRES
1506 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1507 # TS_POSTGRES
1508 } else {
1509 # Bogus value; fall back to the epoch...
1510 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1511 $uts = 0;
1514 if (count( $da ) ) {
1515 // Warning! gmmktime() acts oddly if the month or day is set to 0
1516 // We may want to handle that explicitly at some point
1517 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1518 (int)$da[2],(int)$da[3],(int)$da[1]);
1521 switch($outputtype) {
1522 case TS_UNIX:
1523 return $uts;
1524 case TS_MW:
1525 return gmdate( 'YmdHis', $uts );
1526 case TS_DB:
1527 return gmdate( 'Y-m-d H:i:s', $uts );
1528 case TS_ISO_8601:
1529 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1530 // This shouldn't ever be used, but is included for completeness
1531 case TS_EXIF:
1532 return gmdate( 'Y:m:d H:i:s', $uts );
1533 case TS_RFC2822:
1534 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1535 case TS_ORACLE:
1536 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1537 case TS_POSTGRES:
1538 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1539 default:
1540 throw new MWException( 'wfTimestamp() called with illegal output type.');
1545 * Return a formatted timestamp, or null if input is null.
1546 * For dealing with nullable timestamp columns in the database.
1547 * @param int $outputtype
1548 * @param string $ts
1549 * @return string
1551 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1552 if( is_null( $ts ) ) {
1553 return null;
1554 } else {
1555 return wfTimestamp( $outputtype, $ts );
1560 * Check if the operating system is Windows
1562 * @return bool True if it's Windows, False otherwise.
1564 function wfIsWindows() {
1565 if (substr(php_uname(), 0, 7) == 'Windows') {
1566 return true;
1567 } else {
1568 return false;
1573 * Swap two variables
1575 function swap( &$x, &$y ) {
1576 $z = $x;
1577 $x = $y;
1578 $y = $z;
1581 function wfGetCachedNotice( $name ) {
1582 global $wgOut, $parserMemc;
1583 $fname = 'wfGetCachedNotice';
1584 wfProfileIn( $fname );
1586 $needParse = false;
1588 if( $name === 'default' ) {
1589 // special case
1590 global $wgSiteNotice;
1591 $notice = $wgSiteNotice;
1592 if( empty( $notice ) ) {
1593 wfProfileOut( $fname );
1594 return false;
1596 } else {
1597 $notice = wfMsgForContentNoTrans( $name );
1598 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1599 wfProfileOut( $fname );
1600 return( false );
1604 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1605 if( is_array( $cachedNotice ) ) {
1606 if( md5( $notice ) == $cachedNotice['hash'] ) {
1607 $notice = $cachedNotice['html'];
1608 } else {
1609 $needParse = true;
1611 } else {
1612 $needParse = true;
1615 if( $needParse ) {
1616 if( is_object( $wgOut ) ) {
1617 $parsed = $wgOut->parse( $notice );
1618 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1619 $notice = $parsed;
1620 } else {
1621 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1622 $notice = '';
1626 wfProfileOut( $fname );
1627 return $notice;
1630 function wfGetNamespaceNotice() {
1631 global $wgTitle;
1633 # Paranoia
1634 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1635 return "";
1637 $fname = 'wfGetNamespaceNotice';
1638 wfProfileIn( $fname );
1640 $key = "namespacenotice-" . $wgTitle->getNsText();
1641 $namespaceNotice = wfGetCachedNotice( $key );
1642 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1643 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1644 } else {
1645 $namespaceNotice = "";
1648 wfProfileOut( $fname );
1649 return $namespaceNotice;
1652 function wfGetSiteNotice() {
1653 global $wgUser, $wgSiteNotice;
1654 $fname = 'wfGetSiteNotice';
1655 wfProfileIn( $fname );
1656 $siteNotice = '';
1658 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1659 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1660 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1661 } else {
1662 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1663 if( !$anonNotice ) {
1664 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1665 } else {
1666 $siteNotice = $anonNotice;
1669 if( !$siteNotice ) {
1670 $siteNotice = wfGetCachedNotice( 'default' );
1674 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1675 wfProfileOut( $fname );
1676 return $siteNotice;
1680 * BC wrapper for MimeMagic::singleton()
1681 * @deprecated
1683 function &wfGetMimeMagic() {
1684 return MimeMagic::singleton();
1688 * Tries to get the system directory for temporary files.
1689 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1690 * and if none are set /tmp is returned as the generic Unix default.
1692 * NOTE: When possible, use the tempfile() function to create temporary
1693 * files to avoid race conditions on file creation, etc.
1695 * @return string
1697 function wfTempDir() {
1698 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1699 $tmp = getenv( $var );
1700 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1701 return $tmp;
1704 # Hope this is Unix of some kind!
1705 return '/tmp';
1709 * Make directory, and make all parent directories if they don't exist
1711 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1712 if( strval( $fullDir ) === '' )
1713 return true;
1714 if( file_exists( $fullDir ) )
1715 return true;
1717 # Go back through the paths to find the first directory that exists
1718 $currentDir = $fullDir;
1719 $createList = array();
1720 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1721 # Strip trailing slashes
1722 $currentDir = rtrim( $currentDir, '/\\' );
1724 # Add to create list
1725 $createList[] = $currentDir;
1727 # Find next delimiter searching from the end
1728 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1729 if ( $p === false ) {
1730 $currentDir = false;
1731 } else {
1732 $currentDir = substr( $currentDir, 0, $p );
1736 if ( count( $createList ) == 0 ) {
1737 # Directory specified already exists
1738 return true;
1739 } elseif ( $currentDir === false ) {
1740 # Went all the way back to root and it apparently doesn't exist
1741 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1742 return false;
1744 # Now go forward creating directories
1745 $createList = array_reverse( $createList );
1747 # Is the parent directory writable?
1748 if ( $currentDir === '' ) {
1749 $currentDir = '/';
1751 if ( !is_writable( $currentDir ) ) {
1752 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1753 return false;
1756 foreach ( $createList as $dir ) {
1757 # use chmod to override the umask, as suggested by the PHP manual
1758 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1759 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1760 return false;
1763 return true;
1767 * Increment a statistics counter
1769 function wfIncrStats( $key ) {
1770 global $wgStatsMethod;
1772 if( $wgStatsMethod == 'udp' ) {
1773 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1774 static $socket;
1775 if (!$socket) {
1776 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1777 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1778 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1780 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1781 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1782 } elseif( $wgStatsMethod == 'cache' ) {
1783 global $wgMemc;
1784 $key = wfMemcKey( 'stats', $key );
1785 if ( is_null( $wgMemc->incr( $key ) ) ) {
1786 $wgMemc->add( $key, 1 );
1788 } else {
1789 // Disabled
1794 * @param mixed $nr The number to format
1795 * @param int $acc The number of digits after the decimal point, default 2
1796 * @param bool $round Whether or not to round the value, default true
1797 * @return float
1799 function wfPercent( $nr, $acc = 2, $round = true ) {
1800 $ret = sprintf( "%.${acc}f", $nr );
1801 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1805 * Encrypt a username/password.
1807 * @param string $userid ID of the user
1808 * @param string $password Password of the user
1809 * @return string Hashed password
1810 * @deprecated Use User::crypt() or User::oldCrypt() instead
1812 function wfEncryptPassword( $userid, $password ) {
1813 wfDeprecated(__FUNCTION__);
1814 # Just wrap around User::oldCrypt()
1815 return User::oldCrypt($password, $userid);
1819 * Appends to second array if $value differs from that in $default
1821 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1822 if ( is_null( $changed ) ) {
1823 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1825 if ( $default[$key] !== $value ) {
1826 $changed[$key] = $value;
1831 * Since wfMsg() and co suck, they don't return false if the message key they
1832 * looked up didn't exist but a XHTML string, this function checks for the
1833 * nonexistance of messages by looking at wfMsg() output
1835 * @param $msg The message key looked up
1836 * @param $wfMsgOut The output of wfMsg*()
1837 * @return bool
1839 function wfEmptyMsg( $msg, $wfMsgOut ) {
1840 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1844 * Find out whether or not a mixed variable exists in a string
1846 * @param mixed needle
1847 * @param string haystack
1848 * @return bool
1850 function in_string( $needle, $str ) {
1851 return strpos( $str, $needle ) !== false;
1854 function wfSpecialList( $page, $details ) {
1855 global $wgContLang;
1856 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1857 return $page . $details;
1861 * Returns a regular expression of url protocols
1863 * @return string
1865 function wfUrlProtocols() {
1866 global $wgUrlProtocols;
1868 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1869 // with LocalSettings files from 1.5
1870 if ( is_array( $wgUrlProtocols ) ) {
1871 $protocols = array();
1872 foreach ($wgUrlProtocols as $protocol)
1873 $protocols[] = preg_quote( $protocol, '/' );
1875 return implode( '|', $protocols );
1876 } else {
1877 return $wgUrlProtocols;
1882 * Safety wrapper around ini_get() for boolean settings.
1883 * The values returned from ini_get() are pre-normalized for settings
1884 * set via php.ini or php_flag/php_admin_flag... but *not*
1885 * for those set via php_value/php_admin_value.
1887 * It's fairly common for people to use php_value instead of php_flag,
1888 * which can leave you with an 'off' setting giving a false positive
1889 * for code that just takes the ini_get() return value as a boolean.
1891 * To make things extra interesting, setting via php_value accepts
1892 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1893 * Unrecognized values go false... again opposite PHP's own coercion
1894 * from string to bool.
1896 * Luckily, 'properly' set settings will always come back as '0' or '1',
1897 * so we only have to worry about them and the 'improper' settings.
1899 * I frickin' hate PHP... :P
1901 * @param string $setting
1902 * @return bool
1904 function wfIniGetBool( $setting ) {
1905 $val = ini_get( $setting );
1906 // 'on' and 'true' can't have whitespace around them, but '1' can.
1907 return strtolower( $val ) == 'on'
1908 || strtolower( $val ) == 'true'
1909 || strtolower( $val ) == 'yes'
1910 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1914 * Execute a shell command, with time and memory limits mirrored from the PHP
1915 * configuration if supported.
1916 * @param $cmd Command line, properly escaped for shell.
1917 * @param &$retval optional, will receive the program's exit code.
1918 * (non-zero is usually failure)
1919 * @return collected stdout as a string (trailing newlines stripped)
1921 function wfShellExec( $cmd, &$retval=null ) {
1922 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1924 if( wfIniGetBool( 'safe_mode' ) ) {
1925 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1926 $retval = 1;
1927 return "Unable to run external programs in safe mode.";
1930 if ( php_uname( 's' ) == 'Linux' ) {
1931 $time = intval( ini_get( 'max_execution_time' ) );
1932 $mem = intval( $wgMaxShellMemory );
1933 $filesize = intval( $wgMaxShellFileSize );
1935 if ( $time > 0 && $mem > 0 ) {
1936 $script = "$IP/bin/ulimit4.sh";
1937 if ( is_executable( $script ) ) {
1938 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1941 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1942 # This is a hack to work around PHP's flawed invocation of cmd.exe
1943 # http://news.php.net/php.internals/21796
1944 $cmd = '"' . $cmd . '"';
1946 wfDebug( "wfShellExec: $cmd\n" );
1948 $retval = 1; // error by default?
1949 ob_start();
1950 passthru( $cmd, $retval );
1951 $output = ob_get_contents();
1952 ob_end_clean();
1953 return $output;
1958 * This function works like "use VERSION" in Perl, the program will die with a
1959 * backtrace if the current version of PHP is less than the version provided
1961 * This is useful for extensions which due to their nature are not kept in sync
1962 * with releases, and might depend on other versions of PHP than the main code
1964 * Note: PHP might die due to parsing errors in some cases before it ever
1965 * manages to call this function, such is life
1967 * @see perldoc -f use
1969 * @param mixed $version The version to check, can be a string, an integer, or
1970 * a float
1972 function wfUsePHP( $req_ver ) {
1973 $php_ver = PHP_VERSION;
1975 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1976 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1980 * This function works like "use VERSION" in Perl except it checks the version
1981 * of MediaWiki, the program will die with a backtrace if the current version
1982 * of MediaWiki is less than the version provided.
1984 * This is useful for extensions which due to their nature are not kept in sync
1985 * with releases
1987 * @see perldoc -f use
1989 * @param mixed $version The version to check, can be a string, an integer, or
1990 * a float
1992 function wfUseMW( $req_ver ) {
1993 global $wgVersion;
1995 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1996 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2000 * @deprecated use StringUtils::escapeRegexReplacement
2002 function wfRegexReplacement( $string ) {
2003 return StringUtils::escapeRegexReplacement( $string );
2007 * Return the final portion of a pathname.
2008 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2009 * http://bugs.php.net/bug.php?id=33898
2011 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2012 * We'll consider it so always, as we don't want \s in our Unix paths either.
2014 * @param string $path
2015 * @param string $suffix to remove if present
2016 * @return string
2018 function wfBaseName( $path, $suffix='' ) {
2019 $encSuffix = ($suffix == '')
2020 ? ''
2021 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2022 $matches = array();
2023 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2024 return $matches[1];
2025 } else {
2026 return '';
2031 * Generate a relative path name to the given file.
2032 * May explode on non-matching case-insensitive paths,
2033 * funky symlinks, etc.
2035 * @param string $path Absolute destination path including target filename
2036 * @param string $from Absolute source path, directory only
2037 * @return string
2039 function wfRelativePath( $path, $from ) {
2040 // Normalize mixed input on Windows...
2041 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2042 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2044 // Trim trailing slashes -- fix for drive root
2045 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2046 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2048 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2049 $against = explode( DIRECTORY_SEPARATOR, $from );
2051 if( $pieces[0] !== $against[0] ) {
2052 // Non-matching Windows drive letters?
2053 // Return a full path.
2054 return $path;
2057 // Trim off common prefix
2058 while( count( $pieces ) && count( $against )
2059 && $pieces[0] == $against[0] ) {
2060 array_shift( $pieces );
2061 array_shift( $against );
2064 // relative dots to bump us to the parent
2065 while( count( $against ) ) {
2066 array_unshift( $pieces, '..' );
2067 array_shift( $against );
2070 array_push( $pieces, wfBaseName( $path ) );
2072 return implode( DIRECTORY_SEPARATOR, $pieces );
2076 * array_merge() does awful things with "numeric" indexes, including
2077 * string indexes when happen to look like integers. When we want
2078 * to merge arrays with arbitrary string indexes, we don't want our
2079 * arrays to be randomly corrupted just because some of them consist
2080 * of numbers.
2082 * Fuck you, PHP. Fuck you in the ear!
2084 * @param array $array1, [$array2, [...]]
2085 * @return array
2087 function wfArrayMerge( $array1/* ... */ ) {
2088 $out = $array1;
2089 for( $i = 1; $i < func_num_args(); $i++ ) {
2090 foreach( func_get_arg( $i ) as $key => $value ) {
2091 $out[$key] = $value;
2094 return $out;
2098 * Make a URL index, appropriate for the el_index field of externallinks.
2100 function wfMakeUrlIndex( $url ) {
2101 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2102 wfSuppressWarnings();
2103 $bits = parse_url( $url );
2104 wfRestoreWarnings();
2105 if ( !$bits ) {
2106 return false;
2108 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2109 $delimiter = '';
2110 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2111 $delimiter = '://';
2112 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2113 $delimiter = ':';
2114 // parse_url detects for news: and mailto: the host part of an url as path
2115 // We have to correct this wrong detection
2116 if ( isset ( $bits['path'] ) ) {
2117 $bits['host'] = $bits['path'];
2118 $bits['path'] = '';
2120 } else {
2121 return false;
2124 // Reverse the labels in the hostname, convert to lower case
2125 // For emails reverse domainpart only
2126 if ( $bits['scheme'] == 'mailto' ) {
2127 $mailparts = explode( '@', $bits['host'], 2 );
2128 if ( count($mailparts) === 2 ) {
2129 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2130 } else {
2131 // No domain specified, don't mangle it
2132 $domainpart = '';
2134 $reversedHost = $domainpart . '@' . $mailparts[0];
2135 } else {
2136 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2138 // Add an extra dot to the end
2139 // Why? Is it in wrong place in mailto links?
2140 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2141 $reversedHost .= '.';
2143 // Reconstruct the pseudo-URL
2144 $prot = $bits['scheme'];
2145 $index = "$prot$delimiter$reversedHost";
2146 // Leave out user and password. Add the port, path, query and fragment
2147 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2148 if ( isset( $bits['path'] ) ) {
2149 $index .= $bits['path'];
2150 } else {
2151 $index .= '/';
2153 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2154 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2155 return $index;
2159 * Do any deferred updates and clear the list
2160 * TODO: This could be in Wiki.php if that class made any sense at all
2162 function wfDoUpdates()
2164 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2165 foreach ( $wgDeferredUpdateList as $update ) {
2166 $update->doUpdate();
2168 foreach ( $wgPostCommitUpdateList as $update ) {
2169 $update->doUpdate();
2171 $wgDeferredUpdateList = array();
2172 $wgPostCommitUpdateList = array();
2176 * @deprecated use StringUtils::explodeMarkup
2178 function wfExplodeMarkup( $separator, $text ) {
2179 return StringUtils::explodeMarkup( $separator, $text );
2183 * Convert an arbitrarily-long digit string from one numeric base
2184 * to another, optionally zero-padding to a minimum column width.
2186 * Supports base 2 through 36; digit values 10-36 are represented
2187 * as lowercase letters a-z. Input is case-insensitive.
2189 * @param $input string of digits
2190 * @param $sourceBase int 2-36
2191 * @param $destBase int 2-36
2192 * @param $pad int 1 or greater
2193 * @param $lowercase bool
2194 * @return string or false on invalid input
2196 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2197 $input = strval( $input );
2198 if( $sourceBase < 2 ||
2199 $sourceBase > 36 ||
2200 $destBase < 2 ||
2201 $destBase > 36 ||
2202 $pad < 1 ||
2203 $sourceBase != intval( $sourceBase ) ||
2204 $destBase != intval( $destBase ) ||
2205 $pad != intval( $pad ) ||
2206 !is_string( $input ) ||
2207 $input == '' ) {
2208 return false;
2210 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2211 $inDigits = array();
2212 $outChars = '';
2214 // Decode and validate input string
2215 $input = strtolower( $input );
2216 for( $i = 0; $i < strlen( $input ); $i++ ) {
2217 $n = strpos( $digitChars, $input{$i} );
2218 if( $n === false || $n > $sourceBase ) {
2219 return false;
2221 $inDigits[] = $n;
2224 // Iterate over the input, modulo-ing out an output digit
2225 // at a time until input is gone.
2226 while( count( $inDigits ) ) {
2227 $work = 0;
2228 $workDigits = array();
2230 // Long division...
2231 foreach( $inDigits as $digit ) {
2232 $work *= $sourceBase;
2233 $work += $digit;
2235 if( $work < $destBase ) {
2236 // Gonna need to pull another digit.
2237 if( count( $workDigits ) ) {
2238 // Avoid zero-padding; this lets us find
2239 // the end of the input very easily when
2240 // length drops to zero.
2241 $workDigits[] = 0;
2243 } else {
2244 // Finally! Actual division!
2245 $workDigits[] = intval( $work / $destBase );
2247 // Isn't it annoying that most programming languages
2248 // don't have a single divide-and-remainder operator,
2249 // even though the CPU implements it that way?
2250 $work = $work % $destBase;
2254 // All that division leaves us with a remainder,
2255 // which is conveniently our next output digit.
2256 $outChars .= $digitChars[$work];
2258 // And we continue!
2259 $inDigits = $workDigits;
2262 while( strlen( $outChars ) < $pad ) {
2263 $outChars .= '0';
2266 return strrev( $outChars );
2270 * Create an object with a given name and an array of construct parameters
2271 * @param string $name
2272 * @param array $p parameters
2274 function wfCreateObject( $name, $p ){
2275 $p = array_values( $p );
2276 switch ( count( $p ) ) {
2277 case 0:
2278 return new $name;
2279 case 1:
2280 return new $name( $p[0] );
2281 case 2:
2282 return new $name( $p[0], $p[1] );
2283 case 3:
2284 return new $name( $p[0], $p[1], $p[2] );
2285 case 4:
2286 return new $name( $p[0], $p[1], $p[2], $p[3] );
2287 case 5:
2288 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2289 case 6:
2290 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2291 default:
2292 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2297 * Aliases for modularized functions
2299 function wfGetHTTP( $url, $timeout = 'default' ) {
2300 return Http::get( $url, $timeout );
2302 function wfIsLocalURL( $url ) {
2303 return Http::isLocalURL( $url );
2306 function wfHttpOnlySafe() {
2307 global $wgHttpOnlyBlacklist;
2308 if( !version_compare("5.2", PHP_VERSION, "<") )
2309 return false;
2311 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2312 foreach( $wgHttpOnlyBlacklist as $regex ) {
2313 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2314 return false;
2319 return true;
2323 * Initialise php session
2325 function wfSetupSession() {
2326 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2327 if( $wgSessionsInMemcached ) {
2328 require_once( 'MemcachedSessions.php' );
2329 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2330 # If it's left on 'user' or another setting from another
2331 # application, it will end up failing. Try to recover.
2332 ini_set ( 'session.save_handler', 'files' );
2334 $httpOnlySafe = wfHttpOnlySafe();
2335 wfDebugLog( 'cookie',
2336 'session_set_cookie_params: "' . implode( '", "',
2337 array(
2339 $wgCookiePath,
2340 $wgCookieDomain,
2341 $wgCookieSecure,
2342 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2343 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2344 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2345 } else {
2346 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2347 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2349 session_cache_limiter( 'private, must-revalidate' );
2350 wfSuppressWarnings();
2351 session_start();
2352 wfRestoreWarnings();
2356 * Get an object from the precompiled serialized directory
2358 * @return mixed The variable on success, false on failure
2360 function wfGetPrecompiledData( $name ) {
2361 global $IP;
2363 $file = "$IP/serialized/$name";
2364 if ( file_exists( $file ) ) {
2365 $blob = file_get_contents( $file );
2366 if ( $blob ) {
2367 return unserialize( $blob );
2370 return false;
2373 function wfGetCaller( $level = 2 ) {
2374 $backtrace = wfDebugBacktrace();
2375 if ( isset( $backtrace[$level] ) ) {
2376 return wfFormatStackFrame($backtrace[$level]);
2377 } else {
2378 $caller = 'unknown';
2380 return $caller;
2383 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2384 function wfGetAllCallers() {
2385 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2388 /** Return a string representation of frame */
2389 function wfFormatStackFrame($frame) {
2390 return isset( $frame["class"] )?
2391 $frame["class"]."::".$frame["function"]:
2392 $frame["function"];
2396 * Get a cache key
2398 function wfMemcKey( /*... */ ) {
2399 $args = func_get_args();
2400 $key = wfWikiID() . ':' . implode( ':', $args );
2401 return $key;
2405 * Get a cache key for a foreign DB
2407 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2408 $args = array_slice( func_get_args(), 2 );
2409 if ( $prefix ) {
2410 $key = "$db-$prefix:" . implode( ':', $args );
2411 } else {
2412 $key = $db . ':' . implode( ':', $args );
2414 return $key;
2418 * Get an ASCII string identifying this wiki
2419 * This is used as a prefix in memcached keys
2421 function wfWikiID( $db = null ) {
2422 if( $db instanceof Database ) {
2423 return $db->getWikiID();
2424 } else {
2425 global $wgDBprefix, $wgDBname;
2426 if ( $wgDBprefix ) {
2427 return "$wgDBname-$wgDBprefix";
2428 } else {
2429 return $wgDBname;
2435 * Split a wiki ID into DB name and table prefix
2437 function wfSplitWikiID( $wiki ) {
2438 $bits = explode( '-', $wiki, 2 );
2439 if ( count( $bits ) < 2 ) {
2440 $bits[] = '';
2442 return $bits;
2446 * Get a Database object.
2447 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2448 * master (for write queries), DB_SLAVE for potentially lagged
2449 * read queries, or an integer >= 0 for a particular server.
2451 * @param mixed $groups Query groups. An array of group names that this query
2452 * belongs to. May contain a single string if the query is only
2453 * in one group.
2455 * @param string $wiki The wiki ID, or false for the current wiki
2457 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2458 * will always return the same object, unless the underlying connection or load
2459 * balancer is manually destroyed.
2461 function &wfGetDB( $db = DB_LAST, $groups = array(), $wiki = false ) {
2462 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2466 * Get a load balancer object.
2468 * @param array $groups List of query groups
2469 * @param string $wiki Wiki ID, or false for the current wiki
2470 * @return LoadBalancer
2472 function wfGetLB( $wiki = false ) {
2473 return wfGetLBFactory()->getMainLB( $wiki );
2477 * Get the load balancer factory object
2479 function &wfGetLBFactory() {
2480 return LBFactory::singleton();
2484 * Find a file.
2485 * Shortcut for RepoGroup::singleton()->findFile()
2486 * @param mixed $title Title object or string. May be interwiki.
2487 * @param mixed $time Requested time for an archived image, or false for the
2488 * current version. An image object will be returned which
2489 * was created at the specified time.
2490 * @param mixed $flags FileRepo::FIND_ flags
2491 * @return File, or false if the file does not exist
2493 function wfFindFile( $title, $time = false, $flags = 0 ) {
2494 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2498 * Get an object referring to a locally registered file.
2499 * Returns a valid placeholder object if the file does not exist.
2501 function wfLocalFile( $title ) {
2502 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2506 * Should low-performance queries be disabled?
2508 * @return bool
2510 function wfQueriesMustScale() {
2511 global $wgMiserMode;
2512 return $wgMiserMode
2513 || ( SiteStats::pages() > 100000
2514 && SiteStats::edits() > 1000000
2515 && SiteStats::users() > 10000 );
2519 * Get the path to a specified script file, respecting file
2520 * extensions; this is a wrapper around $wgScriptExtension etc.
2522 * @param string $script Script filename, sans extension
2523 * @return string
2525 function wfScript( $script = 'index' ) {
2526 global $wgScriptPath, $wgScriptExtension;
2527 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2531 * Convenience function converts boolean values into "true"
2532 * or "false" (string) values
2534 * @param bool $value
2535 * @return string
2537 function wfBoolToStr( $value ) {
2538 return $value ? 'true' : 'false';
2542 * Load an extension messages file
2544 * @param string $extensionName Name of extension to load messages from\for.
2545 * @param string $langcode Language to load messages for, or false for default
2546 * behvaiour (en, content language and user language).
2548 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2549 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2551 #For recording whether extension message files have been loaded in a given language.
2552 static $loaded = array();
2554 if( !array_key_exists( $extensionName, $loaded ) ) {
2555 $loaded[$extensionName] = array();
2558 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2559 # Just do en, content language and user language.
2560 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2561 # Mark that they have been loaded.
2562 $loaded[$extensionName]['en'] = true;
2563 $loaded[$extensionName][$wgLang->getCode()] = true;
2564 $loaded[$extensionName][$wgContLang->getCode()] = true;
2565 # Mark that this part has been done to avoid weird if statements.
2566 $loaded[$extensionName]['*'] = true;
2567 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2568 # Load messages for specified language.
2569 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2570 # Mark that they have been loaded.
2571 $loaded[$extensionName][$langcode] = true;
2576 * Get a platform-independent path to the null file, e.g.
2577 * /dev/null
2579 * @return string
2581 function wfGetNull() {
2582 return wfIsWindows()
2583 ? 'NUL'
2584 : '/dev/null';
2588 * Displays a maxlag error
2590 * @param string $host Server that lags the most
2591 * @param int $lag Maxlag (actual)
2592 * @param int $maxLag Maxlag (requested)
2594 function wfMaxlagError( $host, $lag, $maxLag ) {
2595 global $wgShowHostnames;
2596 header( 'HTTP/1.1 503 Service Unavailable' );
2597 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2598 header( 'X-Database-Lag: ' . intval( $lag ) );
2599 header( 'Content-Type: text/plain' );
2600 if( $wgShowHostnames ) {
2601 echo "Waiting for $host: $lag seconds lagged\n";
2602 } else {
2603 echo "Waiting for a database server: $lag seconds lagged\n";
2608 * Throws an E_USER_NOTICE saying that $function is deprecated
2609 * @param string $function
2610 * @return null
2612 function wfDeprecated( $function ) {
2613 global $wgDebugLogFile;
2614 if ( !$wgDebugLogFile ) {
2615 return;
2617 $callers = wfDebugBacktrace();
2618 if( isset( $callers[2] ) ){
2619 $callerfunc = $callers[2];
2620 $callerfile = $callers[1];
2621 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2622 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2623 } else {
2624 $file = '(internal function)';
2626 $func = '';
2627 if( isset( $callerfunc['class'] ) )
2628 $func .= $callerfunc['class'] . '::';
2629 $func .= @$callerfunc['function'];
2630 $msg = "Use of $function is deprecated. Called from $func in $file";
2631 } else {
2632 $msg = "Use of $function is deprecated.";
2634 wfDebug( "$msg\n" );
2638 * Sleep until the worst slave's replication lag is less than or equal to
2639 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2640 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2641 * a no-op if there are no slaves.
2643 * Every time the function has to wait for a slave, it will print a message to
2644 * that effect (and then sleep for a little while), so it's probably not best
2645 * to use this outside maintenance scripts in its present form.
2647 * @param int $maxLag
2648 * @return null
2650 function wfWaitForSlaves( $maxLag ) {
2651 if( $maxLag ) {
2652 $lb = wfGetLB();
2653 list( $host, $lag ) = $lb->getMaxLag();
2654 while( $lag > $maxLag ) {
2655 $name = @gethostbyaddr( $host );
2656 if( $name !== false ) {
2657 $host = $name;
2659 print "Waiting for $host (lagged $lag seconds)...\n";
2660 sleep($maxLag);
2661 list( $host, $lag ) = $lb->getMaxLag();
2666 /** Generate a random 32-character hexadecimal token.
2667 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2669 function wfGenerateToken( $salt = '' ) {
2670 $salt = serialize($salt);
2672 return md5( mt_rand( 0, 0x7fffffff ) . $salt );