3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
11 require_once dirname(__FILE__
) . '/LogPage.php';
12 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__
) . '/XmlFunctions.php';
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 );
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
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 ) );
44 return join( '', array_slice( $ar[0], $start ) );
49 if ( !function_exists( 'mb_strlen' ) ) {
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
53 * @param string $enc optional encoding; ignored
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
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];
73 if ( !function_exists( 'array_diff_key' ) ) {
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 ) {
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
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;
104 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
105 $cmp = strcmp( $valueA, $valueB );
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() {
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.
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, '.', '' );
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.
154 function wfUrlencode ( $s ) {
155 $s = urlencode( $s );
156 $s = preg_replace( '/%3[Aa]/', ':', $s );
157 $s = preg_replace( '/%2[Ff]/', '/', $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 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
180 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
184 if ( $wgDebugComments && !$logonly ) {
185 if ( !isset( $wgOut ) ) {
188 if ( !StubObject
::isRealObject( $wgOut ) ) {
196 $wgOut->debug( $text );
198 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
199 # Strip unprintables; they can switch terminal modes when binary data
200 # gets dumped, which is pretty annoying.
201 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
202 wfErrorLog( $text, $wgDebugLogFile );
207 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
208 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
210 * @param $logGroup String
211 * @param $text String
212 * @param $public Bool: whether to log the event in the public log if no private
213 * log file is specified, (default true)
215 function wfDebugLog( $logGroup, $text, $public = true ) {
216 global $wgDebugLogGroups;
217 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
218 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
219 $time = wfTimestamp( TS_DB
);
221 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
222 } else if ( $public === true ) {
223 wfDebug( $text, true );
228 * Log for database errors
229 * @param $text String: database error message.
231 function wfLogDBError( $text ) {
232 global $wgDBerrorLog, $wgDBname;
233 if ( $wgDBerrorLog ) {
234 $host = trim(`hostname`
);
235 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
236 wfErrorLog( $text, $wgDBerrorLog );
241 * Log to a file without getting "file size exceeded" signals
243 function wfErrorLog( $text, $file ) {
244 wfSuppressWarnings();
245 $exists = file_exists( $file );
246 $size = $exists ?
filesize( $file ) : false;
247 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
248 error_log( $text, 3, $file );
256 function wfLogProfilingData() {
257 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
258 global $wgProfiler, $wgUser;
259 if ( !isset( $wgProfiler ) )
263 $elapsed = $now - $wgRequestTime;
264 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
266 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
267 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
268 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
269 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
270 if( !empty( $_SERVER['HTTP_FROM'] ) )
271 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
273 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
274 // Don't unstub $wgUser at this late stage just for statistics purposes
275 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
277 $log = sprintf( "%s\t%04.3f\t%s\n",
278 gmdate( 'YmdHis' ), $elapsed,
279 urldecode( $wgRequest->getRequestURL() . $forward ) );
280 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
281 wfErrorLog( $log . $prof, $wgDebugLogFile );
286 * Check if the wiki read-only lock file is present. This can be used to lock
287 * off editing functions, but doesn't guarantee that the database will not be
291 function wfReadOnly() {
292 global $wgReadOnlyFile, $wgReadOnly;
294 if ( !is_null( $wgReadOnly ) ) {
295 return (bool)$wgReadOnly;
297 if ( '' == $wgReadOnlyFile ) {
300 // Set $wgReadOnly for faster access next time
301 if ( is_file( $wgReadOnlyFile ) ) {
302 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
306 return (bool)$wgReadOnly;
309 function wfReadOnlyReason() {
316 * Get a message from anywhere, for the current user language.
318 * Use wfMsgForContent() instead if the message should NOT
319 * change depending on the user preferences.
321 * @param $key String: lookup key for the message, usually
322 * defined in languages/Language.php
324 * This function also takes extra optional parameters (not
325 * shown in the function definition), which can by used to
326 * insert variable text into the predefined message.
328 function wfMsg( $key ) {
329 $args = func_get_args();
330 array_shift( $args );
331 return wfMsgReal( $key, $args, true );
335 * Same as above except doesn't transform the message
337 function wfMsgNoTrans( $key ) {
338 $args = func_get_args();
339 array_shift( $args );
340 return wfMsgReal( $key, $args, true, false, false );
344 * Get a message from anywhere, for the current global language
345 * set with $wgLanguageCode.
347 * Use this if the message should NOT change dependent on the
348 * language set in the user's preferences. This is the case for
349 * most text written into logs, as well as link targets (such as
350 * the name of the copyright policy page). Link titles, on the
351 * other hand, should be shown in the UI language.
353 * Note that MediaWiki allows users to change the user interface
354 * language in their preferences, but a single installation
355 * typically only contains content in one language.
357 * Be wary of this distinction: If you use wfMsg() where you should
358 * use wfMsgForContent(), a user of the software may have to
359 * customize over 70 messages in order to, e.g., fix a link in every
362 * @param $key String: lookup key for the message, usually
363 * defined in languages/Language.php
365 function wfMsgForContent( $key ) {
366 global $wgForceUIMsgAsContentMsg;
367 $args = func_get_args();
368 array_shift( $args );
370 if( is_array( $wgForceUIMsgAsContentMsg ) &&
371 in_array( $key, $wgForceUIMsgAsContentMsg ) )
373 return wfMsgReal( $key, $args, true, $forcontent );
377 * Same as above except doesn't transform the message
379 function wfMsgForContentNoTrans( $key ) {
380 global $wgForceUIMsgAsContentMsg;
381 $args = func_get_args();
382 array_shift( $args );
384 if( is_array( $wgForceUIMsgAsContentMsg ) &&
385 in_array( $key, $wgForceUIMsgAsContentMsg ) )
387 return wfMsgReal( $key, $args, true, $forcontent, false );
391 * Get a message from the language file, for the UI elements
393 function wfMsgNoDB( $key ) {
394 $args = func_get_args();
395 array_shift( $args );
396 return wfMsgReal( $key, $args, false );
400 * Get a message from the language file, for the content
402 function wfMsgNoDBForContent( $key ) {
403 global $wgForceUIMsgAsContentMsg;
404 $args = func_get_args();
405 array_shift( $args );
407 if( is_array( $wgForceUIMsgAsContentMsg ) &&
408 in_array( $key, $wgForceUIMsgAsContentMsg ) )
410 return wfMsgReal( $key, $args, false, $forcontent );
415 * Really get a message
416 * @param $key String: key to get.
418 * @param $useDB Boolean
419 * @param $transform Boolean: Whether or not to transform the message.
420 * @param $forContent Boolean
421 * @return String: the requested message.
423 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
424 wfProfileIn( __METHOD__
);
425 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
426 $message = wfMsgReplaceArgs( $message, $args );
427 wfProfileOut( __METHOD__
);
432 * This function provides the message source for messages to be edited which are *not* stored in the database.
433 * @param $key String:
435 function wfMsgWeirdKey ( $key ) {
436 $source = wfMsgGetKey( $key, false, true, false );
437 if ( wfEmptyMsg( $key, $source ) )
444 * Fetch a message string value, but don't replace any keys yet.
447 * @param string $langcode Code of the language to get the message for, or
448 * behaves as a content language switch if it is a
450 * @param bool $fallback Whether or not to fallback to a different language if
451 * it is not found in the selected one.
455 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true, $fallback = true ) {
456 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
458 # If $wgMessageCache isn't initialised yet, try to return something sensible.
459 if( is_object( $wgMessageCache ) ) {
460 $message = $wgMessageCache->get( $key, $useDB, $langCode, false, $fallback );
462 $message = $wgMessageCache->transform( $message );
465 if( $langCode === true ) {
466 $lang = &$wgContLang;
467 } elseif( $langCode === false ) {
470 $validCodes = array_keys( Language
::getLanguageNames() );
471 if( in_array( $langCode, $validCodes ) ) {
472 # $langcode corresponds to a valid language.
473 $lang = Language
::factory( $langCode );
475 # $langcode is a string, but not a valid language code; use content language.
476 $lang =& $wgContLang;
477 wfDebug( 'Invalid language code passed to wfMsgGetKey, falling back to content language.' );
481 # MessageCache::get() does this already, Language::getMessage() doesn't
482 # ISSUE: Should we try to handle "message/lang" here too?
483 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
485 if( is_object( $lang ) ) {
486 $message = $lang->getMessage( $key );
496 * Replace message parameter keys on the given formatted output.
498 * @param string $message
503 function wfMsgReplaceArgs( $message, $args ) {
504 # Fix windows line-endings
505 # Some messages are split with explode("\n", $msg)
506 $message = str_replace( "\r", '', $message );
509 if ( count( $args ) ) {
510 if ( is_array( $args[0] ) ) {
511 $args = array_values( $args[0] );
513 $replacementKeys = array();
514 foreach( $args as $n => $param ) {
515 $replacementKeys['$' . ($n +
1)] = $param;
517 $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 through htmlspecialchars
565 * <i>escapenoentities</i>: same, but allows entity references like through
566 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
567 * <i>parsemag</i>: transform the message using magic phrases
568 * <i>content</i>: fetch message for content language instead of interface
569 * <i>nofallback</i>: do not fallback to a different language
570 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
571 * with parser, parseinline and parsemag is undefined.
572 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
574 function wfMsgExt( $key, $options ) {
575 global $wgOut, $wgParser;
577 $args = func_get_args();
578 array_shift( $args );
579 array_shift( $args );
581 if( !is_array($options) ) {
582 $options = array($options);
585 if( in_array('content', $options) ) {
588 } elseif( array_key_exists('language', $options) ) {
590 $langCode = $options['language'];
591 $validCodes = array_keys( Language
::getLanguageNames() );
592 if( !in_array($options['language'], $validCodes) ) {
600 $fallback = !in_array('nofallback', $options);
602 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false, /*Fallback*/$fallback );
604 if( !in_array('replaceafter', $options) ) {
605 $string = wfMsgReplaceArgs( $string, $args );
608 if( in_array('parse', $options) ) {
609 $string = $wgOut->parse( $string, true, !$forContent );
610 } elseif ( in_array('parseinline', $options) ) {
611 $string = $wgOut->parse( $string, true, !$forContent );
613 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
616 } elseif ( in_array('parsemag', $options) ) {
617 global $wgMessageCache;
618 if ( isset( $wgMessageCache ) ) {
619 $string = $wgMessageCache->transform( $string, !$forContent );
623 if ( in_array('escape', $options) ) {
624 $string = htmlspecialchars ( $string );
625 } elseif ( in_array( 'escapenoentities', $options ) ) {
626 $string = htmlspecialchars( $string );
627 $string = str_replace( '&', '&', $string );
628 $string = Sanitizer
::normalizeCharReferences( $string );
631 if( in_array('replaceafter', $options) ) {
632 $string = wfMsgReplaceArgs( $string, $args );
640 * Just like exit() but makes a note of it.
641 * Commits open transactions except if the error parameter is set
643 * @deprecated Please return control to the caller or throw an exception
645 function wfAbruptExit( $error = false ){
646 static $called = false;
652 $bt = wfDebugBacktrace();
654 for($i = 0; $i < count($bt) ; $i++
){
655 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
656 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
657 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
660 wfDebug('WARNING: Abrupt exit\n');
663 wfLogProfilingData();
666 wfGetLB()->closeAll();
672 * @deprecated Please return control the caller or throw an exception
674 function wfErrorExit() {
675 wfAbruptExit( true );
679 * Print a simple message and die, returning nonzero to the shell if any.
680 * Plain die() fails to return nonzero to the shell if you pass a string.
683 function wfDie( $msg='' ) {
689 * Throw a debugging exception. This function previously once exited the process,
690 * but now throws an exception instead, with similar results.
692 * @param string $msg Message shown when dieing.
694 function wfDebugDieBacktrace( $msg = '' ) {
695 throw new MWException( $msg );
699 * Fetch server name for use in error reporting etc.
700 * Use real server name if available, so we know which machine
701 * in a server farm generated the current page.
704 function wfHostname() {
705 if ( function_exists( 'posix_uname' ) ) {
706 // This function not present on Windows
707 $uname = @posix_uname
();
711 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
712 return $uname['nodename'];
714 # This may be a virtual server.
715 return $_SERVER['SERVER_NAME'];
720 * Returns a HTML comment with the elapsed time since request.
721 * This method has no side effects.
724 function wfReportTime() {
725 global $wgRequestTime, $wgShowHostnames;
728 $elapsed = $now - $wgRequestTime;
730 return $wgShowHostnames
731 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
732 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
736 * Safety wrapper for debug_backtrace().
738 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
739 * murky circumstances, which may be triggered in part by stub objects
740 * or other fancy talkin'.
742 * Will return an empty array if Zend Optimizer is detected, otherwise
743 * the output from debug_backtrace() (trimmed).
745 * @return array of backtrace information
747 function wfDebugBacktrace() {
748 if( extension_loaded( 'Zend Optimizer' ) ) {
749 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
752 return array_slice( debug_backtrace(), 1 );
756 function wfBacktrace() {
757 global $wgCommandLineMode;
759 if ( $wgCommandLineMode ) {
764 $backtrace = wfDebugBacktrace();
765 foreach( $backtrace as $call ) {
766 if( isset( $call['file'] ) ) {
767 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
768 $file = $f[count($f)-1];
772 if( isset( $call['line'] ) ) {
773 $line = $call['line'];
777 if ( $wgCommandLineMode ) {
778 $msg .= "$file line $line calls ";
780 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
782 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
783 $msg .= $call['function'] . '()';
785 if ( $wgCommandLineMode ) {
791 if ( $wgCommandLineMode ) {
801 /* Some generic result counters, pulled out of SearchEngine */
807 function wfShowingResults( $offset, $limit ) {
809 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
815 function wfShowingResultsNum( $offset, $limit, $num ) {
817 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
823 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
825 $fmtLimit = $wgLang->formatNum( $limit );
826 $prev = wfMsg( 'prevn', $fmtLimit );
827 $next = wfMsg( 'nextn', $fmtLimit );
829 if( is_object( $link ) ) {
832 $title = Title
::newFromText( $link );
833 if( is_null( $title ) ) {
838 if ( 0 != $offset ) {
839 $po = $offset - $limit;
840 if ( $po < 0 ) { $po = 0; }
841 $q = "limit={$limit}&offset={$po}";
842 if ( '' != $query ) { $q .= '&'.$query; }
843 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
844 } else { $plink = $prev; }
846 $no = $offset +
$limit;
847 $q = 'limit='.$limit.'&offset='.$no;
848 if ( '' != $query ) { $q .= '&'.$query; }
853 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
855 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
856 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
857 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
858 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
859 wfNumLink( $offset, 500, $title, $query );
861 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
867 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
869 if ( '' == $query ) { $q = ''; }
870 else { $q = $query.'&'; }
871 $q .= 'limit='.$limit.'&offset='.$offset;
873 $fmtLimit = $wgLang->formatNum( $limit );
874 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
880 * @todo FIXME: we may want to blacklist some broken browsers
882 * @return bool Whereas client accept gzip compression
884 function wfClientAcceptsGzip() {
887 # FIXME: we may want to blacklist some broken browsers
890 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
891 $_SERVER['HTTP_ACCEPT_ENCODING'],
893 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
894 wfDebug( " accepts gzip\n" );
902 * Obtain the offset and limit values from the request string;
903 * used in special pages
905 * @param $deflimit Default limit if none supplied
906 * @param $optionname Name of a user preference to check against
910 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
912 return $wgRequest->getLimitOffset( $deflimit, $optionname );
916 * Escapes the given text so that it may be output using addWikiText()
917 * without any linking, formatting, etc. making its way through. This
918 * is achieved by substituting certain characters with HTML entities.
919 * As required by the callers, <nowiki> is not used. It currently does
920 * not filter out characters which have special meaning only at the
921 * start of a line, such as "*".
923 * @param string $text Text to be escaped
925 function wfEscapeWikiText( $text ) {
927 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
928 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
929 htmlspecialchars($text) );
936 function wfQuotedPrintable( $string, $charset = '' ) {
937 # Probably incomplete; see RFC 2045
938 if( empty( $charset ) ) {
939 global $wgInputEncoding;
940 $charset = $wgInputEncoding;
942 $charset = strtoupper( $charset );
943 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
945 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
946 $replace = $illegal . '\t ?_';
947 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
948 $out = "=?$charset?Q?";
949 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
960 return microtime(true);
964 * Sets dest to source and returns the original value of dest
965 * If source is NULL, it just returns the value, it doesn't set the variable
967 function wfSetVar( &$dest, $source ) {
969 if ( !is_null( $source ) ) {
976 * As for wfSetVar except setting a bit
978 function wfSetBit( &$dest, $bit, $state = true ) {
979 $temp = (bool)($dest & $bit );
980 if ( !is_null( $state ) ) {
991 * This function takes two arrays as input, and returns a CGI-style string, e.g.
992 * "days=7&limit=100". Options in the first array override options in the second.
993 * Options set to "" will not be output.
995 function wfArrayToCGI( $array1, $array2 = NULL )
997 if ( !is_null( $array2 ) ) {
998 $array1 = $array1 +
$array2;
1002 foreach ( $array1 as $key => $value ) {
1003 if ( '' !== $value ) {
1007 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
1014 * Append a query string to an existing URL, which may or may not already
1015 * have query string parameters already. If so, they will be combined.
1017 * @param string $url
1018 * @param string $query
1021 function wfAppendQuery( $url, $query ) {
1022 if( $query != '' ) {
1023 if( false === strpos( $url, '?' ) ) {
1034 * Expand a potentially local URL to a fully-qualified URL.
1035 * Assumes $wgServer is correct. :)
1036 * @param string $url, either fully-qualified or a local path + query
1037 * @return string Fully-qualified URL
1039 function wfExpandUrl( $url ) {
1040 if( substr( $url, 0, 1 ) == '/' ) {
1042 return $wgServer . $url;
1049 * This is obsolete, use SquidUpdate::purge()
1052 function wfPurgeSquidServers ($urlArr) {
1053 SquidUpdate
::purge( $urlArr );
1057 * Windows-compatible version of escapeshellarg()
1058 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1059 * function puts single quotes in regardless of OS
1061 function wfEscapeShellArg( ) {
1062 $args = func_get_args();
1065 foreach ( $args as $arg ) {
1072 if ( wfIsWindows() ) {
1073 // Escaping for an MSVC-style command line parser
1074 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1075 // Double the backslashes before any double quotes. Escape the double quotes.
1076 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1079 foreach ( $tokens as $token ) {
1081 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1087 // Double the backslashes before the end of the string, because
1088 // we will soon add a quote
1090 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1091 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1094 // Add surrounding quotes
1095 $retVal .= '"' . $arg . '"';
1097 $retVal .= escapeshellarg( $arg );
1104 * wfMerge attempts to merge differences between three texts.
1105 * Returns true for a clean merge and false for failure or a conflict.
1107 function wfMerge( $old, $mine, $yours, &$result ){
1110 # This check may also protect against code injection in
1111 # case of broken installations.
1112 if(! file_exists( $wgDiff3 ) ){
1113 wfDebug( "diff3 not found\n" );
1117 # Make temporary files
1119 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1120 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1121 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1123 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1124 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1125 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1127 # Check for a conflict
1128 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1129 wfEscapeShellArg( $mytextName ) . ' ' .
1130 wfEscapeShellArg( $oldtextName ) . ' ' .
1131 wfEscapeShellArg( $yourtextName );
1132 $handle = popen( $cmd, 'r' );
1134 if( fgets( $handle, 1024 ) ){
1142 $cmd = $wgDiff3 . ' -a -e --merge ' .
1143 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1144 $handle = popen( $cmd, 'r' );
1147 $data = fread( $handle, 8192 );
1148 if ( strlen( $data ) == 0 ) {
1154 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1156 if ( $result === '' && $old !== '' && $conflict == false ) {
1157 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1166 function wfVarDump( $var ) {
1168 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1169 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1172 $wgOut->addHTML( $s );
1177 * Provide a simple HTTP error.
1179 function wfHttpError( $code, $label, $desc ) {
1182 header( "HTTP/1.0 $code $label" );
1183 header( "Status: $code $label" );
1184 $wgOut->sendCacheControl();
1186 header( 'Content-type: text/html; charset=utf-8' );
1187 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1188 "<html><head><title>" .
1189 htmlspecialchars( $label ) .
1190 "</title></head><body><h1>" .
1191 htmlspecialchars( $label ) .
1193 nl2br( htmlspecialchars( $desc ) ) .
1194 "</p></body></html>\n";
1198 * Clear away any user-level output buffers, discarding contents.
1200 * Suitable for 'starting afresh', for instance when streaming
1201 * relatively large amounts of data without buffering, or wanting to
1202 * output image files without ob_gzhandler's compression.
1204 * The optional $resetGzipEncoding parameter controls suppression of
1205 * the Content-Encoding header sent by ob_gzhandler; by default it
1206 * is left. See comments for wfClearOutputBuffers() for why it would
1209 * Note that some PHP configuration options may add output buffer
1210 * layers which cannot be removed; these are left in place.
1212 * @param bool $resetGzipEncoding
1214 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1215 if( $resetGzipEncoding ) {
1216 // Suppress Content-Encoding and Content-Length
1217 // headers from 1.10+s wfOutputHandler
1218 global $wgDisableOutputCompression;
1219 $wgDisableOutputCompression = true;
1221 while( $status = ob_get_status() ) {
1222 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1223 // Probably from zlib.output_compression or other
1224 // PHP-internal setting which can't be removed.
1226 // Give up, and hope the result doesn't break
1230 if( !ob_end_clean() ) {
1231 // Could not remove output buffer handler; abort now
1232 // to avoid getting in some kind of infinite loop.
1235 if( $resetGzipEncoding ) {
1236 if( $status['name'] == 'ob_gzhandler' ) {
1237 // Reset the 'Content-Encoding' field set by this handler
1238 // so we can start fresh.
1239 header( 'Content-Encoding:' );
1246 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1248 * Clear away output buffers, but keep the Content-Encoding header
1249 * produced by ob_gzhandler, if any.
1251 * This should be used for HTTP 304 responses, where you need to
1252 * preserve the Content-Encoding header of the real result, but
1253 * also need to suppress the output of ob_gzhandler to keep to spec
1254 * and avoid breaking Firefox in rare cases where the headers and
1255 * body are broken over two packets.
1257 function wfClearOutputBuffers() {
1258 wfResetOutputBuffers( false );
1262 * Converts an Accept-* header into an array mapping string values to quality
1265 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1266 # No arg means accept anything (per HTTP spec)
1268 return array( $def => 1 );
1273 $parts = explode( ',', $accept );
1275 foreach( $parts as $part ) {
1276 # FIXME: doesn't deal with params like 'text/html; level=1'
1277 @list
( $value, $qpart ) = explode( ';', $part );
1279 if( !isset( $qpart ) ) {
1281 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1282 $prefs[$value] = $match[1];
1290 * Checks if a given MIME type matches any of the keys in the given
1291 * array. Basic wildcards are accepted in the array keys.
1293 * Returns the matching MIME type (or wildcard) if a match, otherwise
1296 * @param string $type
1297 * @param array $avail
1301 function mimeTypeMatch( $type, $avail ) {
1302 if( array_key_exists($type, $avail) ) {
1305 $parts = explode( '/', $type );
1306 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1307 return $parts[0] . '/*';
1308 } elseif( array_key_exists( '*/*', $avail ) ) {
1317 * Returns the 'best' match between a client's requested internet media types
1318 * and the server's list of available types. Each list should be an associative
1319 * array of type to preference (preference is a float between 0.0 and 1.0).
1320 * Wildcards in the types are acceptable.
1322 * @param array $cprefs Client's acceptable type list
1323 * @param array $sprefs Server's offered types
1326 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1327 * XXX: generalize to negotiate other stuff
1329 function wfNegotiateType( $cprefs, $sprefs ) {
1332 foreach( array_keys($sprefs) as $type ) {
1333 $parts = explode( '/', $type );
1334 if( $parts[1] != '*' ) {
1335 $ckey = mimeTypeMatch( $type, $cprefs );
1337 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1342 foreach( array_keys( $cprefs ) as $type ) {
1343 $parts = explode( '/', $type );
1344 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1345 $skey = mimeTypeMatch( $type, $sprefs );
1347 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1355 foreach( array_keys( $combine ) as $type ) {
1356 if( $combine[$type] > $bestq ) {
1358 $bestq = $combine[$type];
1367 * Returns an array where the values in the first array are replaced by the
1368 * values in the second array with the corresponding keys
1372 function wfArrayLookup( $a, $b ) {
1373 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1377 * Convenience function; returns MediaWiki timestamp for the present time.
1380 function wfTimestampNow() {
1382 return wfTimestamp( TS_MW
, time() );
1386 * Reference-counted warning suppression
1388 function wfSuppressWarnings( $end = false ) {
1389 static $suppressCount = 0;
1390 static $originalLevel = false;
1393 if ( $suppressCount ) {
1395 if ( !$suppressCount ) {
1396 error_reporting( $originalLevel );
1400 if ( !$suppressCount ) {
1401 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1408 * Restore error level to previous value
1410 function wfRestoreWarnings() {
1411 wfSuppressWarnings( true );
1414 # Autodetect, convert and provide timestamps of various types
1417 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1419 define('TS_UNIX', 0);
1422 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1427 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1432 * RFC 2822 format, for E-mail and HTTP headers
1434 define('TS_RFC2822', 3);
1437 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1439 * This is used by Special:Export
1441 define('TS_ISO_8601', 4);
1444 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1446 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1447 * DateTime tag and page 36 for the DateTimeOriginal and
1448 * DateTimeDigitized tags.
1450 define('TS_EXIF', 5);
1453 * Oracle format time.
1455 define('TS_ORACLE', 6);
1458 * Postgres format time.
1460 define('TS_POSTGRES', 7);
1463 * @param mixed $outputtype A timestamp in one of the supported formats, the
1464 * function will autodetect which format is supplied
1465 * and act accordingly.
1466 * @return string Time in the format specified in $outputtype
1468 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1473 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1475 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1476 (int)$da[2],(int)$da[3],(int)$da[1]);
1477 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1479 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1480 (int)$da[2],(int)$da[3],(int)$da[1]);
1481 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1483 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1484 (int)$da[2],(int)$da[3],(int)$da[1]);
1485 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1488 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1490 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1491 str_replace("+00:00", "UTC", $ts)));
1492 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1494 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1495 (int)$da[2],(int)$da[3],(int)$da[1]);
1496 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1498 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1499 (int)$da[2],(int)$da[3],(int)$da[1]);
1500 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1502 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1503 (int)$da[2],(int)$da[3],(int)$da[1]);
1505 # Bogus value; fall back to the epoch...
1506 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1511 switch($outputtype) {
1515 return gmdate( 'YmdHis', $uts );
1517 return gmdate( 'Y-m-d H:i:s', $uts );
1519 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1520 // This shouldn't ever be used, but is included for completeness
1522 return gmdate( 'Y:m:d H:i:s', $uts );
1524 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1526 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1528 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1530 throw new MWException( 'wfTimestamp() called with illegal output type.');
1535 * Return a formatted timestamp, or null if input is null.
1536 * For dealing with nullable timestamp columns in the database.
1537 * @param int $outputtype
1541 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1542 if( is_null( $ts ) ) {
1545 return wfTimestamp( $outputtype, $ts );
1550 * Check if the operating system is Windows
1552 * @return bool True if it's Windows, False otherwise.
1554 function wfIsWindows() {
1555 if (substr(php_uname(), 0, 7) == 'Windows') {
1563 * Swap two variables
1565 function swap( &$x, &$y ) {
1571 function wfGetCachedNotice( $name ) {
1572 global $wgOut, $parserMemc;
1573 $fname = 'wfGetCachedNotice';
1574 wfProfileIn( $fname );
1578 if( $name === 'default' ) {
1580 global $wgSiteNotice;
1581 $notice = $wgSiteNotice;
1582 if( empty( $notice ) ) {
1583 wfProfileOut( $fname );
1587 $notice = wfMsgForContentNoTrans( $name );
1588 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1589 wfProfileOut( $fname );
1594 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1595 if( is_array( $cachedNotice ) ) {
1596 if( md5( $notice ) == $cachedNotice['hash'] ) {
1597 $notice = $cachedNotice['html'];
1606 if( is_object( $wgOut ) ) {
1607 $parsed = $wgOut->parse( $notice );
1608 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1611 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1616 wfProfileOut( $fname );
1620 function wfGetNamespaceNotice() {
1624 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1627 $fname = 'wfGetNamespaceNotice';
1628 wfProfileIn( $fname );
1630 $key = "namespacenotice-" . $wgTitle->getNsText();
1631 $namespaceNotice = wfGetCachedNotice( $key );
1632 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1633 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1635 $namespaceNotice = "";
1638 wfProfileOut( $fname );
1639 return $namespaceNotice;
1642 function wfGetSiteNotice() {
1643 global $wgUser, $wgSiteNotice;
1644 $fname = 'wfGetSiteNotice';
1645 wfProfileIn( $fname );
1648 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1649 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1650 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1652 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1653 if( !$anonNotice ) {
1654 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1656 $siteNotice = $anonNotice;
1659 if( !$siteNotice ) {
1660 $siteNotice = wfGetCachedNotice( 'default' );
1664 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1665 wfProfileOut( $fname );
1670 * BC wrapper for MimeMagic::singleton()
1673 function &wfGetMimeMagic() {
1674 return MimeMagic
::singleton();
1678 * Tries to get the system directory for temporary files.
1679 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1680 * and if none are set /tmp is returned as the generic Unix default.
1682 * NOTE: When possible, use the tempfile() function to create temporary
1683 * files to avoid race conditions on file creation, etc.
1687 function wfTempDir() {
1688 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1689 $tmp = getenv( $var );
1690 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1694 # Hope this is Unix of some kind!
1699 * Make directory, and make all parent directories if they don't exist
1701 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1702 if( strval( $fullDir ) === '' )
1704 if( file_exists( $fullDir ) )
1706 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1710 * Increment a statistics counter
1712 function wfIncrStats( $key ) {
1713 global $wgStatsMethod;
1715 if( $wgStatsMethod == 'udp' ) {
1716 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1719 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1720 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1721 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1723 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1724 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1725 } elseif( $wgStatsMethod == 'cache' ) {
1727 $key = wfMemcKey( 'stats', $key );
1728 if ( is_null( $wgMemc->incr( $key ) ) ) {
1729 $wgMemc->add( $key, 1 );
1737 * @param mixed $nr The number to format
1738 * @param int $acc The number of digits after the decimal point, default 2
1739 * @param bool $round Whether or not to round the value, default true
1742 function wfPercent( $nr, $acc = 2, $round = true ) {
1743 $ret = sprintf( "%.${acc}f", $nr );
1744 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1748 * Encrypt a username/password.
1750 * @param string $userid ID of the user
1751 * @param string $password Password of the user
1752 * @return string Hashed password
1754 function wfEncryptPassword( $userid, $password ) {
1755 global $wgPasswordSalt;
1756 $p = md5( $password);
1759 return md5( "{$userid}-{$p}" );
1765 * Appends to second array if $value differs from that in $default
1767 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1768 if ( is_null( $changed ) ) {
1769 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1771 if ( $default[$key] !== $value ) {
1772 $changed[$key] = $value;
1777 * Since wfMsg() and co suck, they don't return false if the message key they
1778 * looked up didn't exist but a XHTML string, this function checks for the
1779 * nonexistance of messages by looking at wfMsg() output
1781 * @param $msg The message key looked up
1782 * @param $wfMsgOut The output of wfMsg*()
1785 function wfEmptyMsg( $msg, $wfMsgOut ) {
1786 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1790 * Find out whether or not a mixed variable exists in a string
1792 * @param mixed needle
1793 * @param string haystack
1796 function in_string( $needle, $str ) {
1797 return strpos( $str, $needle ) !== false;
1800 function wfSpecialList( $page, $details ) {
1802 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1803 return $page . $details;
1807 * Returns a regular expression of url protocols
1811 function wfUrlProtocols() {
1812 global $wgUrlProtocols;
1814 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1815 // with LocalSettings files from 1.5
1816 if ( is_array( $wgUrlProtocols ) ) {
1817 $protocols = array();
1818 foreach ($wgUrlProtocols as $protocol)
1819 $protocols[] = preg_quote( $protocol, '/' );
1821 return implode( '|', $protocols );
1823 return $wgUrlProtocols;
1828 * Safety wrapper around ini_get() for boolean settings.
1829 * The values returned from ini_get() are pre-normalized for settings
1830 * set via php.ini or php_flag/php_admin_flag... but *not*
1831 * for those set via php_value/php_admin_value.
1833 * It's fairly common for people to use php_value instead of php_flag,
1834 * which can leave you with an 'off' setting giving a false positive
1835 * for code that just takes the ini_get() return value as a boolean.
1837 * To make things extra interesting, setting via php_value accepts
1838 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1839 * Unrecognized values go false... again opposite PHP's own coercion
1840 * from string to bool.
1842 * Luckily, 'properly' set settings will always come back as '0' or '1',
1843 * so we only have to worry about them and the 'improper' settings.
1845 * I frickin' hate PHP... :P
1847 * @param string $setting
1850 function wfIniGetBool( $setting ) {
1851 $val = ini_get( $setting );
1852 // 'on' and 'true' can't have whitespace around them, but '1' can.
1853 return strtolower( $val ) == 'on'
1854 ||
strtolower( $val ) == 'true'
1855 ||
strtolower( $val ) == 'yes'
1856 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1860 * Execute a shell command, with time and memory limits mirrored from the PHP
1861 * configuration if supported.
1862 * @param $cmd Command line, properly escaped for shell.
1863 * @param &$retval optional, will receive the program's exit code.
1864 * (non-zero is usually failure)
1865 * @return collected stdout as a string (trailing newlines stripped)
1867 function wfShellExec( $cmd, &$retval=null ) {
1868 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1870 if( wfIniGetBool( 'safe_mode' ) ) {
1871 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1873 return "Unable to run external programs in safe mode.";
1876 if ( php_uname( 's' ) == 'Linux' ) {
1877 $time = intval( ini_get( 'max_execution_time' ) );
1878 $mem = intval( $wgMaxShellMemory );
1879 $filesize = intval( $wgMaxShellFileSize );
1881 if ( $time > 0 && $mem > 0 ) {
1882 $script = "$IP/bin/ulimit4.sh";
1883 if ( is_executable( $script ) ) {
1884 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1887 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1888 # This is a hack to work around PHP's flawed invocation of cmd.exe
1889 # http://news.php.net/php.internals/21796
1890 $cmd = '"' . $cmd . '"';
1892 wfDebug( "wfShellExec: $cmd\n" );
1894 $retval = 1; // error by default?
1896 passthru( $cmd, $retval );
1897 $output = ob_get_contents();
1904 * This function works like "use VERSION" in Perl, the program will die with a
1905 * backtrace if the current version of PHP is less than the version provided
1907 * This is useful for extensions which due to their nature are not kept in sync
1908 * with releases, and might depend on other versions of PHP than the main code
1910 * Note: PHP might die due to parsing errors in some cases before it ever
1911 * manages to call this function, such is life
1913 * @see perldoc -f use
1915 * @param mixed $version The version to check, can be a string, an integer, or
1918 function wfUsePHP( $req_ver ) {
1919 $php_ver = PHP_VERSION
;
1921 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1922 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1926 * This function works like "use VERSION" in Perl except it checks the version
1927 * of MediaWiki, the program will die with a backtrace if the current version
1928 * of MediaWiki is less than the version provided.
1930 * This is useful for extensions which due to their nature are not kept in sync
1933 * @see perldoc -f use
1935 * @param mixed $version The version to check, can be a string, an integer, or
1938 function wfUseMW( $req_ver ) {
1941 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1942 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1946 * @deprecated use StringUtils::escapeRegexReplacement
1948 function wfRegexReplacement( $string ) {
1949 return StringUtils
::escapeRegexReplacement( $string );
1953 * Return the final portion of a pathname.
1954 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1955 * http://bugs.php.net/bug.php?id=33898
1957 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1958 * We'll consider it so always, as we don't want \s in our Unix paths either.
1960 * @param string $path
1961 * @param string $suffix to remove if present
1964 function wfBaseName( $path, $suffix='' ) {
1965 $encSuffix = ($suffix == '')
1967 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1969 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1977 * Generate a relative path name to the given file.
1978 * May explode on non-matching case-insensitive paths,
1979 * funky symlinks, etc.
1981 * @param string $path Absolute destination path including target filename
1982 * @param string $from Absolute source path, directory only
1985 function wfRelativePath( $path, $from ) {
1986 // Normalize mixed input on Windows...
1987 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1988 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1990 // Trim trailing slashes -- fix for drive root
1991 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
1992 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
1994 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1995 $against = explode( DIRECTORY_SEPARATOR
, $from );
1997 if( $pieces[0] !== $against[0] ) {
1998 // Non-matching Windows drive letters?
1999 // Return a full path.
2003 // Trim off common prefix
2004 while( count( $pieces ) && count( $against )
2005 && $pieces[0] == $against[0] ) {
2006 array_shift( $pieces );
2007 array_shift( $against );
2010 // relative dots to bump us to the parent
2011 while( count( $against ) ) {
2012 array_unshift( $pieces, '..' );
2013 array_shift( $against );
2016 array_push( $pieces, wfBaseName( $path ) );
2018 return implode( DIRECTORY_SEPARATOR
, $pieces );
2022 * array_merge() does awful things with "numeric" indexes, including
2023 * string indexes when happen to look like integers. When we want
2024 * to merge arrays with arbitrary string indexes, we don't want our
2025 * arrays to be randomly corrupted just because some of them consist
2028 * Fuck you, PHP. Fuck you in the ear!
2030 * @param array $array1, [$array2, [...]]
2033 function wfArrayMerge( $array1/* ... */ ) {
2035 for( $i = 1; $i < func_num_args(); $i++
) {
2036 foreach( func_get_arg( $i ) as $key => $value ) {
2037 $out[$key] = $value;
2044 * Make a URL index, appropriate for the el_index field of externallinks.
2046 function wfMakeUrlIndex( $url ) {
2047 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2048 wfSuppressWarnings();
2049 $bits = parse_url( $url );
2050 wfRestoreWarnings();
2054 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2056 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2058 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2060 // parse_url detects for news: and mailto: the host part of an url as path
2061 // We have to correct this wrong detection
2062 if ( isset ( $bits['path'] ) ) {
2063 $bits['host'] = $bits['path'];
2070 // Reverse the labels in the hostname, convert to lower case
2071 // For emails reverse domainpart only
2072 if ( $bits['scheme'] == 'mailto' ) {
2073 $mailparts = explode( '@', $bits['host'], 2 );
2074 if ( count($mailparts) === 2 ) {
2075 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2077 // No domain specified, don't mangle it
2080 $reversedHost = $domainpart . '@' . $mailparts[0];
2082 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2084 // Add an extra dot to the end
2085 // Why? Is it in wrong place in mailto links?
2086 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2087 $reversedHost .= '.';
2089 // Reconstruct the pseudo-URL
2090 $prot = $bits['scheme'];
2091 $index = "$prot$delimiter$reversedHost";
2092 // Leave out user and password. Add the port, path, query and fragment
2093 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2094 if ( isset( $bits['path'] ) ) {
2095 $index .= $bits['path'];
2099 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2100 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2105 * Do any deferred updates and clear the list
2106 * TODO: This could be in Wiki.php if that class made any sense at all
2108 function wfDoUpdates()
2110 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2111 foreach ( $wgDeferredUpdateList as $update ) {
2112 $update->doUpdate();
2114 foreach ( $wgPostCommitUpdateList as $update ) {
2115 $update->doUpdate();
2117 $wgDeferredUpdateList = array();
2118 $wgPostCommitUpdateList = array();
2122 * @deprecated use StringUtils::explodeMarkup
2124 function wfExplodeMarkup( $separator, $text ) {
2125 return StringUtils
::explodeMarkup( $separator, $text );
2129 * Convert an arbitrarily-long digit string from one numeric base
2130 * to another, optionally zero-padding to a minimum column width.
2132 * Supports base 2 through 36; digit values 10-36 are represented
2133 * as lowercase letters a-z. Input is case-insensitive.
2135 * @param $input string of digits
2136 * @param $sourceBase int 2-36
2137 * @param $destBase int 2-36
2138 * @param $pad int 1 or greater
2139 * @param $lowercase bool
2140 * @return string or false on invalid input
2142 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2143 $input = strval( $input );
2144 if( $sourceBase < 2 ||
2149 $sourceBase != intval( $sourceBase ) ||
2150 $destBase != intval( $destBase ) ||
2151 $pad != intval( $pad ) ||
2152 !is_string( $input ) ||
2156 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2157 $inDigits = array();
2160 // Decode and validate input string
2161 $input = strtolower( $input );
2162 for( $i = 0; $i < strlen( $input ); $i++
) {
2163 $n = strpos( $digitChars, $input{$i} );
2164 if( $n === false ||
$n > $sourceBase ) {
2170 // Iterate over the input, modulo-ing out an output digit
2171 // at a time until input is gone.
2172 while( count( $inDigits ) ) {
2174 $workDigits = array();
2177 foreach( $inDigits as $digit ) {
2178 $work *= $sourceBase;
2181 if( $work < $destBase ) {
2182 // Gonna need to pull another digit.
2183 if( count( $workDigits ) ) {
2184 // Avoid zero-padding; this lets us find
2185 // the end of the input very easily when
2186 // length drops to zero.
2190 // Finally! Actual division!
2191 $workDigits[] = intval( $work / $destBase );
2193 // Isn't it annoying that most programming languages
2194 // don't have a single divide-and-remainder operator,
2195 // even though the CPU implements it that way?
2196 $work = $work %
$destBase;
2200 // All that division leaves us with a remainder,
2201 // which is conveniently our next output digit.
2202 $outChars .= $digitChars[$work];
2205 $inDigits = $workDigits;
2208 while( strlen( $outChars ) < $pad ) {
2212 return strrev( $outChars );
2216 * Create an object with a given name and an array of construct parameters
2217 * @param string $name
2218 * @param array $p parameters
2220 function wfCreateObject( $name, $p ){
2221 $p = array_values( $p );
2222 switch ( count( $p ) ) {
2226 return new $name( $p[0] );
2228 return new $name( $p[0], $p[1] );
2230 return new $name( $p[0], $p[1], $p[2] );
2232 return new $name( $p[0], $p[1], $p[2], $p[3] );
2234 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2236 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2238 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2243 * Aliases for modularized functions
2245 function wfGetHTTP( $url, $timeout = 'default' ) {
2246 return Http
::get( $url, $timeout );
2248 function wfIsLocalURL( $url ) {
2249 return Http
::isLocalURL( $url );
2253 * Initialise php session
2255 function wfSetupSession() {
2256 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2257 if( $wgSessionsInMemcached ) {
2258 require_once( 'MemcachedSessions.php' );
2259 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2260 # If it's left on 'user' or another setting from another
2261 # application, it will end up failing. Try to recover.
2262 ini_set ( 'session.save_handler', 'files' );
2264 $httpOnlySafe = version_compare("5.2", PHP_VERSION
, "<");
2265 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2266 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2268 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2269 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2271 session_cache_limiter( 'private, must-revalidate' );
2272 wfSuppressWarnings();
2274 wfRestoreWarnings();
2278 * Get an object from the precompiled serialized directory
2280 * @return mixed The variable on success, false on failure
2282 function wfGetPrecompiledData( $name ) {
2285 $file = "$IP/serialized/$name";
2286 if ( file_exists( $file ) ) {
2287 $blob = file_get_contents( $file );
2289 return unserialize( $blob );
2295 function wfGetCaller( $level = 2 ) {
2296 $backtrace = wfDebugBacktrace();
2297 if ( isset( $backtrace[$level] ) ) {
2298 return wfFormatStackFrame($backtrace[$level]);
2300 $caller = 'unknown';
2305 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2306 function wfGetAllCallers() {
2307 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2310 /** Return a string representation of frame */
2311 function wfFormatStackFrame($frame) {
2312 return isset( $frame["class"] )?
2313 $frame["class"]."::".$frame["function"]:
2320 function wfMemcKey( /*... */ ) {
2321 global $wgDBprefix, $wgDBname;
2322 $args = func_get_args();
2323 if ( $wgDBprefix ) {
2324 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2326 $key = $wgDBname . ':' . implode( ':', $args );
2332 * Get a cache key for a foreign DB
2334 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2335 $args = array_slice( func_get_args(), 2 );
2337 $key = "$db-$prefix:" . implode( ':', $args );
2339 $key = $db . ':' . implode( ':', $args );
2345 * Get an ASCII string identifying this wiki
2346 * This is used as a prefix in memcached keys
2348 function wfWikiID() {
2349 global $wgDBprefix, $wgDBname;
2350 if ( $wgDBprefix ) {
2351 return "$wgDBname-$wgDBprefix";
2358 * Split a wiki ID into DB name and table prefix
2360 function wfSplitWikiID( $wiki ) {
2361 $bits = explode( '-', $wiki, 2 );
2362 if ( count( $bits ) < 2 ) {
2369 * Get a Database object
2370 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2371 * master (for write queries), DB_SLAVE for potentially lagged
2372 * read queries, or an integer >= 0 for a particular server.
2374 * @param mixed $groups Query groups. An array of group names that this query
2375 * belongs to. May contain a single string if the query is only
2378 * @param string $wiki The wiki ID, or false for the current wiki
2380 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2381 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2385 * Get a load balancer object.
2387 * @param array $groups List of query groups
2388 * @param string $wiki Wiki ID, or false for the current wiki
2389 * @return LoadBalancer
2391 function wfGetLB( $wiki = false ) {
2392 return wfGetLBFactory()->getMainLB( $wiki );
2396 * Get the load balancer factory object
2398 function &wfGetLBFactory() {
2399 return LBFactory
::singleton();
2404 * Shortcut for RepoGroup::singleton()->findFile()
2405 * @param mixed $title Title object or string. May be interwiki.
2406 * @param mixed $time Requested time for an archived image, or false for the
2407 * current version. An image object will be returned which
2408 * was created at the specified time.
2409 * @return File, or false if the file does not exist
2411 function wfFindFile( $title, $time = false ) {
2412 return RepoGroup
::singleton()->findFile( $title, $time );
2416 * Get an object referring to a locally registered file.
2417 * Returns a valid placeholder object if the file does not exist.
2419 function wfLocalFile( $title ) {
2420 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2424 * Should low-performance queries be disabled?
2428 function wfQueriesMustScale() {
2429 global $wgMiserMode;
2431 ||
( SiteStats
::pages() > 100000
2432 && SiteStats
::edits() > 1000000
2433 && SiteStats
::users() > 10000 );
2437 * Get the path to a specified script file, respecting file
2438 * extensions; this is a wrapper around $wgScriptExtension etc.
2440 * @param string $script Script filename, sans extension
2443 function wfScript( $script = 'index' ) {
2444 global $wgScriptPath, $wgScriptExtension;
2445 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2449 * Convenience function converts boolean values into "true"
2450 * or "false" (string) values
2452 * @param bool $value
2455 function wfBoolToStr( $value ) {
2456 return $value ?
'true' : 'false';
2460 * Load an extension messages file
2462 * @param string $extensionName Name of extension to load messages from\for.
2463 * @param boolean $all Whether or not to load all languages.
2465 function wfLoadExtensionMessages( $extensionName, $all = false ) {
2466 global $wgExtensionMessagesFiles, $wgMessageCache;
2467 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2468 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $all );
2469 // Prevent double-loading if all the messages have been loaded.
2471 $wgExtensionMessagesFiles[$extensionName] = false;
2477 * Get a platform-independent path to the null file, e.g.
2482 function wfGetNull() {
2483 return wfIsWindows()
2489 * Displays a maxlag error
2491 * @param string $host Server that lags the most
2492 * @param int $lag Maxlag (actual)
2493 * @param int $maxLag Maxlag (requested)
2495 function wfMaxlagError( $host, $lag, $maxLag ) {
2496 global $wgShowHostnames;
2497 header( 'HTTP/1.1 503 Service Unavailable' );
2498 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2499 header( 'X-Database-Lag: ' . intval( $lag ) );
2500 header( 'Content-Type: text/plain' );
2501 if( $wgShowHostnames ) {
2502 echo "Waiting for $host: $lag seconds lagged\n";
2504 echo "Waiting for a database server: $lag seconds lagged\n";
2509 * Throws an E_USER_NOTICE saying that $function is deprecated
2510 * @param string $function
2513 function wfDeprecated( $function ) {
2514 $callers = wfDebugBacktrace();
2515 if( isset( $callers[2] ) ){
2516 $callerfunc = $callers[2];
2517 $callerfile = $callers[1];
2518 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2519 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2521 $file = '(internal function)';
2524 if( isset( $callerfunc['class'] ) )
2525 $func .= $callerfunc['class'] . '::';
2526 $func .= @$callerfunc['function'];
2527 trigger_error( "Use of $function is deprecated. Called from $func in $file", E_USER_NOTICE
);
2529 trigger_error( "Use of $function is deprecated.", E_USER_NOTICE
);
2534 * Sleep until the worst slave's replication lag is less than or equal to
2535 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2536 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2537 * a no-op if there are no slaves.
2539 * Every time the function has to wait for a slave, it will print a message to
2540 * that effect (and then sleep for a little while), so it's probably not best
2541 * to use this outside maintenance scripts in its present form.
2543 * @param int $maxLag
2546 function wfWaitForSlaves( $maxLag ) {
2549 list( $host, $lag ) = $lb->getMaxLag();
2550 while( $lag > $maxLag ) {
2551 $name = @gethostbyaddr
( $host );
2552 if( $name !== false ) {
2555 print "Waiting for $host (lagged $lag seconds)...\n";
2557 list( $host, $lag ) = $lb->getMaxLag();
2562 /** Generate a random 32-character hexadecimal token.
2563 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2565 function wfGenerateToken( $salt = '' ) {
2566 $salt = serialize($salt);
2568 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2572 * Generate a list of all available rights.
2573 * @todo Doesn't list any rights which aren't assigned to a group.
2575 function wfGetAvailableRights() {
2576 global $wgGroupPermissions;
2580 foreach( $wgGroupPermissions as $permissions ) {
2581 $rights = array_merge( array_keys($permissions),$rights );
2584 $rights = array_unique($rights);
2586 wfRunHooks( 'GetAvailableRights', array( &$rights ) );