3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
12 * Some globals and requires needed
15 /** Total number of articles */
16 $wgNumberOfArticles = -1; # Unset
18 /** Total number of views */
21 /** Total number of edits */
26 require_once dirname(__FILE__
) . '/LogPage.php';
27 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
28 require_once dirname(__FILE__
) . '/XmlFunctions.php';
31 * Compatibility functions
33 * We more or less support PHP 5.0.x and up.
34 * Re-implementations of newer functions or functions in non-standard
35 * PHP extensions may be included here.
37 if( !function_exists('iconv') ) {
38 # iconv support is not in the default configuration and so may not be present.
39 # Assume will only ever use utf-8 and iso-8859-1.
40 # This will *not* work in all circumstances.
41 function iconv( $from, $to, $string ) {
42 if(strcasecmp( $from, $to ) == 0) return $string;
43 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
44 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
49 # UTF-8 substr function based on a PHP manual comment
50 if ( !function_exists( 'mb_substr' ) ) {
51 function mb_substr( $str, $start ) {
53 preg_match_all( '/./us', $str, $ar );
55 if( func_num_args() >= 3 ) {
56 $end = func_get_arg( 2 );
57 return join( '', array_slice( $ar[0], $start, $end ) );
59 return join( '', array_slice( $ar[0], $start ) );
64 if ( !function_exists( 'mb_strlen' ) ) {
66 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
68 * @param string $enc optional encoding; ignored
71 function new_mb_strlen( $str, $enc="" ) {
72 $counts = count_chars( $str );
76 for( $i = 0; $i < 0x80; $i++
) {
77 $total +
= $counts[$i];
80 // Count multibyte sequence heads
81 for( $i = 0xc0; $i < 0xff; $i++
) {
82 $total +
= $counts[$i];
88 if ( !function_exists( 'array_diff_key' ) ) {
90 * Exists in PHP 5.1.0+
91 * Not quite compatible, two-argument version only
92 * Null values will cause problems due to this use of isset()
94 function array_diff_key( $left, $right ) {
96 foreach ( $left as $key => $unused ) {
97 if ( isset( $right[$key] ) ) {
98 unset( $result[$key] );
107 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
108 * PHP 5 won't let you declare a 'clone' function, even conditionally,
109 * so it has to be a wrapper with a different name.
111 function wfClone( $object ) {
112 return clone( $object );
116 * Where as we got a random seed
118 $wgRandomSeeded = false;
121 * Seed Mersenne Twister
122 * No-op for compatibility; only necessary in PHP < 4.2.0
124 function wfSeedRandom() {
129 * Get a random decimal value between 0 and 1, in a way
130 * not likely to give duplicate values for any realistic
131 * number of articles.
135 function wfRandom() {
136 # The maximum random value is "only" 2^31-1, so get two random
137 # values to reduce the chance of dupes
138 $max = mt_getrandmax() +
1;
139 $rand = number_format( (mt_rand() * $max +
mt_rand())
140 / $max / $max, 12, '.', '' );
145 * We want / and : to be included as literal characters in our title URLs.
146 * %2F in the page titles seems to fatally break for some reason.
151 function wfUrlencode ( $s ) {
152 $s = urlencode( $s );
153 $s = preg_replace( '/%3[Aa]/', ':', $s );
154 $s = preg_replace( '/%2[Ff]/', '/', $s );
160 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
161 * In normal operation this is a NOP.
163 * Controlling globals:
164 * $wgDebugLogFile - points to the log file
165 * $wgProfileOnly - if set, normal debug messages will not be recorded.
166 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
167 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
169 * @param $text String
170 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
172 function wfDebug( $text, $logonly = false ) {
173 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
174 static $recursion = 0;
176 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
177 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
181 if ( $wgDebugComments && !$logonly ) {
182 if ( !isset( $wgOut ) ) {
185 if ( !StubObject
::isRealObject( $wgOut ) ) {
193 $wgOut->debug( $text );
195 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
196 # Strip unprintables; they can switch terminal modes when binary data
197 # gets dumped, which is pretty annoying.
198 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
199 wfErrorLog( $text, $wgDebugLogFile );
204 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
205 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
207 * @param $logGroup String
208 * @param $text String
209 * @param $public Bool: whether to log the event in the public log if no private
210 * log file is specified, (default true)
212 function wfDebugLog( $logGroup, $text, $public = true ) {
213 global $wgDebugLogGroups;
214 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
215 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
216 $time = wfTimestamp( TS_DB
);
218 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
219 } else if ( $public === true ) {
220 wfDebug( $text, true );
225 * Log for database errors
226 * @param $text String: database error message.
228 function wfLogDBError( $text ) {
229 global $wgDBerrorLog, $wgDBname;
230 if ( $wgDBerrorLog ) {
231 $host = trim(`hostname`
);
232 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
233 wfErrorLog( $text, $wgDBerrorLog );
238 * Log to a file without getting "file size exceeded" signals
240 function wfErrorLog( $text, $file ) {
241 wfSuppressWarnings();
242 $exists = file_exists( $file );
243 $size = filesize( $file );
244 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
245 error_log( $text, 3, $file );
253 function wfLogProfilingData() {
254 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
255 global $wgProfiling, $wgUser;
256 if ( $wgProfiling ) {
258 $elapsed = $now - $wgRequestTime;
259 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
261 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
262 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
263 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
264 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
265 if( !empty( $_SERVER['HTTP_FROM'] ) )
266 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
268 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
269 // Don't unstub $wgUser at this late stage just for statistics purposes
270 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
272 $log = sprintf( "%s\t%04.3f\t%s\n",
273 gmdate( 'YmdHis' ), $elapsed,
274 urldecode( $wgRequest->getRequestURL() . $forward ) );
275 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
276 wfErrorLog( $log . $prof, $wgDebugLogFile );
282 * Check if the wiki read-only lock file is present. This can be used to lock
283 * off editing functions, but doesn't guarantee that the database will not be
287 function wfReadOnly() {
288 global $wgReadOnlyFile, $wgReadOnly;
290 if ( !is_null( $wgReadOnly ) ) {
291 return (bool)$wgReadOnly;
293 if ( '' == $wgReadOnlyFile ) {
296 // Set $wgReadOnly for faster access next time
297 if ( is_file( $wgReadOnlyFile ) ) {
298 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
302 return (bool)$wgReadOnly;
307 * Get a message from anywhere, for the current user language.
309 * Use wfMsgForContent() instead if the message should NOT
310 * change depending on the user preferences.
312 * Note that the message may contain HTML, and is therefore
313 * not safe for insertion anywhere. Some functions such as
314 * addWikiText will do the escaping for you. Use wfMsgHtml()
315 * if you need an escaped message.
317 * @param $key String: lookup key for the message, usually
318 * defined in languages/Language.php
320 * This function also takes extra optional parameters (not
321 * shown in the function definition), which can by used to
322 * insert variable text into the predefined message.
324 function wfMsg( $key ) {
325 $args = func_get_args();
326 array_shift( $args );
327 return wfMsgReal( $key, $args, true );
331 * Same as above except doesn't transform the message
333 function wfMsgNoTrans( $key ) {
334 $args = func_get_args();
335 array_shift( $args );
336 return wfMsgReal( $key, $args, true, false, false );
340 * Get a message from anywhere, for the current global language
341 * set with $wgLanguageCode.
343 * Use this if the message should NOT change dependent on the
344 * language set in the user's preferences. This is the case for
345 * most text written into logs, as well as link targets (such as
346 * the name of the copyright policy page). Link titles, on the
347 * other hand, should be shown in the UI language.
349 * Note that MediaWiki allows users to change the user interface
350 * language in their preferences, but a single installation
351 * typically only contains content in one language.
353 * Be wary of this distinction: If you use wfMsg() where you should
354 * use wfMsgForContent(), a user of the software may have to
355 * customize over 70 messages in order to, e.g., fix a link in every
358 * @param $key String: lookup key for the message, usually
359 * defined in languages/Language.php
361 function wfMsgForContent( $key ) {
362 global $wgForceUIMsgAsContentMsg;
363 $args = func_get_args();
364 array_shift( $args );
366 if( is_array( $wgForceUIMsgAsContentMsg ) &&
367 in_array( $key, $wgForceUIMsgAsContentMsg ) )
369 return wfMsgReal( $key, $args, true, $forcontent );
373 * Same as above except doesn't transform the message
375 function wfMsgForContentNoTrans( $key ) {
376 global $wgForceUIMsgAsContentMsg;
377 $args = func_get_args();
378 array_shift( $args );
380 if( is_array( $wgForceUIMsgAsContentMsg ) &&
381 in_array( $key, $wgForceUIMsgAsContentMsg ) )
383 return wfMsgReal( $key, $args, true, $forcontent, false );
387 * Get a message from the language file, for the UI elements
389 function wfMsgNoDB( $key ) {
390 $args = func_get_args();
391 array_shift( $args );
392 return wfMsgReal( $key, $args, false );
396 * Get a message from the language file, for the content
398 function wfMsgNoDBForContent( $key ) {
399 global $wgForceUIMsgAsContentMsg;
400 $args = func_get_args();
401 array_shift( $args );
403 if( is_array( $wgForceUIMsgAsContentMsg ) &&
404 in_array( $key, $wgForceUIMsgAsContentMsg ) )
406 return wfMsgReal( $key, $args, false, $forcontent );
411 * Really get a message
412 * @param $key String: key to get.
414 * @param $useDB Boolean
415 * @param $transform Boolean: Whether or not to transform the message.
416 * @param $forContent Boolean
417 * @return String: the requested message.
419 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
420 $fname = 'wfMsgReal';
421 wfProfileIn( $fname );
422 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
423 $message = wfMsgReplaceArgs( $message, $args );
424 wfProfileOut( $fname );
429 * This function provides the message source for messages to be edited which are *not* stored in the database.
430 * @param $key String:
432 function wfMsgWeirdKey ( $key ) {
433 $subsource = str_replace ( ' ' , '_' , $key ) ;
434 $source = wfMsgForContentNoTrans( $subsource ) ;
435 if ( wfEmptyMsg( $subsource, $source) ) {
436 # Try again with first char lower case
437 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
438 $source = wfMsgForContentNoTrans( $subsource ) ;
440 if ( wfEmptyMsg( $subsource, $source ) ) {
441 # Didn't work either, return blank text
448 * Fetch a message string value, but don't replace any keys yet.
451 * @param bool $forContent
455 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
456 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
458 if ( is_object( $wgMessageCache ) )
459 $transstat = $wgMessageCache->getTransform();
461 if( is_object( $wgMessageCache ) ) {
463 $wgMessageCache->disableTransform();
464 $message = $wgMessageCache->get( $key, $useDB, $forContent );
467 $lang = &$wgContLang;
472 wfSuppressWarnings();
474 if( is_object( $lang ) ) {
475 $message = $lang->getMessage( $key );
480 if($message === false)
481 $message = Language
::getMessage($key);
482 if ( $transform && strstr( $message, '{{' ) !== false ) {
483 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
487 if ( is_object( $wgMessageCache ) && ! $transform )
488 $wgMessageCache->setTransform( $transstat );
494 * Replace message parameter keys on the given formatted output.
496 * @param string $message
501 function wfMsgReplaceArgs( $message, $args ) {
502 # Fix windows line-endings
503 # Some messages are split with explode("\n", $msg)
504 $message = str_replace( "\r", '', $message );
507 if ( count( $args ) ) {
508 if ( is_array( $args[0] ) ) {
509 foreach ( $args[0] as $key => $val ) {
510 $message = str_replace( '$' . $key, $val, $message );
513 foreach( $args as $n => $param ) {
514 $replacementKeys['$' . ($n +
1)] = $param;
516 $message = strtr( $message, $replacementKeys );
524 * Return an HTML-escaped version of a message.
525 * Parameter replacements, if any, are done *after* the HTML-escaping,
526 * so parameters may contain HTML (eg links or form controls). Be sure
527 * to pre-escape them if you really do want plaintext, or just wrap
528 * the whole thing in htmlspecialchars().
531 * @param string ... parameters
534 function wfMsgHtml( $key ) {
535 $args = func_get_args();
536 array_shift( $args );
537 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
541 * Return an HTML version of message
542 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
543 * so parameters may contain HTML (eg links or form controls). Be sure
544 * to pre-escape them if you really do want plaintext, or just wrap
545 * the whole thing in htmlspecialchars().
548 * @param string ... parameters
551 function wfMsgWikiHtml( $key ) {
553 $args = func_get_args();
554 array_shift( $args );
555 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
559 * Returns message in the requested format
560 * @param string $key Key of the message
561 * @param array $options Processing rules:
562 * <i>parse<i>: parses wikitext to html
563 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
564 * <i>escape<i>: filters message trough htmlspecialchars
565 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
566 * <i>parsemag<i>: transform the message using magic phrases
568 function wfMsgExt( $key, $options ) {
569 global $wgOut, $wgParser;
571 $args = func_get_args();
572 array_shift( $args );
573 array_shift( $args );
575 if( !is_array($options) ) {
576 $options = array($options);
579 $string = wfMsgGetKey( $key, true, false, false );
581 if( !in_array('replaceafter', $options) ) {
582 $string = wfMsgReplaceArgs( $string, $args );
585 if( in_array('parse', $options) ) {
586 $string = $wgOut->parse( $string, true, true );
587 } elseif ( in_array('parseinline', $options) ) {
588 $string = $wgOut->parse( $string, true, true );
590 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
593 } elseif ( in_array('parsemag', $options) ) {
594 global $wgMessageCache;
595 if ( isset( $wgMessageCache ) ) {
596 $string = $wgMessageCache->transform( $string );
600 if ( in_array('escape', $options) ) {
601 $string = htmlspecialchars ( $string );
604 if( in_array('replaceafter', $options) ) {
605 $string = wfMsgReplaceArgs( $string, $args );
613 * Just like exit() but makes a note of it.
614 * Commits open transactions except if the error parameter is set
616 * @obsolete Please return control to the caller or throw an exception
618 function wfAbruptExit( $error = false ){
619 global $wgLoadBalancer;
620 static $called = false;
626 $bt = wfDebugBacktrace();
628 for($i = 0; $i < count($bt) ; $i++
){
629 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
630 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
631 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
634 wfDebug('WARNING: Abrupt exit\n');
637 wfLogProfilingData();
640 $wgLoadBalancer->closeAll();
646 * @obsolete Please return control the caller or throw an exception
648 function wfErrorExit() {
649 wfAbruptExit( true );
653 * Print a simple message and die, returning nonzero to the shell if any.
654 * Plain die() fails to return nonzero to the shell if you pass a string.
657 function wfDie( $msg='' ) {
663 * Throw a debugging exception. This function previously once exited the process,
664 * but now throws an exception instead, with similar results.
666 * @param string $msg Message shown when dieing.
668 function wfDebugDieBacktrace( $msg = '' ) {
669 throw new MWException( $msg );
673 * Fetch server name for use in error reporting etc.
674 * Use real server name if available, so we know which machine
675 * in a server farm generated the current page.
678 function wfHostname() {
679 if ( function_exists( 'posix_uname' ) ) {
680 // This function not present on Windows
681 $uname = @posix_uname
();
685 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
686 return $uname['nodename'];
688 # This may be a virtual server.
689 return $_SERVER['SERVER_NAME'];
694 * Returns a HTML comment with the elapsed time since request.
695 * This method has no side effects.
698 function wfReportTime() {
699 global $wgRequestTime;
702 $elapsed = $now - $wgRequestTime;
704 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
705 wfHostname(), $elapsed );
710 * Safety wrapper for debug_backtrace().
712 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
713 * murky circumstances, which may be triggered in part by stub objects
714 * or other fancy talkin'.
716 * Will return an empty array if Zend Optimizer is detected, otherwise
717 * the output from debug_backtrace() (trimmed).
719 * @return array of backtrace information
721 function wfDebugBacktrace() {
722 if( extension_loaded( 'Zend Optimizer' ) ) {
723 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
726 return array_slice( debug_backtrace(), 1 );
730 function wfBacktrace() {
731 global $wgCommandLineMode;
733 if ( $wgCommandLineMode ) {
738 $backtrace = wfDebugBacktrace();
739 foreach( $backtrace as $call ) {
740 if( isset( $call['file'] ) ) {
741 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
742 $file = $f[count($f)-1];
746 if( isset( $call['line'] ) ) {
747 $line = $call['line'];
751 if ( $wgCommandLineMode ) {
752 $msg .= "$file line $line calls ";
754 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
756 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
757 $msg .= $call['function'] . '()';
759 if ( $wgCommandLineMode ) {
765 if ( $wgCommandLineMode ) {
775 /* Some generic result counters, pulled out of SearchEngine */
781 function wfShowingResults( $offset, $limit ) {
783 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
789 function wfShowingResultsNum( $offset, $limit, $num ) {
791 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
797 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
799 $fmtLimit = $wgLang->formatNum( $limit );
800 $prev = wfMsg( 'prevn', $fmtLimit );
801 $next = wfMsg( 'nextn', $fmtLimit );
803 if( is_object( $link ) ) {
806 $title = Title
::newFromText( $link );
807 if( is_null( $title ) ) {
812 if ( 0 != $offset ) {
813 $po = $offset - $limit;
814 if ( $po < 0 ) { $po = 0; }
815 $q = "limit={$limit}&offset={$po}";
816 if ( '' != $query ) { $q .= '&'.$query; }
817 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
818 } else { $plink = $prev; }
820 $no = $offset +
$limit;
821 $q = 'limit='.$limit.'&offset='.$no;
822 if ( '' != $query ) { $q .= '&'.$query; }
827 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
829 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
830 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
831 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
832 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
833 wfNumLink( $offset, 500, $title, $query );
835 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
841 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
843 if ( '' == $query ) { $q = ''; }
844 else { $q = $query.'&'; }
845 $q .= 'limit='.$limit.'&offset='.$offset;
847 $fmtLimit = $wgLang->formatNum( $limit );
848 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
854 * @todo FIXME: we may want to blacklist some broken browsers
856 * @return bool Whereas client accept gzip compression
858 function wfClientAcceptsGzip() {
861 # FIXME: we may want to blacklist some broken browsers
864 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
865 $_SERVER['HTTP_ACCEPT_ENCODING'],
867 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
868 wfDebug( " accepts gzip\n" );
876 * Obtain the offset and limit values from the request string;
877 * used in special pages
879 * @param $deflimit Default limit if none supplied
880 * @param $optionname Name of a user preference to check against
884 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
886 return $wgRequest->getLimitOffset( $deflimit, $optionname );
890 * Escapes the given text so that it may be output using addWikiText()
891 * without any linking, formatting, etc. making its way through. This
892 * is achieved by substituting certain characters with HTML entities.
893 * As required by the callers, <nowiki> is not used. It currently does
894 * not filter out characters which have special meaning only at the
895 * start of a line, such as "*".
897 * @param string $text Text to be escaped
899 function wfEscapeWikiText( $text ) {
901 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
902 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
903 htmlspecialchars($text) );
910 function wfQuotedPrintable( $string, $charset = '' ) {
911 # Probably incomplete; see RFC 2045
912 if( empty( $charset ) ) {
913 global $wgInputEncoding;
914 $charset = $wgInputEncoding;
916 $charset = strtoupper( $charset );
917 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
919 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
920 $replace = $illegal . '\t ?_';
921 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
922 $out = "=?$charset?Q?";
923 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
934 return microtime(true);
938 * Sets dest to source and returns the original value of dest
939 * If source is NULL, it just returns the value, it doesn't set the variable
941 function wfSetVar( &$dest, $source ) {
943 if ( !is_null( $source ) ) {
950 * As for wfSetVar except setting a bit
952 function wfSetBit( &$dest, $bit, $state = true ) {
953 $temp = (bool)($dest & $bit );
954 if ( !is_null( $state ) ) {
965 * This function takes two arrays as input, and returns a CGI-style string, e.g.
966 * "days=7&limit=100". Options in the first array override options in the second.
967 * Options set to "" will not be output.
969 function wfArrayToCGI( $array1, $array2 = NULL )
971 if ( !is_null( $array2 ) ) {
972 $array1 = $array1 +
$array2;
976 foreach ( $array1 as $key => $value ) {
977 if ( '' !== $value ) {
981 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
988 * This is obsolete, use SquidUpdate::purge()
991 function wfPurgeSquidServers ($urlArr) {
992 SquidUpdate
::purge( $urlArr );
996 * Windows-compatible version of escapeshellarg()
997 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
998 * function puts single quotes in regardless of OS
1000 function wfEscapeShellArg( ) {
1001 $args = func_get_args();
1004 foreach ( $args as $arg ) {
1011 if ( wfIsWindows() ) {
1012 // Escaping for an MSVC-style command line parser
1013 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1014 // Double the backslashes before any double quotes. Escape the double quotes.
1015 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1018 foreach ( $tokens as $token ) {
1020 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1026 // Double the backslashes before the end of the string, because
1027 // we will soon add a quote
1029 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1030 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1033 // Add surrounding quotes
1034 $retVal .= '"' . $arg . '"';
1036 $retVal .= escapeshellarg( $arg );
1043 * wfMerge attempts to merge differences between three texts.
1044 * Returns true for a clean merge and false for failure or a conflict.
1046 function wfMerge( $old, $mine, $yours, &$result ){
1049 # This check may also protect against code injection in
1050 # case of broken installations.
1051 if(! file_exists( $wgDiff3 ) ){
1052 wfDebug( "diff3 not found\n" );
1056 # Make temporary files
1058 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1059 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1060 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1062 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1063 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1064 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1066 # Check for a conflict
1067 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1068 wfEscapeShellArg( $mytextName ) . ' ' .
1069 wfEscapeShellArg( $oldtextName ) . ' ' .
1070 wfEscapeShellArg( $yourtextName );
1071 $handle = popen( $cmd, 'r' );
1073 if( fgets( $handle, 1024 ) ){
1081 $cmd = $wgDiff3 . ' -a -e --merge ' .
1082 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1083 $handle = popen( $cmd, 'r' );
1086 $data = fread( $handle, 8192 );
1087 if ( strlen( $data ) == 0 ) {
1093 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1095 if ( $result === '' && $old !== '' && $conflict == false ) {
1096 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1105 function wfVarDump( $var ) {
1107 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1108 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1111 $wgOut->addHTML( $s );
1116 * Provide a simple HTTP error.
1118 function wfHttpError( $code, $label, $desc ) {
1121 header( "HTTP/1.0 $code $label" );
1122 header( "Status: $code $label" );
1123 $wgOut->sendCacheControl();
1125 header( 'Content-type: text/html; charset=utf-8' );
1126 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1127 "<html><head><title>" .
1128 htmlspecialchars( $label ) .
1129 "</title></head><body><h1>" .
1130 htmlspecialchars( $label ) .
1132 nl2br( htmlspecialchars( $desc ) ) .
1133 "</p></body></html>\n";
1137 * Clear away any user-level output buffers, discarding contents.
1139 * Suitable for 'starting afresh', for instance when streaming
1140 * relatively large amounts of data without buffering, or wanting to
1141 * output image files without ob_gzhandler's compression.
1143 * The optional $resetGzipEncoding parameter controls suppression of
1144 * the Content-Encoding header sent by ob_gzhandler; by default it
1145 * is left. See comments for wfClearOutputBuffers() for why it would
1148 * Note that some PHP configuration options may add output buffer
1149 * layers which cannot be removed; these are left in place.
1151 * @parameter bool $resetGzipEncoding
1153 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1154 if( $resetGzipEncoding ) {
1155 // Suppress Content-Encoding and Content-Length
1156 // headers from 1.10+s wfOutputHandler
1157 global $wgDisableOutputCompression;
1158 $wgDisableOutputCompression = true;
1160 while( $status = ob_get_status() ) {
1161 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1162 // Probably from zlib.output_compression or other
1163 // PHP-internal setting which can't be removed.
1165 // Give up, and hope the result doesn't break
1169 if( !ob_end_clean() ) {
1170 // Could not remove output buffer handler; abort now
1171 // to avoid getting in some kind of infinite loop.
1174 if( $resetGzipEncoding ) {
1175 if( $status['name'] == 'ob_gzhandler' ) {
1176 // Reset the 'Content-Encoding' field set by this handler
1177 // so we can start fresh.
1178 header( 'Content-Encoding:' );
1185 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1187 * Clear away output buffers, but keep the Content-Encoding header
1188 * produced by ob_gzhandler, if any.
1190 * This should be used for HTTP 304 responses, where you need to
1191 * preserve the Content-Encoding header of the real result, but
1192 * also need to suppress the output of ob_gzhandler to keep to spec
1193 * and avoid breaking Firefox in rare cases where the headers and
1194 * body are broken over two packets.
1196 function wfClearOutputBuffers() {
1197 wfResetOutputBuffers( false );
1201 * Converts an Accept-* header into an array mapping string values to quality
1204 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1205 # No arg means accept anything (per HTTP spec)
1207 return array( $def => 1 );
1212 $parts = explode( ',', $accept );
1214 foreach( $parts as $part ) {
1215 # FIXME: doesn't deal with params like 'text/html; level=1'
1216 @list
( $value, $qpart ) = explode( ';', $part );
1218 if( !isset( $qpart ) ) {
1220 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1221 $prefs[$value] = $match[1];
1229 * Checks if a given MIME type matches any of the keys in the given
1230 * array. Basic wildcards are accepted in the array keys.
1232 * Returns the matching MIME type (or wildcard) if a match, otherwise
1235 * @param string $type
1236 * @param array $avail
1240 function mimeTypeMatch( $type, $avail ) {
1241 if( array_key_exists($type, $avail) ) {
1244 $parts = explode( '/', $type );
1245 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1246 return $parts[0] . '/*';
1247 } elseif( array_key_exists( '*/*', $avail ) ) {
1256 * Returns the 'best' match between a client's requested internet media types
1257 * and the server's list of available types. Each list should be an associative
1258 * array of type to preference (preference is a float between 0.0 and 1.0).
1259 * Wildcards in the types are acceptable.
1261 * @param array $cprefs Client's acceptable type list
1262 * @param array $sprefs Server's offered types
1265 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1266 * XXX: generalize to negotiate other stuff
1268 function wfNegotiateType( $cprefs, $sprefs ) {
1271 foreach( array_keys($sprefs) as $type ) {
1272 $parts = explode( '/', $type );
1273 if( $parts[1] != '*' ) {
1274 $ckey = mimeTypeMatch( $type, $cprefs );
1276 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1281 foreach( array_keys( $cprefs ) as $type ) {
1282 $parts = explode( '/', $type );
1283 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1284 $skey = mimeTypeMatch( $type, $sprefs );
1286 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1294 foreach( array_keys( $combine ) as $type ) {
1295 if( $combine[$type] > $bestq ) {
1297 $bestq = $combine[$type];
1306 * Returns an array where the values in the first array are replaced by the
1307 * values in the second array with the corresponding keys
1311 function wfArrayLookup( $a, $b ) {
1312 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1316 * Convenience function; returns MediaWiki timestamp for the present time.
1319 function wfTimestampNow() {
1321 return wfTimestamp( TS_MW
, time() );
1325 * Reference-counted warning suppression
1327 function wfSuppressWarnings( $end = false ) {
1328 static $suppressCount = 0;
1329 static $originalLevel = false;
1332 if ( $suppressCount ) {
1334 if ( !$suppressCount ) {
1335 error_reporting( $originalLevel );
1339 if ( !$suppressCount ) {
1340 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1347 * Restore error level to previous value
1349 function wfRestoreWarnings() {
1350 wfSuppressWarnings( true );
1353 # Autodetect, convert and provide timestamps of various types
1356 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1358 define('TS_UNIX', 0);
1361 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1366 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1371 * RFC 2822 format, for E-mail and HTTP headers
1373 define('TS_RFC2822', 3);
1376 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1378 * This is used by Special:Export
1380 define('TS_ISO_8601', 4);
1383 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1385 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1386 * DateTime tag and page 36 for the DateTimeOriginal and
1387 * DateTimeDigitized tags.
1389 define('TS_EXIF', 5);
1392 * Oracle format time.
1394 define('TS_ORACLE', 6);
1397 * Postgres format time.
1399 define('TS_POSTGRES', 7);
1402 * @param mixed $outputtype A timestamp in one of the supported formats, the
1403 * function will autodetect which format is supplied
1404 * and act accordingly.
1405 * @return string Time in the format specified in $outputtype
1407 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1412 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1414 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1415 (int)$da[2],(int)$da[3],(int)$da[1]);
1416 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1418 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1419 (int)$da[2],(int)$da[3],(int)$da[1]);
1420 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1422 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1423 (int)$da[2],(int)$da[3],(int)$da[1]);
1424 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1427 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1429 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1430 str_replace("+00:00", "UTC", $ts)));
1431 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1433 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1434 (int)$da[2],(int)$da[3],(int)$da[1]);
1435 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1437 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1438 (int)$da[2],(int)$da[3],(int)$da[1]);
1439 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1441 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1442 (int)$da[2],(int)$da[3],(int)$da[1]);
1444 # Bogus value; fall back to the epoch...
1445 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1450 switch($outputtype) {
1454 return gmdate( 'YmdHis', $uts );
1456 return gmdate( 'Y-m-d H:i:s', $uts );
1458 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1459 // This shouldn't ever be used, but is included for completeness
1461 return gmdate( 'Y:m:d H:i:s', $uts );
1463 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1465 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1467 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1469 throw new MWException( 'wfTimestamp() called with illegal output type.');
1474 * Return a formatted timestamp, or null if input is null.
1475 * For dealing with nullable timestamp columns in the database.
1476 * @param int $outputtype
1480 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1481 if( is_null( $ts ) ) {
1484 return wfTimestamp( $outputtype, $ts );
1489 * Check if the operating system is Windows
1491 * @return bool True if it's Windows, False otherwise.
1493 function wfIsWindows() {
1494 if (substr(php_uname(), 0, 7) == 'Windows') {
1502 * Swap two variables
1504 function swap( &$x, &$y ) {
1510 function wfGetCachedNotice( $name ) {
1511 global $wgOut, $parserMemc;
1512 $fname = 'wfGetCachedNotice';
1513 wfProfileIn( $fname );
1517 if( $name === 'default' ) {
1519 global $wgSiteNotice;
1520 $notice = $wgSiteNotice;
1521 if( empty( $notice ) ) {
1522 wfProfileOut( $fname );
1526 $notice = wfMsgForContentNoTrans( $name );
1527 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1528 wfProfileOut( $fname );
1533 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1534 if( is_array( $cachedNotice ) ) {
1535 if( md5( $notice ) == $cachedNotice['hash'] ) {
1536 $notice = $cachedNotice['html'];
1545 if( is_object( $wgOut ) ) {
1546 $parsed = $wgOut->parse( $notice );
1547 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1550 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1555 wfProfileOut( $fname );
1559 function wfGetNamespaceNotice() {
1563 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1566 $fname = 'wfGetNamespaceNotice';
1567 wfProfileIn( $fname );
1569 $key = "namespacenotice-" . $wgTitle->getNsText();
1570 $namespaceNotice = wfGetCachedNotice( $key );
1571 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1572 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1574 $namespaceNotice = "";
1577 wfProfileOut( $fname );
1578 return $namespaceNotice;
1581 function wfGetSiteNotice() {
1582 global $wgUser, $wgSiteNotice;
1583 $fname = 'wfGetSiteNotice';
1584 wfProfileIn( $fname );
1587 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1588 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1589 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1591 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1592 if( !$anonNotice ) {
1593 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1595 $siteNotice = $anonNotice;
1598 if( !$siteNotice ) {
1599 $siteNotice = wfGetCachedNotice( 'default' );
1603 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1604 wfProfileOut( $fname );
1609 * BC wrapper for MimeMagic::singleton()
1612 function &wfGetMimeMagic() {
1613 return MimeMagic
::singleton();
1617 * Tries to get the system directory for temporary files.
1618 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1619 * and if none are set /tmp is returned as the generic Unix default.
1621 * NOTE: When possible, use the tempfile() function to create temporary
1622 * files to avoid race conditions on file creation, etc.
1626 function wfTempDir() {
1627 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1628 $tmp = getenv( $var );
1629 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1633 # Hope this is Unix of some kind!
1638 * Make directory, and make all parent directories if they don't exist
1640 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1641 if ( strval( $fullDir ) === '' ) {
1645 # Go back through the paths to find the first directory that exists
1646 $currentDir = $fullDir;
1647 $createList = array();
1648 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1649 # Strip trailing slashes
1650 $currentDir = rtrim( $currentDir, '/\\' );
1652 # Add to create list
1653 $createList[] = $currentDir;
1655 # Find next delimiter searching from the end
1656 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1657 if ( $p === false ) {
1658 $currentDir = false;
1660 $currentDir = substr( $currentDir, 0, $p );
1664 if ( count( $createList ) == 0 ) {
1665 # Directory specified already exists
1667 } elseif ( $currentDir === false ) {
1668 # Went all the way back to root and it apparently doesn't exist
1672 # Now go forward creating directories
1673 $createList = array_reverse( $createList );
1674 foreach ( $createList as $dir ) {
1675 # use chmod to override the umask, as suggested by the PHP manual
1676 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1677 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1685 * Increment a statistics counter
1687 function wfIncrStats( $key ) {
1689 $key = wfMemcKey( 'stats', $key );
1690 if ( is_null( $wgMemc->incr( $key ) ) ) {
1691 $wgMemc->add( $key, 1 );
1696 * @param mixed $nr The number to format
1697 * @param int $acc The number of digits after the decimal point, default 2
1698 * @param bool $round Whether or not to round the value, default true
1701 function wfPercent( $nr, $acc = 2, $round = true ) {
1702 $ret = sprintf( "%.${acc}f", $nr );
1703 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1707 * Encrypt a username/password.
1709 * @param string $userid ID of the user
1710 * @param string $password Password of the user
1711 * @return string Hashed password
1713 function wfEncryptPassword( $userid, $password ) {
1714 global $wgPasswordSalt;
1715 $p = md5( $password);
1718 return md5( "{$userid}-{$p}" );
1724 * Appends to second array if $value differs from that in $default
1726 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1727 if ( is_null( $changed ) ) {
1728 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1730 if ( $default[$key] !== $value ) {
1731 $changed[$key] = $value;
1736 * Since wfMsg() and co suck, they don't return false if the message key they
1737 * looked up didn't exist but a XHTML string, this function checks for the
1738 * nonexistance of messages by looking at wfMsg() output
1740 * @param $msg The message key looked up
1741 * @param $wfMsgOut The output of wfMsg*()
1744 function wfEmptyMsg( $msg, $wfMsgOut ) {
1745 return $wfMsgOut === "<$msg>";
1749 * Find out whether or not a mixed variable exists in a string
1751 * @param mixed needle
1752 * @param string haystack
1755 function in_string( $needle, $str ) {
1756 return strpos( $str, $needle ) !== false;
1759 function wfSpecialList( $page, $details ) {
1761 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1762 return $page . $details;
1766 * Returns a regular expression of url protocols
1770 function wfUrlProtocols() {
1771 global $wgUrlProtocols;
1773 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1774 // with LocalSettings files from 1.5
1775 if ( is_array( $wgUrlProtocols ) ) {
1776 $protocols = array();
1777 foreach ($wgUrlProtocols as $protocol)
1778 $protocols[] = preg_quote( $protocol, '/' );
1780 return implode( '|', $protocols );
1782 return $wgUrlProtocols;
1787 * Execute a shell command, with time and memory limits mirrored from the PHP
1788 * configuration if supported.
1789 * @param $cmd Command line, properly escaped for shell.
1790 * @param &$retval optional, will receive the program's exit code.
1791 * (non-zero is usually failure)
1792 * @return collected stdout as a string (trailing newlines stripped)
1794 function wfShellExec( $cmd, &$retval=null ) {
1795 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1797 if( ini_get( 'safe_mode' ) ) {
1798 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1800 return "Unable to run external programs in safe mode.";
1803 if ( php_uname( 's' ) == 'Linux' ) {
1804 $time = ini_get( 'max_execution_time' );
1805 $mem = intval( $wgMaxShellMemory );
1806 $filesize = intval( $wgMaxShellFileSize );
1808 if ( $time > 0 && $mem > 0 ) {
1809 $script = "$IP/bin/ulimit-tvf.sh";
1810 if ( is_executable( $script ) ) {
1811 $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
1814 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1815 # This is a hack to work around PHP's flawed invocation of cmd.exe
1816 # http://news.php.net/php.internals/21796
1817 $cmd = '"' . $cmd . '"';
1819 wfDebug( "wfShellExec: $cmd\n" );
1822 $retval = 1; // error by default?
1823 exec( $cmd, $output, $retval ); // returns the last line of output.
1824 return implode( "\n", $output );
1829 * This function works like "use VERSION" in Perl, the program will die with a
1830 * backtrace if the current version of PHP is less than the version provided
1832 * This is useful for extensions which due to their nature are not kept in sync
1833 * with releases, and might depend on other versions of PHP than the main code
1835 * Note: PHP might die due to parsing errors in some cases before it ever
1836 * manages to call this function, such is life
1838 * @see perldoc -f use
1840 * @param mixed $version The version to check, can be a string, an integer, or
1843 function wfUsePHP( $req_ver ) {
1844 $php_ver = PHP_VERSION
;
1846 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1847 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1851 * This function works like "use VERSION" in Perl except it checks the version
1852 * of MediaWiki, the program will die with a backtrace if the current version
1853 * of MediaWiki is less than the version provided.
1855 * This is useful for extensions which due to their nature are not kept in sync
1858 * @see perldoc -f use
1860 * @param mixed $version The version to check, can be a string, an integer, or
1863 function wfUseMW( $req_ver ) {
1866 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1867 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1871 * @deprecated use StringUtils::escapeRegexReplacement
1873 function wfRegexReplacement( $string ) {
1874 return StringUtils
::escapeRegexReplacement( $string );
1878 * Return the final portion of a pathname.
1879 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1880 * http://bugs.php.net/bug.php?id=33898
1882 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1883 * We'll consider it so always, as we don't want \s in our Unix paths either.
1885 * @param string $path
1888 function wfBaseName( $path ) {
1890 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1898 * Generate a relative path name to the given file.
1899 * May explode on non-matching case-insensitive paths,
1900 * funky symlinks, etc.
1902 * @param string $path Absolute destination path including target filename
1903 * @param string $from Absolute source path, directory only
1906 function wfRelativePath( $path, $from ) {
1907 // Normalize mixed input on Windows...
1908 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1909 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1911 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1912 $against = explode( DIRECTORY_SEPARATOR
, $from );
1914 // Trim off common prefix
1915 while( count( $pieces ) && count( $against )
1916 && $pieces[0] == $against[0] ) {
1917 array_shift( $pieces );
1918 array_shift( $against );
1921 // relative dots to bump us to the parent
1922 while( count( $against ) ) {
1923 array_unshift( $pieces, '..' );
1924 array_shift( $against );
1927 array_push( $pieces, wfBaseName( $path ) );
1929 return implode( DIRECTORY_SEPARATOR
, $pieces );
1933 * Make a URL index, appropriate for the el_index field of externallinks.
1935 function wfMakeUrlIndex( $url ) {
1936 wfSuppressWarnings();
1937 $bits = parse_url( $url );
1938 wfRestoreWarnings();
1939 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1942 // Reverse the labels in the hostname, convert to lower case
1943 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1944 // Add an extra dot to the end
1945 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1946 $reversedHost .= '.';
1948 // Reconstruct the pseudo-URL
1949 $index = "http://$reversedHost";
1950 // Leave out user and password. Add the port, path, query and fragment
1951 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1952 if ( isset( $bits['path'] ) ) {
1953 $index .= $bits['path'];
1957 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1958 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1963 * Do any deferred updates and clear the list
1964 * TODO: This could be in Wiki.php if that class made any sense at all
1966 function wfDoUpdates()
1968 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1969 foreach ( $wgDeferredUpdateList as $update ) {
1970 $update->doUpdate();
1972 foreach ( $wgPostCommitUpdateList as $update ) {
1973 $update->doUpdate();
1975 $wgDeferredUpdateList = array();
1976 $wgPostCommitUpdateList = array();
1980 * @deprecated use StringUtils::explodeMarkup
1982 function wfExplodeMarkup( $separator, $text ) {
1983 return StringUtils
::explodeMarkup( $separator, $text );
1987 * Convert an arbitrarily-long digit string from one numeric base
1988 * to another, optionally zero-padding to a minimum column width.
1990 * Supports base 2 through 36; digit values 10-36 are represented
1991 * as lowercase letters a-z. Input is case-insensitive.
1993 * @param $input string of digits
1994 * @param $sourceBase int 2-36
1995 * @param $destBase int 2-36
1996 * @param $pad int 1 or greater
1997 * @return string or false on invalid input
1999 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2000 $input = strval( $input );
2001 if( $sourceBase < 2 ||
2006 $sourceBase != intval( $sourceBase ) ||
2007 $destBase != intval( $destBase ) ||
2008 $pad != intval( $pad ) ||
2009 !is_string( $input ) ||
2013 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2014 $inDigits = array();
2017 // Decode and validate input string
2018 $input = strtolower( $input );
2019 for( $i = 0; $i < strlen( $input ); $i++
) {
2020 $n = strpos( $digitChars, $input{$i} );
2021 if( $n === false ||
$n > $sourceBase ) {
2027 // Iterate over the input, modulo-ing out an output digit
2028 // at a time until input is gone.
2029 while( count( $inDigits ) ) {
2031 $workDigits = array();
2034 foreach( $inDigits as $digit ) {
2035 $work *= $sourceBase;
2038 if( $work < $destBase ) {
2039 // Gonna need to pull another digit.
2040 if( count( $workDigits ) ) {
2041 // Avoid zero-padding; this lets us find
2042 // the end of the input very easily when
2043 // length drops to zero.
2047 // Finally! Actual division!
2048 $workDigits[] = intval( $work / $destBase );
2050 // Isn't it annoying that most programming languages
2051 // don't have a single divide-and-remainder operator,
2052 // even though the CPU implements it that way?
2053 $work = $work %
$destBase;
2057 // All that division leaves us with a remainder,
2058 // which is conveniently our next output digit.
2059 $outChars .= $digitChars[$work];
2062 $inDigits = $workDigits;
2065 while( strlen( $outChars ) < $pad ) {
2069 return strrev( $outChars );
2073 * Create an object with a given name and an array of construct parameters
2074 * @param string $name
2075 * @param array $p parameters
2077 function wfCreateObject( $name, $p ){
2078 $p = array_values( $p );
2079 switch ( count( $p ) ) {
2083 return new $name( $p[0] );
2085 return new $name( $p[0], $p[1] );
2087 return new $name( $p[0], $p[1], $p[2] );
2089 return new $name( $p[0], $p[1], $p[2], $p[3] );
2091 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2093 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2095 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2100 * Aliases for modularized functions
2102 function wfGetHTTP( $url, $timeout = 'default' ) {
2103 return Http
::get( $url, $timeout );
2105 function wfIsLocalURL( $url ) {
2106 return Http
::isLocalURL( $url );
2110 * Initialise php session
2112 function wfSetupSession() {
2113 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2114 if( $wgSessionsInMemcached ) {
2115 require_once( 'MemcachedSessions.php' );
2116 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2117 # If it's left on 'user' or another setting from another
2118 # application, it will end up failing. Try to recover.
2119 ini_set ( 'session.save_handler', 'files' );
2121 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2122 session_cache_limiter( 'private, must-revalidate' );
2127 * Get an object from the precompiled serialized directory
2129 * @return mixed The variable on success, false on failure
2131 function wfGetPrecompiledData( $name ) {
2134 $file = "$IP/serialized/$name";
2135 if ( file_exists( $file ) ) {
2136 $blob = file_get_contents( $file );
2138 return unserialize( $blob );
2144 function wfGetCaller( $level = 2 ) {
2145 $backtrace = wfDebugBacktrace();
2146 if ( isset( $backtrace[$level] ) ) {
2147 if ( isset( $backtrace[$level]['class'] ) ) {
2148 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2150 $caller = $backtrace[$level]['function'];
2153 $caller = 'unknown';
2158 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2159 function wfGetAllCallers() {
2160 return implode('/', array_map(
2161 create_function('$frame','
2162 return isset( $frame["class"] )?
2163 $frame["class"]."::".$frame["function"]:
2166 array_reverse(wfDebugBacktrace())));
2172 function wfMemcKey( /*... */ ) {
2173 global $wgDBprefix, $wgDBname;
2174 $args = func_get_args();
2175 if ( $wgDBprefix ) {
2176 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2178 $key = $wgDBname . ':' . implode( ':', $args );
2184 * Get a cache key for a foreign DB
2186 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2187 $args = array_slice( func_get_args(), 2 );
2189 $key = "$db-$prefix:" . implode( ':', $args );
2191 $key = $db . ':' . implode( ':', $args );
2197 * Get an ASCII string identifying this wiki
2198 * This is used as a prefix in memcached keys
2200 function wfWikiID() {
2201 global $wgDBprefix, $wgDBname;
2202 if ( $wgDBprefix ) {
2203 return "$wgDBname-$wgDBprefix";
2210 * Get a Database object
2211 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2212 * master (for write queries), DB_SLAVE for potentially lagged
2213 * read queries, or an integer >= 0 for a particular server.
2215 * @param mixed $groups Query groups. An array of group names that this query
2216 * belongs to. May contain a single string if the query is only
2219 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2220 global $wgLoadBalancer;
2221 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );