* Output title before class in Linker::link() to match behavior of makeLink() and...
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
5 }
6
7 /**
8 * Global functions used everywhere
9 */
10
11 require_once dirname(__FILE__) . '/LogPage.php';
12 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__) . '/XmlFunctions.php';
14
15 /**
16 * Compatibility functions
17 *
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.
21 */
22 if( !function_exists('iconv') ) {
23 # iconv support is not in the default configuration and so may not be present.
24 # Assume will only ever use utf-8 and iso-8859-1.
25 # This will *not* work in all circumstances.
26 function iconv( $from, $to, $string ) {
27 if(strcasecmp( $from, $to ) == 0) return $string;
28 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
29 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
30 return $string;
31 }
32 }
33
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
37 $ar = array();
38 preg_match_all( '/./us', $str, $ar );
39
40 if( func_num_args() >= 3 ) {
41 $end = func_get_arg( 2 );
42 return join( '', array_slice( $ar[0], $start, $end ) );
43 } else {
44 return join( '', array_slice( $ar[0], $start ) );
45 }
46 }
47 }
48
49 if ( !function_exists( 'mb_strlen' ) ) {
50 /**
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
52 * @param string $str
53 * @param string $enc optional encoding; ignored
54 * @return int
55 */
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
58 $total = 0;
59
60 // Count ASCII bytes
61 for( $i = 0; $i < 0x80; $i++ ) {
62 $total += $counts[$i];
63 }
64
65 // Count multibyte sequence heads
66 for( $i = 0xc0; $i < 0xff; $i++ ) {
67 $total += $counts[$i];
68 }
69 return $total;
70 }
71 }
72
73 if ( !function_exists( 'array_diff_key' ) ) {
74 /**
75 * Exists in PHP 5.1.0+
76 * Not quite compatible, two-argument version only
77 * Null values will cause problems due to this use of isset()
78 */
79 function array_diff_key( $left, $right ) {
80 $result = $left;
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
84 }
85 }
86 return $result;
87 }
88 }
89
90 /**
91 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
92 */
93 function wfArrayDiff2( $a, $b ) {
94 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
95 }
96 function wfArrayDiff2_cmp( $a, $b ) {
97 if ( !is_array( $a ) ) {
98 return strcmp( $a, $b );
99 } elseif ( count( $a ) !== count( $b ) ) {
100 return count( $a ) < count( $b ) ? -1 : 1;
101 } else {
102 reset( $a );
103 reset( $b );
104 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
105 $cmp = strcmp( $valueA, $valueB );
106 if ( $cmp !== 0 ) {
107 return $cmp;
108 }
109 }
110 return 0;
111 }
112 }
113
114 /**
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.
118 */
119 function wfClone( $object ) {
120 return clone( $object );
121 }
122
123 /**
124 * Seed Mersenne Twister
125 * No-op for compatibility; only necessary in PHP < 4.2.0
126 */
127 function wfSeedRandom() {
128 /* No-op */
129 }
130
131 /**
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.
135 *
136 * @return string
137 */
138 function wfRandom() {
139 # The maximum random value is "only" 2^31-1, so get two random
140 # values to reduce the chance of dupes
141 $max = mt_getrandmax() + 1;
142 $rand = number_format( (mt_rand() * $max + mt_rand())
143 / $max / $max, 12, '.', '' );
144 return $rand;
145 }
146
147 /**
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.
150 *
151 * @param $s String:
152 * @return string
153 */
154 function wfUrlencode ( $s ) {
155 $s = urlencode( $s );
156 $s = preg_replace( '/%3[Aa]/', ':', $s );
157 $s = preg_replace( '/%2[Ff]/', '/', $s );
158
159 return $s;
160 }
161
162 /**
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.
165 *
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.
171 *
172 * @param $text String
173 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
174 */
175 function wfDebug( $text, $logonly = false ) {
176 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
177 static $recursion = 0;
178
179 static $cache = array(); // Cache of unoutputted messages
180
181 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
182 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
183 return;
184 }
185
186 if ( $wgDebugComments && !$logonly ) {
187 $cache[] = $text;
188
189 if ( !isset( $wgOut ) ) {
190 return;
191 }
192 if ( !StubObject::isRealObject( $wgOut ) ) {
193 if ( $recursion ) {
194 return;
195 }
196 $recursion++;
197 $wgOut->_unstub();
198 $recursion--;
199 }
200
201 // add the message and possible cached ones to the output
202 array_map( array( $wgOut, 'debug' ), $cache );
203 $cache = array();
204 }
205 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
206 # Strip unprintables; they can switch terminal modes when binary data
207 # gets dumped, which is pretty annoying.
208 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
209 wfErrorLog( $text, $wgDebugLogFile );
210 }
211 }
212
213 /**
214 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
215 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
216 *
217 * @param $logGroup String
218 * @param $text String
219 * @param $public Bool: whether to log the event in the public log if no private
220 * log file is specified, (default true)
221 */
222 function wfDebugLog( $logGroup, $text, $public = true ) {
223 global $wgDebugLogGroups;
224 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
225 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
226 $time = wfTimestamp( TS_DB );
227 $wiki = wfWikiID();
228 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
229 } else if ( $public === true ) {
230 wfDebug( $text, true );
231 }
232 }
233
234 /**
235 * Log for database errors
236 * @param $text String: database error message.
237 */
238 function wfLogDBError( $text ) {
239 global $wgDBerrorLog, $wgDBname;
240 if ( $wgDBerrorLog ) {
241 $host = trim(`hostname`);
242 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
243 wfErrorLog( $text, $wgDBerrorLog );
244 }
245 }
246
247 /**
248 * Log to a file without getting "file size exceeded" signals
249 */
250 function wfErrorLog( $text, $file ) {
251 wfSuppressWarnings();
252 $exists = file_exists( $file );
253 $size = $exists ? filesize( $file ) : false;
254 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
255 error_log( $text, 3, $file );
256 }
257 wfRestoreWarnings();
258 }
259
260 /**
261 * @todo document
262 */
263 function wfLogProfilingData() {
264 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
265 global $wgProfiler, $wgUser;
266 if ( !isset( $wgProfiler ) )
267 return;
268
269 $now = wfTime();
270 $elapsed = $now - $wgRequestTime;
271 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
272 $forward = '';
273 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
274 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
275 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
276 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
277 if( !empty( $_SERVER['HTTP_FROM'] ) )
278 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
279 if( $forward )
280 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
281 // Don't unstub $wgUser at this late stage just for statistics purposes
282 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
283 $forward .= ' anon';
284 $log = sprintf( "%s\t%04.3f\t%s\n",
285 gmdate( 'YmdHis' ), $elapsed,
286 urldecode( $wgRequest->getRequestURL() . $forward ) );
287 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
288 wfErrorLog( $log . $prof, $wgDebugLogFile );
289 }
290 }
291
292 /**
293 * Check if the wiki read-only lock file is present. This can be used to lock
294 * off editing functions, but doesn't guarantee that the database will not be
295 * modified.
296 * @return bool
297 */
298 function wfReadOnly() {
299 global $wgReadOnlyFile, $wgReadOnly;
300
301 if ( !is_null( $wgReadOnly ) ) {
302 return (bool)$wgReadOnly;
303 }
304 if ( '' == $wgReadOnlyFile ) {
305 return false;
306 }
307 // Set $wgReadOnly for faster access next time
308 if ( is_file( $wgReadOnlyFile ) ) {
309 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
310 } else {
311 $wgReadOnly = false;
312 }
313 return (bool)$wgReadOnly;
314 }
315
316 function wfReadOnlyReason() {
317 global $wgReadOnly;
318 wfReadOnly();
319 return $wgReadOnly;
320 }
321
322 /**
323 * Return a Language object from $langcode
324 * @param $langcode Mixed: either:
325 * - a Language object
326 * - code of the language to get the message for, if it is
327 * a valid code create a language for that language, if
328 * it is a string but not a valid code then make a basic
329 * language object
330 * - a boolean: if it's false then use the current users
331 * language (as a fallback for the old parameter
332 * functionality), or if it is true then use the wikis
333 * @return Language object
334 */
335 function wfGetLangObj( $langcode = false ){
336 # Identify which language to get or create a language object for.
337 if( $langcode instanceof Language )
338 # Great, we already have the object!
339 return $langcode;
340
341 global $wgContLang;
342 if( $langcode === $wgContLang->getCode() || $langcode === true )
343 # $langcode is the language code of the wikis content language object.
344 # or it is a boolean and value is true
345 return $wgContLang;
346
347 global $wgLang;
348 if( $langcode === $wgLang->getCode() || $langcode === false )
349 # $langcode is the language code of user language object.
350 # or it was a boolean and value is false
351 return $wgLang;
352
353 $validCodes = array_keys( Language::getLanguageNames() );
354 if( in_array( $langcode, $validCodes ) )
355 # $langcode corresponds to a valid language.
356 return Language::factory( $langcode );
357
358 # $langcode is a string, but not a valid language code; use content language.
359 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
360 return $wgContLang;
361 }
362
363 /**
364 * Get a message from anywhere, for the current user language.
365 *
366 * Use wfMsgForContent() instead if the message should NOT
367 * change depending on the user preferences.
368 *
369 * @param $key String: lookup key for the message, usually
370 * defined in languages/Language.php
371 *
372 * This function also takes extra optional parameters (not
373 * shown in the function definition), which can by used to
374 * insert variable text into the predefined message.
375 */
376 function wfMsg( $key ) {
377 $args = func_get_args();
378 array_shift( $args );
379 return wfMsgReal( $key, $args, true );
380 }
381
382 /**
383 * Same as above except doesn't transform the message
384 */
385 function wfMsgNoTrans( $key ) {
386 $args = func_get_args();
387 array_shift( $args );
388 return wfMsgReal( $key, $args, true, false, false );
389 }
390
391 /**
392 * Get a message from anywhere, for the current global language
393 * set with $wgLanguageCode.
394 *
395 * Use this if the message should NOT change dependent on the
396 * language set in the user's preferences. This is the case for
397 * most text written into logs, as well as link targets (such as
398 * the name of the copyright policy page). Link titles, on the
399 * other hand, should be shown in the UI language.
400 *
401 * Note that MediaWiki allows users to change the user interface
402 * language in their preferences, but a single installation
403 * typically only contains content in one language.
404 *
405 * Be wary of this distinction: If you use wfMsg() where you should
406 * use wfMsgForContent(), a user of the software may have to
407 * customize over 70 messages in order to, e.g., fix a link in every
408 * possible language.
409 *
410 * @param $key String: lookup key for the message, usually
411 * defined in languages/Language.php
412 */
413 function wfMsgForContent( $key ) {
414 global $wgForceUIMsgAsContentMsg;
415 $args = func_get_args();
416 array_shift( $args );
417 $forcontent = true;
418 if( is_array( $wgForceUIMsgAsContentMsg ) &&
419 in_array( $key, $wgForceUIMsgAsContentMsg ) )
420 $forcontent = false;
421 return wfMsgReal( $key, $args, true, $forcontent );
422 }
423
424 /**
425 * Same as above except doesn't transform the message
426 */
427 function wfMsgForContentNoTrans( $key ) {
428 global $wgForceUIMsgAsContentMsg;
429 $args = func_get_args();
430 array_shift( $args );
431 $forcontent = true;
432 if( is_array( $wgForceUIMsgAsContentMsg ) &&
433 in_array( $key, $wgForceUIMsgAsContentMsg ) )
434 $forcontent = false;
435 return wfMsgReal( $key, $args, true, $forcontent, false );
436 }
437
438 /**
439 * Get a message from the language file, for the UI elements
440 */
441 function wfMsgNoDB( $key ) {
442 $args = func_get_args();
443 array_shift( $args );
444 return wfMsgReal( $key, $args, false );
445 }
446
447 /**
448 * Get a message from the language file, for the content
449 */
450 function wfMsgNoDBForContent( $key ) {
451 global $wgForceUIMsgAsContentMsg;
452 $args = func_get_args();
453 array_shift( $args );
454 $forcontent = true;
455 if( is_array( $wgForceUIMsgAsContentMsg ) &&
456 in_array( $key, $wgForceUIMsgAsContentMsg ) )
457 $forcontent = false;
458 return wfMsgReal( $key, $args, false, $forcontent );
459 }
460
461
462 /**
463 * Really get a message
464 * @param $key String: key to get.
465 * @param $args
466 * @param $useDB Boolean
467 * @param $transform Boolean: Whether or not to transform the message.
468 * @param $forContent Boolean
469 * @return String: the requested message.
470 */
471 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
472 wfProfileIn( __METHOD__ );
473 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
474 $message = wfMsgReplaceArgs( $message, $args );
475 wfProfileOut( __METHOD__ );
476 return $message;
477 }
478
479 /**
480 * This function provides the message source for messages to be edited which are *not* stored in the database.
481 * @param $key String:
482 */
483 function wfMsgWeirdKey ( $key ) {
484 $source = wfMsgGetKey( $key, false, true, false );
485 if ( wfEmptyMsg( $key, $source ) )
486 return "";
487 else
488 return $source;
489 }
490
491 /**
492 * Fetch a message string value, but don't replace any keys yet.
493 * @param string $key
494 * @param bool $useDB
495 * @param string $langcode Code of the language to get the message for, or
496 * behaves as a content language switch if it is a
497 * boolean.
498 * @return string
499 * @private
500 */
501 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
502 global $wgContLang, $wgMessageCache;
503
504 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
505
506 # If $wgMessageCache isn't initialised yet, try to return something sensible.
507 if( is_object( $wgMessageCache ) ) {
508 $message = $wgMessageCache->get( $key, $useDB, $langCode );
509 if ( $transform ) {
510 $message = $wgMessageCache->transform( $message );
511 }
512 } else {
513 $lang = wfGetLangObj( $langCode );
514
515 # MessageCache::get() does this already, Language::getMessage() doesn't
516 # ISSUE: Should we try to handle "message/lang" here too?
517 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
518
519 if( is_object( $lang ) ) {
520 $message = $lang->getMessage( $key );
521 } else {
522 $message = false;
523 }
524 }
525
526 return $message;
527 }
528
529 /**
530 * Replace message parameter keys on the given formatted output.
531 *
532 * @param string $message
533 * @param array $args
534 * @return string
535 * @private
536 */
537 function wfMsgReplaceArgs( $message, $args ) {
538 # Fix windows line-endings
539 # Some messages are split with explode("\n", $msg)
540 $message = str_replace( "\r", '', $message );
541
542 // Replace arguments
543 if ( count( $args ) ) {
544 if ( is_array( $args[0] ) ) {
545 $args = array_values( $args[0] );
546 }
547 $replacementKeys = array();
548 foreach( $args as $n => $param ) {
549 $replacementKeys['$' . ($n + 1)] = $param;
550 }
551 $message = strtr( $message, $replacementKeys );
552 }
553
554 return $message;
555 }
556
557 /**
558 * Return an HTML-escaped version of a message.
559 * Parameter replacements, if any, are done *after* the HTML-escaping,
560 * so parameters may contain HTML (eg links or form controls). Be sure
561 * to pre-escape them if you really do want plaintext, or just wrap
562 * the whole thing in htmlspecialchars().
563 *
564 * @param string $key
565 * @param string ... parameters
566 * @return string
567 */
568 function wfMsgHtml( $key ) {
569 $args = func_get_args();
570 array_shift( $args );
571 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
572 }
573
574 /**
575 * Return an HTML version of message
576 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
577 * so parameters may contain HTML (eg links or form controls). Be sure
578 * to pre-escape them if you really do want plaintext, or just wrap
579 * the whole thing in htmlspecialchars().
580 *
581 * @param string $key
582 * @param string ... parameters
583 * @return string
584 */
585 function wfMsgWikiHtml( $key ) {
586 global $wgOut;
587 $args = func_get_args();
588 array_shift( $args );
589 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
590 }
591
592 /**
593 * Returns message in the requested format
594 * @param string $key Key of the message
595 * @param array $options Processing rules:
596 * <i>parse</i>: parses wikitext to html
597 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
598 * <i>escape</i>: filters message through htmlspecialchars
599 * <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
600 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
601 * <i>parsemag</i>: transform the message using magic phrases
602 * <i>content</i>: fetch message for content language instead of interface
603 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
604 * with parser, parseinline and parsemag is undefined.
605 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
606 */
607 function wfMsgExt( $key, $options ) {
608 global $wgOut, $wgParser;
609
610 $args = func_get_args();
611 array_shift( $args );
612 array_shift( $args );
613
614 if( !is_array($options) ) {
615 $options = array($options);
616 }
617
618 if( in_array('content', $options) ) {
619 $forContent = true;
620 $langCode = true;
621 } elseif( array_key_exists('language', $options) ) {
622 $forContent = false;
623 $langCode = $options['language'];
624 $validCodes = array_keys( Language::getLanguageNames() );
625 if( !in_array($options['language'], $validCodes) ) {
626 # Fallback to en, instead of whatever interface language we might have
627 $langCode = 'en';
628 }
629 } else {
630 $forContent = false;
631 $langCode = false;
632 }
633
634 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
635
636 if( !in_array('replaceafter', $options) ) {
637 $string = wfMsgReplaceArgs( $string, $args );
638 }
639
640 if( in_array('parse', $options) ) {
641 $string = $wgOut->parse( $string, true, !$forContent );
642 } elseif ( in_array('parseinline', $options) ) {
643 $string = $wgOut->parse( $string, true, !$forContent );
644 $m = array();
645 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
646 $string = $m[1];
647 }
648 } elseif ( in_array('parsemag', $options) ) {
649 global $wgMessageCache;
650 if ( isset( $wgMessageCache ) ) {
651 $string = $wgMessageCache->transform( $string, !$forContent );
652 }
653 }
654
655 if ( in_array('escape', $options) ) {
656 $string = htmlspecialchars ( $string );
657 } elseif ( in_array( 'escapenoentities', $options ) ) {
658 $string = htmlspecialchars( $string );
659 $string = str_replace( '&amp;', '&', $string );
660 $string = Sanitizer::normalizeCharReferences( $string );
661 }
662
663 if( in_array('replaceafter', $options) ) {
664 $string = wfMsgReplaceArgs( $string, $args );
665 }
666
667 return $string;
668 }
669
670
671 /**
672 * Just like exit() but makes a note of it.
673 * Commits open transactions except if the error parameter is set
674 *
675 * @deprecated Please return control to the caller or throw an exception
676 */
677 function wfAbruptExit( $error = false ){
678 static $called = false;
679 if ( $called ){
680 exit( -1 );
681 }
682 $called = true;
683
684 $bt = wfDebugBacktrace();
685 if( $bt ) {
686 for($i = 0; $i < count($bt) ; $i++){
687 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
688 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
689 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
690 }
691 } else {
692 wfDebug('WARNING: Abrupt exit\n');
693 }
694
695 wfLogProfilingData();
696
697 if ( !$error ) {
698 wfGetLB()->closeAll();
699 }
700 exit( -1 );
701 }
702
703 /**
704 * @deprecated Please return control the caller or throw an exception
705 */
706 function wfErrorExit() {
707 wfAbruptExit( true );
708 }
709
710 /**
711 * Print a simple message and die, returning nonzero to the shell if any.
712 * Plain die() fails to return nonzero to the shell if you pass a string.
713 * @param string $msg
714 */
715 function wfDie( $msg='' ) {
716 echo $msg;
717 die( 1 );
718 }
719
720 /**
721 * Throw a debugging exception. This function previously once exited the process,
722 * but now throws an exception instead, with similar results.
723 *
724 * @param string $msg Message shown when dieing.
725 */
726 function wfDebugDieBacktrace( $msg = '' ) {
727 throw new MWException( $msg );
728 }
729
730 /**
731 * Fetch server name for use in error reporting etc.
732 * Use real server name if available, so we know which machine
733 * in a server farm generated the current page.
734 * @return string
735 */
736 function wfHostname() {
737 if ( function_exists( 'posix_uname' ) ) {
738 // This function not present on Windows
739 $uname = @posix_uname();
740 } else {
741 $uname = false;
742 }
743 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
744 return $uname['nodename'];
745 } else {
746 # This may be a virtual server.
747 return $_SERVER['SERVER_NAME'];
748 }
749 }
750
751 /**
752 * Returns a HTML comment with the elapsed time since request.
753 * This method has no side effects.
754 * @return string
755 */
756 function wfReportTime() {
757 global $wgRequestTime, $wgShowHostnames;
758
759 $now = wfTime();
760 $elapsed = $now - $wgRequestTime;
761
762 return $wgShowHostnames
763 ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
764 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
765 }
766
767 /**
768 * Safety wrapper for debug_backtrace().
769 *
770 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
771 * murky circumstances, which may be triggered in part by stub objects
772 * or other fancy talkin'.
773 *
774 * Will return an empty array if Zend Optimizer is detected, otherwise
775 * the output from debug_backtrace() (trimmed).
776 *
777 * @return array of backtrace information
778 */
779 function wfDebugBacktrace() {
780 if( extension_loaded( 'Zend Optimizer' ) ) {
781 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
782 return array();
783 } else {
784 return array_slice( debug_backtrace(), 1 );
785 }
786 }
787
788 function wfBacktrace() {
789 global $wgCommandLineMode;
790
791 if ( $wgCommandLineMode ) {
792 $msg = '';
793 } else {
794 $msg = "<ul>\n";
795 }
796 $backtrace = wfDebugBacktrace();
797 foreach( $backtrace as $call ) {
798 if( isset( $call['file'] ) ) {
799 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
800 $file = $f[count($f)-1];
801 } else {
802 $file = '-';
803 }
804 if( isset( $call['line'] ) ) {
805 $line = $call['line'];
806 } else {
807 $line = '-';
808 }
809 if ( $wgCommandLineMode ) {
810 $msg .= "$file line $line calls ";
811 } else {
812 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
813 }
814 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
815 $msg .= $call['function'] . '()';
816
817 if ( $wgCommandLineMode ) {
818 $msg .= "\n";
819 } else {
820 $msg .= "</li>\n";
821 }
822 }
823 if ( $wgCommandLineMode ) {
824 $msg .= "\n";
825 } else {
826 $msg .= "</ul>\n";
827 }
828
829 return $msg;
830 }
831
832
833 /* Some generic result counters, pulled out of SearchEngine */
834
835
836 /**
837 * @todo document
838 */
839 function wfShowingResults( $offset, $limit ) {
840 global $wgLang;
841 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
842 }
843
844 /**
845 * @todo document
846 */
847 function wfShowingResultsNum( $offset, $limit, $num ) {
848 global $wgLang;
849 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
850 }
851
852 /**
853 * @todo document
854 */
855 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
856 global $wgLang;
857 $fmtLimit = $wgLang->formatNum( $limit );
858 $prev = wfMsg( 'prevn', $fmtLimit );
859 $next = wfMsg( 'nextn', $fmtLimit );
860
861 if( is_object( $link ) ) {
862 $title =& $link;
863 } else {
864 $title = Title::newFromText( $link );
865 if( is_null( $title ) ) {
866 return false;
867 }
868 }
869
870 if ( 0 != $offset ) {
871 $po = $offset - $limit;
872 if ( $po < 0 ) { $po = 0; }
873 $q = "limit={$limit}&offset={$po}";
874 if ( '' != $query ) { $q .= '&'.$query; }
875 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
876 } else { $plink = $prev; }
877
878 $no = $offset + $limit;
879 $q = 'limit='.$limit.'&offset='.$no;
880 if ( '' != $query ) { $q .= '&'.$query; }
881
882 if ( $atend ) {
883 $nlink = $next;
884 } else {
885 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
886 }
887 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
888 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
889 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
890 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
891 wfNumLink( $offset, 500, $title, $query );
892
893 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
894 }
895
896 /**
897 * @todo document
898 */
899 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
900 global $wgLang;
901 if ( '' == $query ) { $q = ''; }
902 else { $q = $query.'&'; }
903 $q .= 'limit='.$limit.'&offset='.$offset;
904
905 $fmtLimit = $wgLang->formatNum( $limit );
906 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
907 return $s;
908 }
909
910 /**
911 * @todo document
912 * @todo FIXME: we may want to blacklist some broken browsers
913 *
914 * @return bool Whereas client accept gzip compression
915 */
916 function wfClientAcceptsGzip() {
917 global $wgUseGzip;
918 if( $wgUseGzip ) {
919 # FIXME: we may want to blacklist some broken browsers
920 $m = array();
921 if( preg_match(
922 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
923 $_SERVER['HTTP_ACCEPT_ENCODING'],
924 $m ) ) {
925 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
926 wfDebug( " accepts gzip\n" );
927 return true;
928 }
929 }
930 return false;
931 }
932
933 /**
934 * Obtain the offset and limit values from the request string;
935 * used in special pages
936 *
937 * @param $deflimit Default limit if none supplied
938 * @param $optionname Name of a user preference to check against
939 * @return array
940 *
941 */
942 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
943 global $wgRequest;
944 return $wgRequest->getLimitOffset( $deflimit, $optionname );
945 }
946
947 /**
948 * Escapes the given text so that it may be output using addWikiText()
949 * without any linking, formatting, etc. making its way through. This
950 * is achieved by substituting certain characters with HTML entities.
951 * As required by the callers, <nowiki> is not used. It currently does
952 * not filter out characters which have special meaning only at the
953 * start of a line, such as "*".
954 *
955 * @param string $text Text to be escaped
956 */
957 function wfEscapeWikiText( $text ) {
958 $text = str_replace(
959 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
960 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
961 htmlspecialchars($text) );
962 return $text;
963 }
964
965 /**
966 * @todo document
967 */
968 function wfQuotedPrintable( $string, $charset = '' ) {
969 # Probably incomplete; see RFC 2045
970 if( empty( $charset ) ) {
971 global $wgInputEncoding;
972 $charset = $wgInputEncoding;
973 }
974 $charset = strtoupper( $charset );
975 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
976
977 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
978 $replace = $illegal . '\t ?_';
979 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
980 $out = "=?$charset?Q?";
981 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
982 $out .= '?=';
983 return $out;
984 }
985
986
987 /**
988 * @todo document
989 * @return float
990 */
991 function wfTime() {
992 return microtime(true);
993 }
994
995 /**
996 * Sets dest to source and returns the original value of dest
997 * If source is NULL, it just returns the value, it doesn't set the variable
998 */
999 function wfSetVar( &$dest, $source ) {
1000 $temp = $dest;
1001 if ( !is_null( $source ) ) {
1002 $dest = $source;
1003 }
1004 return $temp;
1005 }
1006
1007 /**
1008 * As for wfSetVar except setting a bit
1009 */
1010 function wfSetBit( &$dest, $bit, $state = true ) {
1011 $temp = (bool)($dest & $bit );
1012 if ( !is_null( $state ) ) {
1013 if ( $state ) {
1014 $dest |= $bit;
1015 } else {
1016 $dest &= ~$bit;
1017 }
1018 }
1019 return $temp;
1020 }
1021
1022 /**
1023 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1024 * "days=7&limit=100". Options in the first array override options in the second.
1025 * Options set to "" will not be output.
1026 */
1027 function wfArrayToCGI( $array1, $array2 = NULL )
1028 {
1029 if ( !is_null( $array2 ) ) {
1030 $array1 = $array1 + $array2;
1031 }
1032
1033 $cgi = '';
1034 foreach ( $array1 as $key => $value ) {
1035 if ( '' !== $value ) {
1036 if ( '' != $cgi ) {
1037 $cgi .= '&';
1038 }
1039 if(is_array($value))
1040 {
1041 $firstTime = true;
1042 foreach($value as $v)
1043 {
1044 $cgi .= ($firstTime ? '' : '&') .
1045 urlencode( $key . '[]' ) . '=' .
1046 urlencode( $v );
1047 $firstTime = false;
1048 }
1049 }
1050 else
1051 $cgi .= urlencode( $key ) . '=' .
1052 urlencode( $value );
1053 }
1054 }
1055 return $cgi;
1056 }
1057
1058 /**
1059 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1060 * its argument and returns the same string in array form. This allows compa-
1061 * tibility with legacy functions that accept raw query strings instead of nice
1062 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1063 * valid query strings, or it will explode.
1064 *
1065 * @param $query string Query string
1066 * @return array Array version of input
1067 */
1068 function wfCgiToArray( $query ) {
1069 if( isset( $query[0] ) and $query[0] == '?' ) {
1070 $query = substr( $query, 1 );
1071 }
1072 $bits = explode( '&', $query );
1073 $ret = array();
1074 foreach( $bits as $bit ) {
1075 if( $bit === '' ) {
1076 continue;
1077 }
1078 list( $key, $value ) = explode( '=', $bit );
1079 $key = urldecode( $key );
1080 $value = urldecode( $value );
1081 $ret[$key] = $value;
1082 }
1083 return $ret;
1084 }
1085
1086 /**
1087 * Append a query string to an existing URL, which may or may not already
1088 * have query string parameters already. If so, they will be combined.
1089 *
1090 * @param string $url
1091 * @param string $query
1092 * @return string
1093 */
1094 function wfAppendQuery( $url, $query ) {
1095 if( $query != '' ) {
1096 if( false === strpos( $url, '?' ) ) {
1097 $url .= '?';
1098 } else {
1099 $url .= '&';
1100 }
1101 $url .= $query;
1102 }
1103 return $url;
1104 }
1105
1106 /**
1107 * Expand a potentially local URL to a fully-qualified URL.
1108 * Assumes $wgServer is correct. :)
1109 * @param string $url, either fully-qualified or a local path + query
1110 * @return string Fully-qualified URL
1111 */
1112 function wfExpandUrl( $url ) {
1113 if( substr( $url, 0, 1 ) == '/' ) {
1114 global $wgServer;
1115 return $wgServer . $url;
1116 } else {
1117 return $url;
1118 }
1119 }
1120
1121 /**
1122 * This is obsolete, use SquidUpdate::purge()
1123 * @deprecated
1124 */
1125 function wfPurgeSquidServers ($urlArr) {
1126 SquidUpdate::purge( $urlArr );
1127 }
1128
1129 /**
1130 * Windows-compatible version of escapeshellarg()
1131 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1132 * function puts single quotes in regardless of OS
1133 */
1134 function wfEscapeShellArg( ) {
1135 $args = func_get_args();
1136 $first = true;
1137 $retVal = '';
1138 foreach ( $args as $arg ) {
1139 if ( !$first ) {
1140 $retVal .= ' ';
1141 } else {
1142 $first = false;
1143 }
1144
1145 if ( wfIsWindows() ) {
1146 // Escaping for an MSVC-style command line parser
1147 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1148 // Double the backslashes before any double quotes. Escape the double quotes.
1149 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1150 $arg = '';
1151 $delim = false;
1152 foreach ( $tokens as $token ) {
1153 if ( $delim ) {
1154 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1155 } else {
1156 $arg .= $token;
1157 }
1158 $delim = !$delim;
1159 }
1160 // Double the backslashes before the end of the string, because
1161 // we will soon add a quote
1162 $m = array();
1163 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1164 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1165 }
1166
1167 // Add surrounding quotes
1168 $retVal .= '"' . $arg . '"';
1169 } else {
1170 $retVal .= escapeshellarg( $arg );
1171 }
1172 }
1173 return $retVal;
1174 }
1175
1176 /**
1177 * wfMerge attempts to merge differences between three texts.
1178 * Returns true for a clean merge and false for failure or a conflict.
1179 */
1180 function wfMerge( $old, $mine, $yours, &$result ){
1181 global $wgDiff3;
1182
1183 # This check may also protect against code injection in
1184 # case of broken installations.
1185 if(! file_exists( $wgDiff3 ) ){
1186 wfDebug( "diff3 not found\n" );
1187 return false;
1188 }
1189
1190 # Make temporary files
1191 $td = wfTempDir();
1192 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1193 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1194 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1195
1196 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1197 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1198 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1199
1200 # Check for a conflict
1201 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1202 wfEscapeShellArg( $mytextName ) . ' ' .
1203 wfEscapeShellArg( $oldtextName ) . ' ' .
1204 wfEscapeShellArg( $yourtextName );
1205 $handle = popen( $cmd, 'r' );
1206
1207 if( fgets( $handle, 1024 ) ){
1208 $conflict = true;
1209 } else {
1210 $conflict = false;
1211 }
1212 pclose( $handle );
1213
1214 # Merge differences
1215 $cmd = $wgDiff3 . ' -a -e --merge ' .
1216 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1217 $handle = popen( $cmd, 'r' );
1218 $result = '';
1219 do {
1220 $data = fread( $handle, 8192 );
1221 if ( strlen( $data ) == 0 ) {
1222 break;
1223 }
1224 $result .= $data;
1225 } while ( true );
1226 pclose( $handle );
1227 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1228
1229 if ( $result === '' && $old !== '' && $conflict == false ) {
1230 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1231 $conflict = true;
1232 }
1233 return ! $conflict;
1234 }
1235
1236 /**
1237 * Returns unified plain-text diff of two texts.
1238 * Useful for machine processing of diffs.
1239 * @param $before string The text before the changes.
1240 * @param $after string The text after the changes.
1241 * @param $params string Command-line options for the diff command.
1242 * @return string Unified diff of $before and $after
1243 */
1244 function wfDiff( $before, $after, $params = '-u' ) {
1245 global $wgDiff;
1246
1247 # This check may also protect against code injection in
1248 # case of broken installations.
1249 if( !file_exists( $wgDiff ) ){
1250 wfDebug( "diff executable not found\n" );
1251 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1252 $format = new UnifiedDiffFormatter();
1253 return $format->format( $diffs );
1254 }
1255
1256 # Make temporary files
1257 $td = wfTempDir();
1258 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1259 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1260
1261 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1262 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1263
1264 // Get the diff of the two files
1265 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1266
1267 $h = popen( $cmd, 'r' );
1268
1269 $diff = '';
1270
1271 do {
1272 $data = fread( $h, 8192 );
1273 if ( strlen( $data ) == 0 ) {
1274 break;
1275 }
1276 $diff .= $data;
1277 } while ( true );
1278
1279 // Clean up
1280 pclose( $h );
1281 unlink( $oldtextName );
1282 unlink( $newtextName );
1283
1284 // Kill the --- and +++ lines. They're not useful.
1285 $diff_lines = explode( "\n", $diff );
1286 if (strpos( $diff_lines[0], '---' ) === 0) {
1287 unset($diff_lines[0]);
1288 }
1289 if (strpos( $diff_lines[1], '+++' ) === 0) {
1290 unset($diff_lines[1]);
1291 }
1292
1293 $diff = implode( "\n", $diff_lines );
1294
1295 return $diff;
1296 }
1297
1298 /**
1299 * @todo document
1300 */
1301 function wfVarDump( $var ) {
1302 global $wgOut;
1303 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1304 if ( headers_sent() || !@is_object( $wgOut ) ) {
1305 print $s;
1306 } else {
1307 $wgOut->addHTML( $s );
1308 }
1309 }
1310
1311 /**
1312 * Provide a simple HTTP error.
1313 */
1314 function wfHttpError( $code, $label, $desc ) {
1315 global $wgOut;
1316 $wgOut->disable();
1317 header( "HTTP/1.0 $code $label" );
1318 header( "Status: $code $label" );
1319 $wgOut->sendCacheControl();
1320
1321 header( 'Content-type: text/html; charset=utf-8' );
1322 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1323 "<html><head><title>" .
1324 htmlspecialchars( $label ) .
1325 "</title></head><body><h1>" .
1326 htmlspecialchars( $label ) .
1327 "</h1><p>" .
1328 nl2br( htmlspecialchars( $desc ) ) .
1329 "</p></body></html>\n";
1330 }
1331
1332 /**
1333 * Clear away any user-level output buffers, discarding contents.
1334 *
1335 * Suitable for 'starting afresh', for instance when streaming
1336 * relatively large amounts of data without buffering, or wanting to
1337 * output image files without ob_gzhandler's compression.
1338 *
1339 * The optional $resetGzipEncoding parameter controls suppression of
1340 * the Content-Encoding header sent by ob_gzhandler; by default it
1341 * is left. See comments for wfClearOutputBuffers() for why it would
1342 * be used.
1343 *
1344 * Note that some PHP configuration options may add output buffer
1345 * layers which cannot be removed; these are left in place.
1346 *
1347 * @param bool $resetGzipEncoding
1348 */
1349 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1350 if( $resetGzipEncoding ) {
1351 // Suppress Content-Encoding and Content-Length
1352 // headers from 1.10+s wfOutputHandler
1353 global $wgDisableOutputCompression;
1354 $wgDisableOutputCompression = true;
1355 }
1356 while( $status = ob_get_status() ) {
1357 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1358 // Probably from zlib.output_compression or other
1359 // PHP-internal setting which can't be removed.
1360 //
1361 // Give up, and hope the result doesn't break
1362 // output behavior.
1363 break;
1364 }
1365 if( !ob_end_clean() ) {
1366 // Could not remove output buffer handler; abort now
1367 // to avoid getting in some kind of infinite loop.
1368 break;
1369 }
1370 if( $resetGzipEncoding ) {
1371 if( $status['name'] == 'ob_gzhandler' ) {
1372 // Reset the 'Content-Encoding' field set by this handler
1373 // so we can start fresh.
1374 header( 'Content-Encoding:' );
1375 }
1376 }
1377 }
1378 }
1379
1380 /**
1381 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1382 *
1383 * Clear away output buffers, but keep the Content-Encoding header
1384 * produced by ob_gzhandler, if any.
1385 *
1386 * This should be used for HTTP 304 responses, where you need to
1387 * preserve the Content-Encoding header of the real result, but
1388 * also need to suppress the output of ob_gzhandler to keep to spec
1389 * and avoid breaking Firefox in rare cases where the headers and
1390 * body are broken over two packets.
1391 */
1392 function wfClearOutputBuffers() {
1393 wfResetOutputBuffers( false );
1394 }
1395
1396 /**
1397 * Converts an Accept-* header into an array mapping string values to quality
1398 * factors
1399 */
1400 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1401 # No arg means accept anything (per HTTP spec)
1402 if( !$accept ) {
1403 return array( $def => 1.0 );
1404 }
1405
1406 $prefs = array();
1407
1408 $parts = explode( ',', $accept );
1409
1410 foreach( $parts as $part ) {
1411 # FIXME: doesn't deal with params like 'text/html; level=1'
1412 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1413 $match = array();
1414 if( !isset( $qpart ) ) {
1415 $prefs[$value] = 1.0;
1416 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1417 $prefs[$value] = floatval($match[1]);
1418 }
1419 }
1420
1421 return $prefs;
1422 }
1423
1424 /**
1425 * Checks if a given MIME type matches any of the keys in the given
1426 * array. Basic wildcards are accepted in the array keys.
1427 *
1428 * Returns the matching MIME type (or wildcard) if a match, otherwise
1429 * NULL if no match.
1430 *
1431 * @param string $type
1432 * @param array $avail
1433 * @return string
1434 * @private
1435 */
1436 function mimeTypeMatch( $type, $avail ) {
1437 if( array_key_exists($type, $avail) ) {
1438 return $type;
1439 } else {
1440 $parts = explode( '/', $type );
1441 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1442 return $parts[0] . '/*';
1443 } elseif( array_key_exists( '*/*', $avail ) ) {
1444 return '*/*';
1445 } else {
1446 return NULL;
1447 }
1448 }
1449 }
1450
1451 /**
1452 * Returns the 'best' match between a client's requested internet media types
1453 * and the server's list of available types. Each list should be an associative
1454 * array of type to preference (preference is a float between 0.0 and 1.0).
1455 * Wildcards in the types are acceptable.
1456 *
1457 * @param array $cprefs Client's acceptable type list
1458 * @param array $sprefs Server's offered types
1459 * @return string
1460 *
1461 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1462 * XXX: generalize to negotiate other stuff
1463 */
1464 function wfNegotiateType( $cprefs, $sprefs ) {
1465 $combine = array();
1466
1467 foreach( array_keys($sprefs) as $type ) {
1468 $parts = explode( '/', $type );
1469 if( $parts[1] != '*' ) {
1470 $ckey = mimeTypeMatch( $type, $cprefs );
1471 if( $ckey ) {
1472 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1473 }
1474 }
1475 }
1476
1477 foreach( array_keys( $cprefs ) as $type ) {
1478 $parts = explode( '/', $type );
1479 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1480 $skey = mimeTypeMatch( $type, $sprefs );
1481 if( $skey ) {
1482 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1483 }
1484 }
1485 }
1486
1487 $bestq = 0;
1488 $besttype = NULL;
1489
1490 foreach( array_keys( $combine ) as $type ) {
1491 if( $combine[$type] > $bestq ) {
1492 $besttype = $type;
1493 $bestq = $combine[$type];
1494 }
1495 }
1496
1497 return $besttype;
1498 }
1499
1500 /**
1501 * Array lookup
1502 * Returns an array where the values in the first array are replaced by the
1503 * values in the second array with the corresponding keys
1504 *
1505 * @return array
1506 */
1507 function wfArrayLookup( $a, $b ) {
1508 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1509 }
1510
1511 /**
1512 * Convenience function; returns MediaWiki timestamp for the present time.
1513 * @return string
1514 */
1515 function wfTimestampNow() {
1516 # return NOW
1517 return wfTimestamp( TS_MW, time() );
1518 }
1519
1520 /**
1521 * Reference-counted warning suppression
1522 */
1523 function wfSuppressWarnings( $end = false ) {
1524 static $suppressCount = 0;
1525 static $originalLevel = false;
1526
1527 if ( $end ) {
1528 if ( $suppressCount ) {
1529 --$suppressCount;
1530 if ( !$suppressCount ) {
1531 error_reporting( $originalLevel );
1532 }
1533 }
1534 } else {
1535 if ( !$suppressCount ) {
1536 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1537 }
1538 ++$suppressCount;
1539 }
1540 }
1541
1542 /**
1543 * Restore error level to previous value
1544 */
1545 function wfRestoreWarnings() {
1546 wfSuppressWarnings( true );
1547 }
1548
1549 # Autodetect, convert and provide timestamps of various types
1550
1551 /**
1552 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1553 */
1554 define('TS_UNIX', 0);
1555
1556 /**
1557 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1558 */
1559 define('TS_MW', 1);
1560
1561 /**
1562 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1563 */
1564 define('TS_DB', 2);
1565
1566 /**
1567 * RFC 2822 format, for E-mail and HTTP headers
1568 */
1569 define('TS_RFC2822', 3);
1570
1571 /**
1572 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1573 *
1574 * This is used by Special:Export
1575 */
1576 define('TS_ISO_8601', 4);
1577
1578 /**
1579 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1580 *
1581 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1582 * DateTime tag and page 36 for the DateTimeOriginal and
1583 * DateTimeDigitized tags.
1584 */
1585 define('TS_EXIF', 5);
1586
1587 /**
1588 * Oracle format time.
1589 */
1590 define('TS_ORACLE', 6);
1591
1592 /**
1593 * Postgres format time.
1594 */
1595 define('TS_POSTGRES', 7);
1596
1597 /**
1598 * @param mixed $outputtype A timestamp in one of the supported formats, the
1599 * function will autodetect which format is supplied
1600 * and act accordingly.
1601 * @return string Time in the format specified in $outputtype
1602 */
1603 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1604 $uts = 0;
1605 $da = array();
1606 if ($ts==0) {
1607 $uts=time();
1608 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1609 # TS_DB
1610 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1611 # TS_EXIF
1612 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1613 # TS_MW
1614 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1615 # TS_UNIX
1616 $uts = $ts;
1617 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1618 # TS_ORACLE
1619 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1620 str_replace("+00:00", "UTC", $ts)));
1621 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1622 # TS_ISO_8601
1623 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1624 # TS_POSTGRES
1625 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1626 # TS_POSTGRES
1627 } else {
1628 # Bogus value; fall back to the epoch...
1629 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1630 $uts = 0;
1631 }
1632
1633 if (count( $da ) ) {
1634 // Warning! gmmktime() acts oddly if the month or day is set to 0
1635 // We may want to handle that explicitly at some point
1636 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1637 (int)$da[2],(int)$da[3],(int)$da[1]);
1638 }
1639
1640 switch($outputtype) {
1641 case TS_UNIX:
1642 return $uts;
1643 case TS_MW:
1644 return gmdate( 'YmdHis', $uts );
1645 case TS_DB:
1646 return gmdate( 'Y-m-d H:i:s', $uts );
1647 case TS_ISO_8601:
1648 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1649 // This shouldn't ever be used, but is included for completeness
1650 case TS_EXIF:
1651 return gmdate( 'Y:m:d H:i:s', $uts );
1652 case TS_RFC2822:
1653 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1654 case TS_ORACLE:
1655 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1656 case TS_POSTGRES:
1657 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1658 default:
1659 throw new MWException( 'wfTimestamp() called with illegal output type.');
1660 }
1661 }
1662
1663 /**
1664 * Return a formatted timestamp, or null if input is null.
1665 * For dealing with nullable timestamp columns in the database.
1666 * @param int $outputtype
1667 * @param string $ts
1668 * @return string
1669 */
1670 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1671 if( is_null( $ts ) ) {
1672 return null;
1673 } else {
1674 return wfTimestamp( $outputtype, $ts );
1675 }
1676 }
1677
1678 /**
1679 * Check if the operating system is Windows
1680 *
1681 * @return bool True if it's Windows, False otherwise.
1682 */
1683 function wfIsWindows() {
1684 if (substr(php_uname(), 0, 7) == 'Windows') {
1685 return true;
1686 } else {
1687 return false;
1688 }
1689 }
1690
1691 /**
1692 * Swap two variables
1693 */
1694 function swap( &$x, &$y ) {
1695 $z = $x;
1696 $x = $y;
1697 $y = $z;
1698 }
1699
1700 function wfGetCachedNotice( $name ) {
1701 global $wgOut, $parserMemc;
1702 $fname = 'wfGetCachedNotice';
1703 wfProfileIn( $fname );
1704
1705 $needParse = false;
1706
1707 if( $name === 'default' ) {
1708 // special case
1709 global $wgSiteNotice;
1710 $notice = $wgSiteNotice;
1711 if( empty( $notice ) ) {
1712 wfProfileOut( $fname );
1713 return false;
1714 }
1715 } else {
1716 $notice = wfMsgForContentNoTrans( $name );
1717 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1718 wfProfileOut( $fname );
1719 return( false );
1720 }
1721 }
1722
1723 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1724 if( is_array( $cachedNotice ) ) {
1725 if( md5( $notice ) == $cachedNotice['hash'] ) {
1726 $notice = $cachedNotice['html'];
1727 } else {
1728 $needParse = true;
1729 }
1730 } else {
1731 $needParse = true;
1732 }
1733
1734 if( $needParse ) {
1735 if( is_object( $wgOut ) ) {
1736 $parsed = $wgOut->parse( $notice );
1737 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1738 $notice = $parsed;
1739 } else {
1740 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1741 $notice = '';
1742 }
1743 }
1744
1745 wfProfileOut( $fname );
1746 return $notice;
1747 }
1748
1749 function wfGetNamespaceNotice() {
1750 global $wgTitle;
1751
1752 # Paranoia
1753 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1754 return "";
1755
1756 $fname = 'wfGetNamespaceNotice';
1757 wfProfileIn( $fname );
1758
1759 $key = "namespacenotice-" . $wgTitle->getNsText();
1760 $namespaceNotice = wfGetCachedNotice( $key );
1761 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1762 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1763 } else {
1764 $namespaceNotice = "";
1765 }
1766
1767 wfProfileOut( $fname );
1768 return $namespaceNotice;
1769 }
1770
1771 function wfGetSiteNotice() {
1772 global $wgUser, $wgSiteNotice;
1773 $fname = 'wfGetSiteNotice';
1774 wfProfileIn( $fname );
1775 $siteNotice = '';
1776
1777 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1778 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1779 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1780 } else {
1781 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1782 if( !$anonNotice ) {
1783 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1784 } else {
1785 $siteNotice = $anonNotice;
1786 }
1787 }
1788 if( !$siteNotice ) {
1789 $siteNotice = wfGetCachedNotice( 'default' );
1790 }
1791 }
1792
1793 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1794 wfProfileOut( $fname );
1795 return $siteNotice;
1796 }
1797
1798 /**
1799 * BC wrapper for MimeMagic::singleton()
1800 * @deprecated
1801 */
1802 function &wfGetMimeMagic() {
1803 return MimeMagic::singleton();
1804 }
1805
1806 /**
1807 * Tries to get the system directory for temporary files.
1808 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1809 * and if none are set /tmp is returned as the generic Unix default.
1810 *
1811 * NOTE: When possible, use the tempfile() function to create temporary
1812 * files to avoid race conditions on file creation, etc.
1813 *
1814 * @return string
1815 */
1816 function wfTempDir() {
1817 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1818 $tmp = getenv( $var );
1819 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1820 return $tmp;
1821 }
1822 }
1823 # Hope this is Unix of some kind!
1824 return '/tmp';
1825 }
1826
1827 /**
1828 * Make directory, and make all parent directories if they don't exist
1829 *
1830 * @param string $fullDir Full path to directory to create
1831 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1832 * @return bool
1833 */
1834 function wfMkdirParents( $fullDir, $mode = null ) {
1835 global $wgDirectoryMode;
1836 if( strval( $fullDir ) === '' )
1837 return true;
1838 if( file_exists( $fullDir ) )
1839 return true;
1840 // If not defined or isn't an int, set to default
1841 if ( is_null( $mode ) ) {
1842 $mode = $wgDirectoryMode;
1843 }
1844
1845
1846 # Go back through the paths to find the first directory that exists
1847 $currentDir = $fullDir;
1848 $createList = array();
1849 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1850 # Strip trailing slashes
1851 $currentDir = rtrim( $currentDir, '/\\' );
1852
1853 # Add to create list
1854 $createList[] = $currentDir;
1855
1856 # Find next delimiter searching from the end
1857 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1858 if ( $p === false ) {
1859 $currentDir = false;
1860 } else {
1861 $currentDir = substr( $currentDir, 0, $p );
1862 }
1863 }
1864
1865 if ( count( $createList ) == 0 ) {
1866 # Directory specified already exists
1867 return true;
1868 } elseif ( $currentDir === false ) {
1869 # Went all the way back to root and it apparently doesn't exist
1870 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1871 return false;
1872 }
1873 # Now go forward creating directories
1874 $createList = array_reverse( $createList );
1875
1876 # Is the parent directory writable?
1877 if ( $currentDir === '' ) {
1878 $currentDir = '/';
1879 }
1880 if ( !is_writable( $currentDir ) ) {
1881 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1882 return false;
1883 }
1884
1885 foreach ( $createList as $dir ) {
1886 # use chmod to override the umask, as suggested by the PHP manual
1887 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1888 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1889 return false;
1890 }
1891 }
1892 return true;
1893 }
1894
1895 /**
1896 * Increment a statistics counter
1897 */
1898 function wfIncrStats( $key ) {
1899 global $wgStatsMethod;
1900
1901 if( $wgStatsMethod == 'udp' ) {
1902 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1903 static $socket;
1904 if (!$socket) {
1905 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1906 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1907 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1908 }
1909 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1910 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1911 } elseif( $wgStatsMethod == 'cache' ) {
1912 global $wgMemc;
1913 $key = wfMemcKey( 'stats', $key );
1914 if ( is_null( $wgMemc->incr( $key ) ) ) {
1915 $wgMemc->add( $key, 1 );
1916 }
1917 } else {
1918 // Disabled
1919 }
1920 }
1921
1922 /**
1923 * @param mixed $nr The number to format
1924 * @param int $acc The number of digits after the decimal point, default 2
1925 * @param bool $round Whether or not to round the value, default true
1926 * @return float
1927 */
1928 function wfPercent( $nr, $acc = 2, $round = true ) {
1929 $ret = sprintf( "%.${acc}f", $nr );
1930 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1931 }
1932
1933 /**
1934 * Encrypt a username/password.
1935 *
1936 * @param string $userid ID of the user
1937 * @param string $password Password of the user
1938 * @return string Hashed password
1939 * @deprecated Use User::crypt() or User::oldCrypt() instead
1940 */
1941 function wfEncryptPassword( $userid, $password ) {
1942 wfDeprecated(__FUNCTION__);
1943 # Just wrap around User::oldCrypt()
1944 return User::oldCrypt($password, $userid);
1945 }
1946
1947 /**
1948 * Appends to second array if $value differs from that in $default
1949 */
1950 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1951 if ( is_null( $changed ) ) {
1952 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1953 }
1954 if ( $default[$key] !== $value ) {
1955 $changed[$key] = $value;
1956 }
1957 }
1958
1959 /**
1960 * Since wfMsg() and co suck, they don't return false if the message key they
1961 * looked up didn't exist but a XHTML string, this function checks for the
1962 * nonexistance of messages by looking at wfMsg() output
1963 *
1964 * @param $msg The message key looked up
1965 * @param $wfMsgOut The output of wfMsg*()
1966 * @return bool
1967 */
1968 function wfEmptyMsg( $msg, $wfMsgOut ) {
1969 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1970 }
1971
1972 /**
1973 * Find out whether or not a mixed variable exists in a string
1974 *
1975 * @param mixed needle
1976 * @param string haystack
1977 * @return bool
1978 */
1979 function in_string( $needle, $str ) {
1980 return strpos( $str, $needle ) !== false;
1981 }
1982
1983 function wfSpecialList( $page, $details ) {
1984 global $wgContLang;
1985 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1986 return $page . $details;
1987 }
1988
1989 /**
1990 * Returns a regular expression of url protocols
1991 *
1992 * @return string
1993 */
1994 function wfUrlProtocols() {
1995 global $wgUrlProtocols;
1996
1997 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1998 // with LocalSettings files from 1.5
1999 if ( is_array( $wgUrlProtocols ) ) {
2000 $protocols = array();
2001 foreach ($wgUrlProtocols as $protocol)
2002 $protocols[] = preg_quote( $protocol, '/' );
2003
2004 return implode( '|', $protocols );
2005 } else {
2006 return $wgUrlProtocols;
2007 }
2008 }
2009
2010 /**
2011 * Safety wrapper around ini_get() for boolean settings.
2012 * The values returned from ini_get() are pre-normalized for settings
2013 * set via php.ini or php_flag/php_admin_flag... but *not*
2014 * for those set via php_value/php_admin_value.
2015 *
2016 * It's fairly common for people to use php_value instead of php_flag,
2017 * which can leave you with an 'off' setting giving a false positive
2018 * for code that just takes the ini_get() return value as a boolean.
2019 *
2020 * To make things extra interesting, setting via php_value accepts
2021 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2022 * Unrecognized values go false... again opposite PHP's own coercion
2023 * from string to bool.
2024 *
2025 * Luckily, 'properly' set settings will always come back as '0' or '1',
2026 * so we only have to worry about them and the 'improper' settings.
2027 *
2028 * I frickin' hate PHP... :P
2029 *
2030 * @param string $setting
2031 * @return bool
2032 */
2033 function wfIniGetBool( $setting ) {
2034 $val = ini_get( $setting );
2035 // 'on' and 'true' can't have whitespace around them, but '1' can.
2036 return strtolower( $val ) == 'on'
2037 || strtolower( $val ) == 'true'
2038 || strtolower( $val ) == 'yes'
2039 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2040 }
2041
2042 /**
2043 * Execute a shell command, with time and memory limits mirrored from the PHP
2044 * configuration if supported.
2045 * @param $cmd Command line, properly escaped for shell.
2046 * @param &$retval optional, will receive the program's exit code.
2047 * (non-zero is usually failure)
2048 * @return collected stdout as a string (trailing newlines stripped)
2049 */
2050 function wfShellExec( $cmd, &$retval=null ) {
2051 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2052
2053 if( wfIniGetBool( 'safe_mode' ) ) {
2054 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2055 $retval = 1;
2056 return "Unable to run external programs in safe mode.";
2057 }
2058
2059 if ( php_uname( 's' ) == 'Linux' ) {
2060 $time = intval( ini_get( 'max_execution_time' ) );
2061 $mem = intval( $wgMaxShellMemory );
2062 $filesize = intval( $wgMaxShellFileSize );
2063
2064 if ( $time > 0 && $mem > 0 ) {
2065 $script = "$IP/bin/ulimit4.sh";
2066 if ( is_executable( $script ) ) {
2067 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2068 }
2069 }
2070 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2071 # This is a hack to work around PHP's flawed invocation of cmd.exe
2072 # http://news.php.net/php.internals/21796
2073 $cmd = '"' . $cmd . '"';
2074 }
2075 wfDebug( "wfShellExec: $cmd\n" );
2076
2077 $retval = 1; // error by default?
2078 ob_start();
2079 passthru( $cmd, $retval );
2080 $output = ob_get_contents();
2081 ob_end_clean();
2082 return $output;
2083
2084 }
2085
2086 /**
2087 * This function works like "use VERSION" in Perl, the program will die with a
2088 * backtrace if the current version of PHP is less than the version provided
2089 *
2090 * This is useful for extensions which due to their nature are not kept in sync
2091 * with releases, and might depend on other versions of PHP than the main code
2092 *
2093 * Note: PHP might die due to parsing errors in some cases before it ever
2094 * manages to call this function, such is life
2095 *
2096 * @see perldoc -f use
2097 *
2098 * @param mixed $version The version to check, can be a string, an integer, or
2099 * a float
2100 */
2101 function wfUsePHP( $req_ver ) {
2102 $php_ver = PHP_VERSION;
2103
2104 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2105 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2106 }
2107
2108 /**
2109 * This function works like "use VERSION" in Perl except it checks the version
2110 * of MediaWiki, the program will die with a backtrace if the current version
2111 * of MediaWiki is less than the version provided.
2112 *
2113 * This is useful for extensions which due to their nature are not kept in sync
2114 * with releases
2115 *
2116 * @see perldoc -f use
2117 *
2118 * @param mixed $version The version to check, can be a string, an integer, or
2119 * a float
2120 */
2121 function wfUseMW( $req_ver ) {
2122 global $wgVersion;
2123
2124 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2125 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2126 }
2127
2128 /**
2129 * @deprecated use StringUtils::escapeRegexReplacement
2130 */
2131 function wfRegexReplacement( $string ) {
2132 return StringUtils::escapeRegexReplacement( $string );
2133 }
2134
2135 /**
2136 * Return the final portion of a pathname.
2137 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2138 * http://bugs.php.net/bug.php?id=33898
2139 *
2140 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2141 * We'll consider it so always, as we don't want \s in our Unix paths either.
2142 *
2143 * @param string $path
2144 * @param string $suffix to remove if present
2145 * @return string
2146 */
2147 function wfBaseName( $path, $suffix='' ) {
2148 $encSuffix = ($suffix == '')
2149 ? ''
2150 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2151 $matches = array();
2152 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2153 return $matches[1];
2154 } else {
2155 return '';
2156 }
2157 }
2158
2159 /**
2160 * Generate a relative path name to the given file.
2161 * May explode on non-matching case-insensitive paths,
2162 * funky symlinks, etc.
2163 *
2164 * @param string $path Absolute destination path including target filename
2165 * @param string $from Absolute source path, directory only
2166 * @return string
2167 */
2168 function wfRelativePath( $path, $from ) {
2169 // Normalize mixed input on Windows...
2170 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2171 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2172
2173 // Trim trailing slashes -- fix for drive root
2174 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2175 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2176
2177 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2178 $against = explode( DIRECTORY_SEPARATOR, $from );
2179
2180 if( $pieces[0] !== $against[0] ) {
2181 // Non-matching Windows drive letters?
2182 // Return a full path.
2183 return $path;
2184 }
2185
2186 // Trim off common prefix
2187 while( count( $pieces ) && count( $against )
2188 && $pieces[0] == $against[0] ) {
2189 array_shift( $pieces );
2190 array_shift( $against );
2191 }
2192
2193 // relative dots to bump us to the parent
2194 while( count( $against ) ) {
2195 array_unshift( $pieces, '..' );
2196 array_shift( $against );
2197 }
2198
2199 array_push( $pieces, wfBaseName( $path ) );
2200
2201 return implode( DIRECTORY_SEPARATOR, $pieces );
2202 }
2203
2204 /**
2205 * array_merge() does awful things with "numeric" indexes, including
2206 * string indexes when happen to look like integers. When we want
2207 * to merge arrays with arbitrary string indexes, we don't want our
2208 * arrays to be randomly corrupted just because some of them consist
2209 * of numbers.
2210 *
2211 * Fuck you, PHP. Fuck you in the ear!
2212 *
2213 * @param array $array1, [$array2, [...]]
2214 * @return array
2215 */
2216 function wfArrayMerge( $array1/* ... */ ) {
2217 $out = $array1;
2218 for( $i = 1; $i < func_num_args(); $i++ ) {
2219 foreach( func_get_arg( $i ) as $key => $value ) {
2220 $out[$key] = $value;
2221 }
2222 }
2223 return $out;
2224 }
2225
2226 /**
2227 * Make a URL index, appropriate for the el_index field of externallinks.
2228 */
2229 function wfMakeUrlIndex( $url ) {
2230 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2231 wfSuppressWarnings();
2232 $bits = parse_url( $url );
2233 wfRestoreWarnings();
2234 if ( !$bits ) {
2235 return false;
2236 }
2237 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2238 $delimiter = '';
2239 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2240 $delimiter = '://';
2241 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2242 $delimiter = ':';
2243 // parse_url detects for news: and mailto: the host part of an url as path
2244 // We have to correct this wrong detection
2245 if ( isset ( $bits['path'] ) ) {
2246 $bits['host'] = $bits['path'];
2247 $bits['path'] = '';
2248 }
2249 } else {
2250 return false;
2251 }
2252
2253 // Reverse the labels in the hostname, convert to lower case
2254 // For emails reverse domainpart only
2255 if ( $bits['scheme'] == 'mailto' ) {
2256 $mailparts = explode( '@', $bits['host'], 2 );
2257 if ( count($mailparts) === 2 ) {
2258 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2259 } else {
2260 // No domain specified, don't mangle it
2261 $domainpart = '';
2262 }
2263 $reversedHost = $domainpart . '@' . $mailparts[0];
2264 } else {
2265 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2266 }
2267 // Add an extra dot to the end
2268 // Why? Is it in wrong place in mailto links?
2269 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2270 $reversedHost .= '.';
2271 }
2272 // Reconstruct the pseudo-URL
2273 $prot = $bits['scheme'];
2274 $index = "$prot$delimiter$reversedHost";
2275 // Leave out user and password. Add the port, path, query and fragment
2276 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2277 if ( isset( $bits['path'] ) ) {
2278 $index .= $bits['path'];
2279 } else {
2280 $index .= '/';
2281 }
2282 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2283 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2284 return $index;
2285 }
2286
2287 /**
2288 * Do any deferred updates and clear the list
2289 * TODO: This could be in Wiki.php if that class made any sense at all
2290 */
2291 function wfDoUpdates()
2292 {
2293 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2294 foreach ( $wgDeferredUpdateList as $update ) {
2295 $update->doUpdate();
2296 }
2297 foreach ( $wgPostCommitUpdateList as $update ) {
2298 $update->doUpdate();
2299 }
2300 $wgDeferredUpdateList = array();
2301 $wgPostCommitUpdateList = array();
2302 }
2303
2304 /**
2305 * @deprecated use StringUtils::explodeMarkup
2306 */
2307 function wfExplodeMarkup( $separator, $text ) {
2308 return StringUtils::explodeMarkup( $separator, $text );
2309 }
2310
2311 /**
2312 * Convert an arbitrarily-long digit string from one numeric base
2313 * to another, optionally zero-padding to a minimum column width.
2314 *
2315 * Supports base 2 through 36; digit values 10-36 are represented
2316 * as lowercase letters a-z. Input is case-insensitive.
2317 *
2318 * @param $input string of digits
2319 * @param $sourceBase int 2-36
2320 * @param $destBase int 2-36
2321 * @param $pad int 1 or greater
2322 * @param $lowercase bool
2323 * @return string or false on invalid input
2324 */
2325 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2326 $input = strval( $input );
2327 if( $sourceBase < 2 ||
2328 $sourceBase > 36 ||
2329 $destBase < 2 ||
2330 $destBase > 36 ||
2331 $pad < 1 ||
2332 $sourceBase != intval( $sourceBase ) ||
2333 $destBase != intval( $destBase ) ||
2334 $pad != intval( $pad ) ||
2335 !is_string( $input ) ||
2336 $input == '' ) {
2337 return false;
2338 }
2339 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2340 $inDigits = array();
2341 $outChars = '';
2342
2343 // Decode and validate input string
2344 $input = strtolower( $input );
2345 for( $i = 0; $i < strlen( $input ); $i++ ) {
2346 $n = strpos( $digitChars, $input{$i} );
2347 if( $n === false || $n > $sourceBase ) {
2348 return false;
2349 }
2350 $inDigits[] = $n;
2351 }
2352
2353 // Iterate over the input, modulo-ing out an output digit
2354 // at a time until input is gone.
2355 while( count( $inDigits ) ) {
2356 $work = 0;
2357 $workDigits = array();
2358
2359 // Long division...
2360 foreach( $inDigits as $digit ) {
2361 $work *= $sourceBase;
2362 $work += $digit;
2363
2364 if( $work < $destBase ) {
2365 // Gonna need to pull another digit.
2366 if( count( $workDigits ) ) {
2367 // Avoid zero-padding; this lets us find
2368 // the end of the input very easily when
2369 // length drops to zero.
2370 $workDigits[] = 0;
2371 }
2372 } else {
2373 // Finally! Actual division!
2374 $workDigits[] = intval( $work / $destBase );
2375
2376 // Isn't it annoying that most programming languages
2377 // don't have a single divide-and-remainder operator,
2378 // even though the CPU implements it that way?
2379 $work = $work % $destBase;
2380 }
2381 }
2382
2383 // All that division leaves us with a remainder,
2384 // which is conveniently our next output digit.
2385 $outChars .= $digitChars[$work];
2386
2387 // And we continue!
2388 $inDigits = $workDigits;
2389 }
2390
2391 while( strlen( $outChars ) < $pad ) {
2392 $outChars .= '0';
2393 }
2394
2395 return strrev( $outChars );
2396 }
2397
2398 /**
2399 * Create an object with a given name and an array of construct parameters
2400 * @param string $name
2401 * @param array $p parameters
2402 */
2403 function wfCreateObject( $name, $p ){
2404 $p = array_values( $p );
2405 switch ( count( $p ) ) {
2406 case 0:
2407 return new $name;
2408 case 1:
2409 return new $name( $p[0] );
2410 case 2:
2411 return new $name( $p[0], $p[1] );
2412 case 3:
2413 return new $name( $p[0], $p[1], $p[2] );
2414 case 4:
2415 return new $name( $p[0], $p[1], $p[2], $p[3] );
2416 case 5:
2417 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2418 case 6:
2419 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2420 default:
2421 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2422 }
2423 }
2424
2425 /**
2426 * Alias for modularized function
2427 * @deprecated Use Http::get() instead
2428 */
2429 function wfGetHTTP( $url, $timeout = 'default' ) {
2430 wfDeprecated(__FUNCTION__);
2431 return Http::get( $url, $timeout );
2432 }
2433
2434 /**
2435 * Alias for modularized function
2436 * @deprecated Use Http::isLocalURL() instead
2437 */
2438 function wfIsLocalURL( $url ) {
2439 wfDeprecated(__FUNCTION__);
2440 return Http::isLocalURL( $url );
2441 }
2442
2443 function wfHttpOnlySafe() {
2444 global $wgHttpOnlyBlacklist;
2445 if( !version_compare("5.2", PHP_VERSION, "<") )
2446 return false;
2447
2448 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2449 foreach( $wgHttpOnlyBlacklist as $regex ) {
2450 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2451 return false;
2452 }
2453 }
2454 }
2455
2456 return true;
2457 }
2458
2459 /**
2460 * Initialise php session
2461 */
2462 function wfSetupSession() {
2463 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2464 if( $wgSessionsInMemcached ) {
2465 require_once( 'MemcachedSessions.php' );
2466 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2467 # If it's left on 'user' or another setting from another
2468 # application, it will end up failing. Try to recover.
2469 ini_set ( 'session.save_handler', 'files' );
2470 }
2471 $httpOnlySafe = wfHttpOnlySafe();
2472 wfDebugLog( 'cookie',
2473 'session_set_cookie_params: "' . implode( '", "',
2474 array(
2475 0,
2476 $wgCookiePath,
2477 $wgCookieDomain,
2478 $wgCookieSecure,
2479 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2480 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2481 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2482 } else {
2483 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2484 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2485 }
2486 session_cache_limiter( 'private, must-revalidate' );
2487 wfSuppressWarnings();
2488 session_start();
2489 wfRestoreWarnings();
2490 }
2491
2492 /**
2493 * Get an object from the precompiled serialized directory
2494 *
2495 * @return mixed The variable on success, false on failure
2496 */
2497 function wfGetPrecompiledData( $name ) {
2498 global $IP;
2499
2500 $file = "$IP/serialized/$name";
2501 if ( file_exists( $file ) ) {
2502 $blob = file_get_contents( $file );
2503 if ( $blob ) {
2504 return unserialize( $blob );
2505 }
2506 }
2507 return false;
2508 }
2509
2510 function wfGetCaller( $level = 2 ) {
2511 $backtrace = wfDebugBacktrace();
2512 if ( isset( $backtrace[$level] ) ) {
2513 return wfFormatStackFrame($backtrace[$level]);
2514 } else {
2515 $caller = 'unknown';
2516 }
2517 return $caller;
2518 }
2519
2520 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2521 function wfGetAllCallers() {
2522 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2523 }
2524
2525 /** Return a string representation of frame */
2526 function wfFormatStackFrame($frame) {
2527 return isset( $frame["class"] )?
2528 $frame["class"]."::".$frame["function"]:
2529 $frame["function"];
2530 }
2531
2532 /**
2533 * Get a cache key
2534 */
2535 function wfMemcKey( /*... */ ) {
2536 $args = func_get_args();
2537 $key = wfWikiID() . ':' . implode( ':', $args );
2538 return $key;
2539 }
2540
2541 /**
2542 * Get a cache key for a foreign DB
2543 */
2544 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2545 $args = array_slice( func_get_args(), 2 );
2546 if ( $prefix ) {
2547 $key = "$db-$prefix:" . implode( ':', $args );
2548 } else {
2549 $key = $db . ':' . implode( ':', $args );
2550 }
2551 return $key;
2552 }
2553
2554 /**
2555 * Get an ASCII string identifying this wiki
2556 * This is used as a prefix in memcached keys
2557 */
2558 function wfWikiID( $db = null ) {
2559 if( $db instanceof Database ) {
2560 return $db->getWikiID();
2561 } else {
2562 global $wgDBprefix, $wgDBname;
2563 if ( $wgDBprefix ) {
2564 return "$wgDBname-$wgDBprefix";
2565 } else {
2566 return $wgDBname;
2567 }
2568 }
2569 }
2570
2571 /**
2572 * Split a wiki ID into DB name and table prefix
2573 */
2574 function wfSplitWikiID( $wiki ) {
2575 $bits = explode( '-', $wiki, 2 );
2576 if ( count( $bits ) < 2 ) {
2577 $bits[] = '';
2578 }
2579 return $bits;
2580 }
2581
2582 /*
2583 * Get a Database object.
2584 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2585 * master (for write queries), DB_SLAVE for potentially lagged
2586 * read queries, or an integer >= 0 for a particular server.
2587 *
2588 * @param mixed $groups Query groups. An array of group names that this query
2589 * belongs to. May contain a single string if the query is only
2590 * in one group.
2591 *
2592 * @param string $wiki The wiki ID, or false for the current wiki
2593 *
2594 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2595 * will always return the same object, unless the underlying connection or load
2596 * balancer is manually destroyed.
2597 */
2598 function &wfGetDB( $db = DB_LAST, $groups = array(), $wiki = false ) {
2599 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2600 }
2601
2602 /**
2603 * Get a load balancer object.
2604 *
2605 * @param array $groups List of query groups
2606 * @param string $wiki Wiki ID, or false for the current wiki
2607 * @return LoadBalancer
2608 */
2609 function wfGetLB( $wiki = false ) {
2610 return wfGetLBFactory()->getMainLB( $wiki );
2611 }
2612
2613 /**
2614 * Get the load balancer factory object
2615 */
2616 function &wfGetLBFactory() {
2617 return LBFactory::singleton();
2618 }
2619
2620 /**
2621 * Find a file.
2622 * Shortcut for RepoGroup::singleton()->findFile()
2623 * @param mixed $title Title object or string. May be interwiki.
2624 * @param mixed $time Requested time for an archived image, or false for the
2625 * current version. An image object will be returned which
2626 * was created at the specified time.
2627 * @param mixed $flags FileRepo::FIND_ flags
2628 * @return File, or false if the file does not exist
2629 */
2630 function wfFindFile( $title, $time = false, $flags = 0 ) {
2631 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2632 }
2633
2634 /**
2635 * Get an object referring to a locally registered file.
2636 * Returns a valid placeholder object if the file does not exist.
2637 */
2638 function wfLocalFile( $title ) {
2639 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2640 }
2641
2642 /**
2643 * Should low-performance queries be disabled?
2644 *
2645 * @return bool
2646 */
2647 function wfQueriesMustScale() {
2648 global $wgMiserMode;
2649 return $wgMiserMode
2650 || ( SiteStats::pages() > 100000
2651 && SiteStats::edits() > 1000000
2652 && SiteStats::users() > 10000 );
2653 }
2654
2655 /**
2656 * Get the path to a specified script file, respecting file
2657 * extensions; this is a wrapper around $wgScriptExtension etc.
2658 *
2659 * @param string $script Script filename, sans extension
2660 * @return string
2661 */
2662 function wfScript( $script = 'index' ) {
2663 global $wgScriptPath, $wgScriptExtension;
2664 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2665 }
2666
2667 /**
2668 * Convenience function converts boolean values into "true"
2669 * or "false" (string) values
2670 *
2671 * @param bool $value
2672 * @return string
2673 */
2674 function wfBoolToStr( $value ) {
2675 return $value ? 'true' : 'false';
2676 }
2677
2678 /**
2679 * Load an extension messages file
2680 *
2681 * @param string $extensionName Name of extension to load messages from\for.
2682 * @param string $langcode Language to load messages for, or false for default
2683 * behvaiour (en, content language and user language).
2684 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2685 * on MediaWiki prior to that
2686 */
2687 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2688 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2689
2690 #For recording whether extension message files have been loaded in a given language.
2691 static $loaded = array();
2692
2693 if( !array_key_exists( $extensionName, $loaded ) ) {
2694 $loaded[$extensionName] = array();
2695 }
2696
2697 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2698 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2699 }
2700
2701 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2702 # Just do en, content language and user language.
2703 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2704 # Mark that they have been loaded.
2705 $loaded[$extensionName]['en'] = true;
2706 $loaded[$extensionName][$wgLang->getCode()] = true;
2707 $loaded[$extensionName][$wgContLang->getCode()] = true;
2708 # Mark that this part has been done to avoid weird if statements.
2709 $loaded[$extensionName]['*'] = true;
2710 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2711 # Load messages for specified language.
2712 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2713 # Mark that they have been loaded.
2714 $loaded[$extensionName][$langcode] = true;
2715 }
2716 }
2717
2718 /**
2719 * Get a platform-independent path to the null file, e.g.
2720 * /dev/null
2721 *
2722 * @return string
2723 */
2724 function wfGetNull() {
2725 return wfIsWindows()
2726 ? 'NUL'
2727 : '/dev/null';
2728 }
2729
2730 /**
2731 * Displays a maxlag error
2732 *
2733 * @param string $host Server that lags the most
2734 * @param int $lag Maxlag (actual)
2735 * @param int $maxLag Maxlag (requested)
2736 */
2737 function wfMaxlagError( $host, $lag, $maxLag ) {
2738 global $wgShowHostnames;
2739 header( 'HTTP/1.1 503 Service Unavailable' );
2740 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2741 header( 'X-Database-Lag: ' . intval( $lag ) );
2742 header( 'Content-Type: text/plain' );
2743 if( $wgShowHostnames ) {
2744 echo "Waiting for $host: $lag seconds lagged\n";
2745 } else {
2746 echo "Waiting for a database server: $lag seconds lagged\n";
2747 }
2748 }
2749
2750 /**
2751 * Throws an E_USER_NOTICE saying that $function is deprecated
2752 * @param string $function
2753 * @return null
2754 */
2755 function wfDeprecated( $function ) {
2756 global $wgDebugLogFile;
2757 if ( !$wgDebugLogFile ) {
2758 return;
2759 }
2760 $callers = wfDebugBacktrace();
2761 if( isset( $callers[2] ) ){
2762 $callerfunc = $callers[2];
2763 $callerfile = $callers[1];
2764 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2765 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2766 } else {
2767 $file = '(internal function)';
2768 }
2769 $func = '';
2770 if( isset( $callerfunc['class'] ) )
2771 $func .= $callerfunc['class'] . '::';
2772 $func .= @$callerfunc['function'];
2773 $msg = "Use of $function is deprecated. Called from $func in $file";
2774 } else {
2775 $msg = "Use of $function is deprecated.";
2776 }
2777 wfDebug( "$msg\n" );
2778 }
2779
2780 /**
2781 * Sleep until the worst slave's replication lag is less than or equal to
2782 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2783 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2784 * a no-op if there are no slaves.
2785 *
2786 * Every time the function has to wait for a slave, it will print a message to
2787 * that effect (and then sleep for a little while), so it's probably not best
2788 * to use this outside maintenance scripts in its present form.
2789 *
2790 * @param int $maxLag
2791 * @return null
2792 */
2793 function wfWaitForSlaves( $maxLag ) {
2794 if( $maxLag ) {
2795 $lb = wfGetLB();
2796 list( $host, $lag ) = $lb->getMaxLag();
2797 while( $lag > $maxLag ) {
2798 $name = @gethostbyaddr( $host );
2799 if( $name !== false ) {
2800 $host = $name;
2801 }
2802 print "Waiting for $host (lagged $lag seconds)...\n";
2803 sleep($maxLag);
2804 list( $host, $lag ) = $lb->getMaxLag();
2805 }
2806 }
2807 }
2808
2809 /** Generate a random 32-character hexadecimal token.
2810 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2811 */
2812 function wfGenerateToken( $salt = '' ) {
2813 $salt = serialize($salt);
2814
2815 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2816 }
2817
2818 /**
2819 * Replace all invalid characters with -
2820 * @param mixed $title Filename to process
2821 */
2822 function wfStripIllegalFilenameChars( $name ) {
2823 $name = wfBaseName( $name );
2824 $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
2825 return $name;
2826 }