Last commit contained errors. Revert most of it, keep only the tweaks to link()...
[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 * Append a query string to an existing URL, which may or may not already
1060 * have query string parameters already. If so, they will be combined.
1061 *
1062 * @param string $url
1063 * @param string $query
1064 * @return string
1065 */
1066 function wfAppendQuery( $url, $query ) {
1067 if( $query != '' ) {
1068 if( false === strpos( $url, '?' ) ) {
1069 $url .= '?';
1070 } else {
1071 $url .= '&';
1072 }
1073 $url .= $query;
1074 }
1075 return $url;
1076 }
1077
1078 /**
1079 * Expand a potentially local URL to a fully-qualified URL.
1080 * Assumes $wgServer is correct. :)
1081 * @param string $url, either fully-qualified or a local path + query
1082 * @return string Fully-qualified URL
1083 */
1084 function wfExpandUrl( $url ) {
1085 if( substr( $url, 0, 1 ) == '/' ) {
1086 global $wgServer;
1087 return $wgServer . $url;
1088 } else {
1089 return $url;
1090 }
1091 }
1092
1093 /**
1094 * This is obsolete, use SquidUpdate::purge()
1095 * @deprecated
1096 */
1097 function wfPurgeSquidServers ($urlArr) {
1098 SquidUpdate::purge( $urlArr );
1099 }
1100
1101 /**
1102 * Windows-compatible version of escapeshellarg()
1103 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1104 * function puts single quotes in regardless of OS
1105 */
1106 function wfEscapeShellArg( ) {
1107 $args = func_get_args();
1108 $first = true;
1109 $retVal = '';
1110 foreach ( $args as $arg ) {
1111 if ( !$first ) {
1112 $retVal .= ' ';
1113 } else {
1114 $first = false;
1115 }
1116
1117 if ( wfIsWindows() ) {
1118 // Escaping for an MSVC-style command line parser
1119 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1120 // Double the backslashes before any double quotes. Escape the double quotes.
1121 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1122 $arg = '';
1123 $delim = false;
1124 foreach ( $tokens as $token ) {
1125 if ( $delim ) {
1126 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1127 } else {
1128 $arg .= $token;
1129 }
1130 $delim = !$delim;
1131 }
1132 // Double the backslashes before the end of the string, because
1133 // we will soon add a quote
1134 $m = array();
1135 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1136 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1137 }
1138
1139 // Add surrounding quotes
1140 $retVal .= '"' . $arg . '"';
1141 } else {
1142 $retVal .= escapeshellarg( $arg );
1143 }
1144 }
1145 return $retVal;
1146 }
1147
1148 /**
1149 * wfMerge attempts to merge differences between three texts.
1150 * Returns true for a clean merge and false for failure or a conflict.
1151 */
1152 function wfMerge( $old, $mine, $yours, &$result ){
1153 global $wgDiff3;
1154
1155 # This check may also protect against code injection in
1156 # case of broken installations.
1157 if(! file_exists( $wgDiff3 ) ){
1158 wfDebug( "diff3 not found\n" );
1159 return false;
1160 }
1161
1162 # Make temporary files
1163 $td = wfTempDir();
1164 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1165 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1166 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1167
1168 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1169 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1170 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1171
1172 # Check for a conflict
1173 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1174 wfEscapeShellArg( $mytextName ) . ' ' .
1175 wfEscapeShellArg( $oldtextName ) . ' ' .
1176 wfEscapeShellArg( $yourtextName );
1177 $handle = popen( $cmd, 'r' );
1178
1179 if( fgets( $handle, 1024 ) ){
1180 $conflict = true;
1181 } else {
1182 $conflict = false;
1183 }
1184 pclose( $handle );
1185
1186 # Merge differences
1187 $cmd = $wgDiff3 . ' -a -e --merge ' .
1188 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1189 $handle = popen( $cmd, 'r' );
1190 $result = '';
1191 do {
1192 $data = fread( $handle, 8192 );
1193 if ( strlen( $data ) == 0 ) {
1194 break;
1195 }
1196 $result .= $data;
1197 } while ( true );
1198 pclose( $handle );
1199 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1200
1201 if ( $result === '' && $old !== '' && $conflict == false ) {
1202 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1203 $conflict = true;
1204 }
1205 return ! $conflict;
1206 }
1207
1208 /**
1209 * Returns unified plain-text diff of two texts.
1210 * Useful for machine processing of diffs.
1211 * @param $before string The text before the changes.
1212 * @param $after string The text after the changes.
1213 * @param $params string Command-line options for the diff command.
1214 * @return string Unified diff of $before and $after
1215 */
1216 function wfDiff( $before, $after, $params = '-u' ) {
1217 global $wgDiff;
1218
1219 # This check may also protect against code injection in
1220 # case of broken installations.
1221 if( !file_exists( $wgDiff ) ){
1222 wfDebug( "diff executable not found\n" );
1223 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1224 $format = new UnifiedDiffFormatter();
1225 return $format->format( $diffs );
1226 }
1227
1228 # Make temporary files
1229 $td = wfTempDir();
1230 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1231 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1232
1233 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1234 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1235
1236 // Get the diff of the two files
1237 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1238
1239 $h = popen( $cmd, 'r' );
1240
1241 $diff = '';
1242
1243 do {
1244 $data = fread( $h, 8192 );
1245 if ( strlen( $data ) == 0 ) {
1246 break;
1247 }
1248 $diff .= $data;
1249 } while ( true );
1250
1251 // Clean up
1252 pclose( $h );
1253 unlink( $oldtextName );
1254 unlink( $newtextName );
1255
1256 // Kill the --- and +++ lines. They're not useful.
1257 $diff_lines = explode( "\n", $diff );
1258 if (strpos( $diff_lines[0], '---' ) === 0) {
1259 unset($diff_lines[0]);
1260 }
1261 if (strpos( $diff_lines[1], '+++' ) === 0) {
1262 unset($diff_lines[1]);
1263 }
1264
1265 $diff = implode( "\n", $diff_lines );
1266
1267 return $diff;
1268 }
1269
1270 /**
1271 * @todo document
1272 */
1273 function wfVarDump( $var ) {
1274 global $wgOut;
1275 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1276 if ( headers_sent() || !@is_object( $wgOut ) ) {
1277 print $s;
1278 } else {
1279 $wgOut->addHTML( $s );
1280 }
1281 }
1282
1283 /**
1284 * Provide a simple HTTP error.
1285 */
1286 function wfHttpError( $code, $label, $desc ) {
1287 global $wgOut;
1288 $wgOut->disable();
1289 header( "HTTP/1.0 $code $label" );
1290 header( "Status: $code $label" );
1291 $wgOut->sendCacheControl();
1292
1293 header( 'Content-type: text/html; charset=utf-8' );
1294 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1295 "<html><head><title>" .
1296 htmlspecialchars( $label ) .
1297 "</title></head><body><h1>" .
1298 htmlspecialchars( $label ) .
1299 "</h1><p>" .
1300 nl2br( htmlspecialchars( $desc ) ) .
1301 "</p></body></html>\n";
1302 }
1303
1304 /**
1305 * Clear away any user-level output buffers, discarding contents.
1306 *
1307 * Suitable for 'starting afresh', for instance when streaming
1308 * relatively large amounts of data without buffering, or wanting to
1309 * output image files without ob_gzhandler's compression.
1310 *
1311 * The optional $resetGzipEncoding parameter controls suppression of
1312 * the Content-Encoding header sent by ob_gzhandler; by default it
1313 * is left. See comments for wfClearOutputBuffers() for why it would
1314 * be used.
1315 *
1316 * Note that some PHP configuration options may add output buffer
1317 * layers which cannot be removed; these are left in place.
1318 *
1319 * @param bool $resetGzipEncoding
1320 */
1321 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1322 if( $resetGzipEncoding ) {
1323 // Suppress Content-Encoding and Content-Length
1324 // headers from 1.10+s wfOutputHandler
1325 global $wgDisableOutputCompression;
1326 $wgDisableOutputCompression = true;
1327 }
1328 while( $status = ob_get_status() ) {
1329 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1330 // Probably from zlib.output_compression or other
1331 // PHP-internal setting which can't be removed.
1332 //
1333 // Give up, and hope the result doesn't break
1334 // output behavior.
1335 break;
1336 }
1337 if( !ob_end_clean() ) {
1338 // Could not remove output buffer handler; abort now
1339 // to avoid getting in some kind of infinite loop.
1340 break;
1341 }
1342 if( $resetGzipEncoding ) {
1343 if( $status['name'] == 'ob_gzhandler' ) {
1344 // Reset the 'Content-Encoding' field set by this handler
1345 // so we can start fresh.
1346 header( 'Content-Encoding:' );
1347 }
1348 }
1349 }
1350 }
1351
1352 /**
1353 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1354 *
1355 * Clear away output buffers, but keep the Content-Encoding header
1356 * produced by ob_gzhandler, if any.
1357 *
1358 * This should be used for HTTP 304 responses, where you need to
1359 * preserve the Content-Encoding header of the real result, but
1360 * also need to suppress the output of ob_gzhandler to keep to spec
1361 * and avoid breaking Firefox in rare cases where the headers and
1362 * body are broken over two packets.
1363 */
1364 function wfClearOutputBuffers() {
1365 wfResetOutputBuffers( false );
1366 }
1367
1368 /**
1369 * Converts an Accept-* header into an array mapping string values to quality
1370 * factors
1371 */
1372 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1373 # No arg means accept anything (per HTTP spec)
1374 if( !$accept ) {
1375 return array( $def => 1.0 );
1376 }
1377
1378 $prefs = array();
1379
1380 $parts = explode( ',', $accept );
1381
1382 foreach( $parts as $part ) {
1383 # FIXME: doesn't deal with params like 'text/html; level=1'
1384 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1385 $match = array();
1386 if( !isset( $qpart ) ) {
1387 $prefs[$value] = 1.0;
1388 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1389 $prefs[$value] = floatval($match[1]);
1390 }
1391 }
1392
1393 return $prefs;
1394 }
1395
1396 /**
1397 * Checks if a given MIME type matches any of the keys in the given
1398 * array. Basic wildcards are accepted in the array keys.
1399 *
1400 * Returns the matching MIME type (or wildcard) if a match, otherwise
1401 * NULL if no match.
1402 *
1403 * @param string $type
1404 * @param array $avail
1405 * @return string
1406 * @private
1407 */
1408 function mimeTypeMatch( $type, $avail ) {
1409 if( array_key_exists($type, $avail) ) {
1410 return $type;
1411 } else {
1412 $parts = explode( '/', $type );
1413 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1414 return $parts[0] . '/*';
1415 } elseif( array_key_exists( '*/*', $avail ) ) {
1416 return '*/*';
1417 } else {
1418 return NULL;
1419 }
1420 }
1421 }
1422
1423 /**
1424 * Returns the 'best' match between a client's requested internet media types
1425 * and the server's list of available types. Each list should be an associative
1426 * array of type to preference (preference is a float between 0.0 and 1.0).
1427 * Wildcards in the types are acceptable.
1428 *
1429 * @param array $cprefs Client's acceptable type list
1430 * @param array $sprefs Server's offered types
1431 * @return string
1432 *
1433 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1434 * XXX: generalize to negotiate other stuff
1435 */
1436 function wfNegotiateType( $cprefs, $sprefs ) {
1437 $combine = array();
1438
1439 foreach( array_keys($sprefs) as $type ) {
1440 $parts = explode( '/', $type );
1441 if( $parts[1] != '*' ) {
1442 $ckey = mimeTypeMatch( $type, $cprefs );
1443 if( $ckey ) {
1444 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1445 }
1446 }
1447 }
1448
1449 foreach( array_keys( $cprefs ) as $type ) {
1450 $parts = explode( '/', $type );
1451 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1452 $skey = mimeTypeMatch( $type, $sprefs );
1453 if( $skey ) {
1454 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1455 }
1456 }
1457 }
1458
1459 $bestq = 0;
1460 $besttype = NULL;
1461
1462 foreach( array_keys( $combine ) as $type ) {
1463 if( $combine[$type] > $bestq ) {
1464 $besttype = $type;
1465 $bestq = $combine[$type];
1466 }
1467 }
1468
1469 return $besttype;
1470 }
1471
1472 /**
1473 * Array lookup
1474 * Returns an array where the values in the first array are replaced by the
1475 * values in the second array with the corresponding keys
1476 *
1477 * @return array
1478 */
1479 function wfArrayLookup( $a, $b ) {
1480 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1481 }
1482
1483 /**
1484 * Convenience function; returns MediaWiki timestamp for the present time.
1485 * @return string
1486 */
1487 function wfTimestampNow() {
1488 # return NOW
1489 return wfTimestamp( TS_MW, time() );
1490 }
1491
1492 /**
1493 * Reference-counted warning suppression
1494 */
1495 function wfSuppressWarnings( $end = false ) {
1496 static $suppressCount = 0;
1497 static $originalLevel = false;
1498
1499 if ( $end ) {
1500 if ( $suppressCount ) {
1501 --$suppressCount;
1502 if ( !$suppressCount ) {
1503 error_reporting( $originalLevel );
1504 }
1505 }
1506 } else {
1507 if ( !$suppressCount ) {
1508 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1509 }
1510 ++$suppressCount;
1511 }
1512 }
1513
1514 /**
1515 * Restore error level to previous value
1516 */
1517 function wfRestoreWarnings() {
1518 wfSuppressWarnings( true );
1519 }
1520
1521 # Autodetect, convert and provide timestamps of various types
1522
1523 /**
1524 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1525 */
1526 define('TS_UNIX', 0);
1527
1528 /**
1529 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1530 */
1531 define('TS_MW', 1);
1532
1533 /**
1534 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1535 */
1536 define('TS_DB', 2);
1537
1538 /**
1539 * RFC 2822 format, for E-mail and HTTP headers
1540 */
1541 define('TS_RFC2822', 3);
1542
1543 /**
1544 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1545 *
1546 * This is used by Special:Export
1547 */
1548 define('TS_ISO_8601', 4);
1549
1550 /**
1551 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1552 *
1553 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1554 * DateTime tag and page 36 for the DateTimeOriginal and
1555 * DateTimeDigitized tags.
1556 */
1557 define('TS_EXIF', 5);
1558
1559 /**
1560 * Oracle format time.
1561 */
1562 define('TS_ORACLE', 6);
1563
1564 /**
1565 * Postgres format time.
1566 */
1567 define('TS_POSTGRES', 7);
1568
1569 /**
1570 * @param mixed $outputtype A timestamp in one of the supported formats, the
1571 * function will autodetect which format is supplied
1572 * and act accordingly.
1573 * @return string Time in the format specified in $outputtype
1574 */
1575 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1576 $uts = 0;
1577 $da = array();
1578 if ($ts==0) {
1579 $uts=time();
1580 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1581 # TS_DB
1582 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1583 # TS_EXIF
1584 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1585 # TS_MW
1586 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1587 # TS_UNIX
1588 $uts = $ts;
1589 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1590 # TS_ORACLE
1591 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1592 str_replace("+00:00", "UTC", $ts)));
1593 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1594 # TS_ISO_8601
1595 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1596 # TS_POSTGRES
1597 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1598 # TS_POSTGRES
1599 } else {
1600 # Bogus value; fall back to the epoch...
1601 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1602 $uts = 0;
1603 }
1604
1605 if (count( $da ) ) {
1606 // Warning! gmmktime() acts oddly if the month or day is set to 0
1607 // We may want to handle that explicitly at some point
1608 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1609 (int)$da[2],(int)$da[3],(int)$da[1]);
1610 }
1611
1612 switch($outputtype) {
1613 case TS_UNIX:
1614 return $uts;
1615 case TS_MW:
1616 return gmdate( 'YmdHis', $uts );
1617 case TS_DB:
1618 return gmdate( 'Y-m-d H:i:s', $uts );
1619 case TS_ISO_8601:
1620 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1621 // This shouldn't ever be used, but is included for completeness
1622 case TS_EXIF:
1623 return gmdate( 'Y:m:d H:i:s', $uts );
1624 case TS_RFC2822:
1625 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1626 case TS_ORACLE:
1627 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1628 case TS_POSTGRES:
1629 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1630 default:
1631 throw new MWException( 'wfTimestamp() called with illegal output type.');
1632 }
1633 }
1634
1635 /**
1636 * Return a formatted timestamp, or null if input is null.
1637 * For dealing with nullable timestamp columns in the database.
1638 * @param int $outputtype
1639 * @param string $ts
1640 * @return string
1641 */
1642 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1643 if( is_null( $ts ) ) {
1644 return null;
1645 } else {
1646 return wfTimestamp( $outputtype, $ts );
1647 }
1648 }
1649
1650 /**
1651 * Check if the operating system is Windows
1652 *
1653 * @return bool True if it's Windows, False otherwise.
1654 */
1655 function wfIsWindows() {
1656 if (substr(php_uname(), 0, 7) == 'Windows') {
1657 return true;
1658 } else {
1659 return false;
1660 }
1661 }
1662
1663 /**
1664 * Swap two variables
1665 */
1666 function swap( &$x, &$y ) {
1667 $z = $x;
1668 $x = $y;
1669 $y = $z;
1670 }
1671
1672 function wfGetCachedNotice( $name ) {
1673 global $wgOut, $parserMemc;
1674 $fname = 'wfGetCachedNotice';
1675 wfProfileIn( $fname );
1676
1677 $needParse = false;
1678
1679 if( $name === 'default' ) {
1680 // special case
1681 global $wgSiteNotice;
1682 $notice = $wgSiteNotice;
1683 if( empty( $notice ) ) {
1684 wfProfileOut( $fname );
1685 return false;
1686 }
1687 } else {
1688 $notice = wfMsgForContentNoTrans( $name );
1689 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1690 wfProfileOut( $fname );
1691 return( false );
1692 }
1693 }
1694
1695 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1696 if( is_array( $cachedNotice ) ) {
1697 if( md5( $notice ) == $cachedNotice['hash'] ) {
1698 $notice = $cachedNotice['html'];
1699 } else {
1700 $needParse = true;
1701 }
1702 } else {
1703 $needParse = true;
1704 }
1705
1706 if( $needParse ) {
1707 if( is_object( $wgOut ) ) {
1708 $parsed = $wgOut->parse( $notice );
1709 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1710 $notice = $parsed;
1711 } else {
1712 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1713 $notice = '';
1714 }
1715 }
1716
1717 wfProfileOut( $fname );
1718 return $notice;
1719 }
1720
1721 function wfGetNamespaceNotice() {
1722 global $wgTitle;
1723
1724 # Paranoia
1725 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1726 return "";
1727
1728 $fname = 'wfGetNamespaceNotice';
1729 wfProfileIn( $fname );
1730
1731 $key = "namespacenotice-" . $wgTitle->getNsText();
1732 $namespaceNotice = wfGetCachedNotice( $key );
1733 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1734 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1735 } else {
1736 $namespaceNotice = "";
1737 }
1738
1739 wfProfileOut( $fname );
1740 return $namespaceNotice;
1741 }
1742
1743 function wfGetSiteNotice() {
1744 global $wgUser, $wgSiteNotice;
1745 $fname = 'wfGetSiteNotice';
1746 wfProfileIn( $fname );
1747 $siteNotice = '';
1748
1749 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1750 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1751 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1752 } else {
1753 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1754 if( !$anonNotice ) {
1755 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1756 } else {
1757 $siteNotice = $anonNotice;
1758 }
1759 }
1760 if( !$siteNotice ) {
1761 $siteNotice = wfGetCachedNotice( 'default' );
1762 }
1763 }
1764
1765 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1766 wfProfileOut( $fname );
1767 return $siteNotice;
1768 }
1769
1770 /**
1771 * BC wrapper for MimeMagic::singleton()
1772 * @deprecated
1773 */
1774 function &wfGetMimeMagic() {
1775 return MimeMagic::singleton();
1776 }
1777
1778 /**
1779 * Tries to get the system directory for temporary files.
1780 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1781 * and if none are set /tmp is returned as the generic Unix default.
1782 *
1783 * NOTE: When possible, use the tempfile() function to create temporary
1784 * files to avoid race conditions on file creation, etc.
1785 *
1786 * @return string
1787 */
1788 function wfTempDir() {
1789 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1790 $tmp = getenv( $var );
1791 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1792 return $tmp;
1793 }
1794 }
1795 # Hope this is Unix of some kind!
1796 return '/tmp';
1797 }
1798
1799 /**
1800 * Make directory, and make all parent directories if they don't exist
1801 *
1802 * @param string $fullDir Full path to directory to create
1803 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1804 * @return bool
1805 */
1806 function wfMkdirParents( $fullDir, $mode = null ) {
1807 global $wgDirectoryMode;
1808 if( strval( $fullDir ) === '' )
1809 return true;
1810 if( file_exists( $fullDir ) )
1811 return true;
1812 // If not defined or isn't an int, set to default
1813 if ( is_null( $mode ) ) {
1814 $mode = $wgDirectoryMode;
1815 }
1816
1817
1818 # Go back through the paths to find the first directory that exists
1819 $currentDir = $fullDir;
1820 $createList = array();
1821 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1822 # Strip trailing slashes
1823 $currentDir = rtrim( $currentDir, '/\\' );
1824
1825 # Add to create list
1826 $createList[] = $currentDir;
1827
1828 # Find next delimiter searching from the end
1829 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1830 if ( $p === false ) {
1831 $currentDir = false;
1832 } else {
1833 $currentDir = substr( $currentDir, 0, $p );
1834 }
1835 }
1836
1837 if ( count( $createList ) == 0 ) {
1838 # Directory specified already exists
1839 return true;
1840 } elseif ( $currentDir === false ) {
1841 # Went all the way back to root and it apparently doesn't exist
1842 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1843 return false;
1844 }
1845 # Now go forward creating directories
1846 $createList = array_reverse( $createList );
1847
1848 # Is the parent directory writable?
1849 if ( $currentDir === '' ) {
1850 $currentDir = '/';
1851 }
1852 if ( !is_writable( $currentDir ) ) {
1853 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1854 return false;
1855 }
1856
1857 foreach ( $createList as $dir ) {
1858 # use chmod to override the umask, as suggested by the PHP manual
1859 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1860 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1861 return false;
1862 }
1863 }
1864 return true;
1865 }
1866
1867 /**
1868 * Increment a statistics counter
1869 */
1870 function wfIncrStats( $key ) {
1871 global $wgStatsMethod;
1872
1873 if( $wgStatsMethod == 'udp' ) {
1874 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1875 static $socket;
1876 if (!$socket) {
1877 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1878 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1879 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1880 }
1881 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1882 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1883 } elseif( $wgStatsMethod == 'cache' ) {
1884 global $wgMemc;
1885 $key = wfMemcKey( 'stats', $key );
1886 if ( is_null( $wgMemc->incr( $key ) ) ) {
1887 $wgMemc->add( $key, 1 );
1888 }
1889 } else {
1890 // Disabled
1891 }
1892 }
1893
1894 /**
1895 * @param mixed $nr The number to format
1896 * @param int $acc The number of digits after the decimal point, default 2
1897 * @param bool $round Whether or not to round the value, default true
1898 * @return float
1899 */
1900 function wfPercent( $nr, $acc = 2, $round = true ) {
1901 $ret = sprintf( "%.${acc}f", $nr );
1902 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1903 }
1904
1905 /**
1906 * Encrypt a username/password.
1907 *
1908 * @param string $userid ID of the user
1909 * @param string $password Password of the user
1910 * @return string Hashed password
1911 * @deprecated Use User::crypt() or User::oldCrypt() instead
1912 */
1913 function wfEncryptPassword( $userid, $password ) {
1914 wfDeprecated(__FUNCTION__);
1915 # Just wrap around User::oldCrypt()
1916 return User::oldCrypt($password, $userid);
1917 }
1918
1919 /**
1920 * Appends to second array if $value differs from that in $default
1921 */
1922 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1923 if ( is_null( $changed ) ) {
1924 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1925 }
1926 if ( $default[$key] !== $value ) {
1927 $changed[$key] = $value;
1928 }
1929 }
1930
1931 /**
1932 * Since wfMsg() and co suck, they don't return false if the message key they
1933 * looked up didn't exist but a XHTML string, this function checks for the
1934 * nonexistance of messages by looking at wfMsg() output
1935 *
1936 * @param $msg The message key looked up
1937 * @param $wfMsgOut The output of wfMsg*()
1938 * @return bool
1939 */
1940 function wfEmptyMsg( $msg, $wfMsgOut ) {
1941 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1942 }
1943
1944 /**
1945 * Find out whether or not a mixed variable exists in a string
1946 *
1947 * @param mixed needle
1948 * @param string haystack
1949 * @return bool
1950 */
1951 function in_string( $needle, $str ) {
1952 return strpos( $str, $needle ) !== false;
1953 }
1954
1955 function wfSpecialList( $page, $details ) {
1956 global $wgContLang;
1957 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1958 return $page . $details;
1959 }
1960
1961 /**
1962 * Returns a regular expression of url protocols
1963 *
1964 * @return string
1965 */
1966 function wfUrlProtocols() {
1967 global $wgUrlProtocols;
1968
1969 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1970 // with LocalSettings files from 1.5
1971 if ( is_array( $wgUrlProtocols ) ) {
1972 $protocols = array();
1973 foreach ($wgUrlProtocols as $protocol)
1974 $protocols[] = preg_quote( $protocol, '/' );
1975
1976 return implode( '|', $protocols );
1977 } else {
1978 return $wgUrlProtocols;
1979 }
1980 }
1981
1982 /**
1983 * Safety wrapper around ini_get() for boolean settings.
1984 * The values returned from ini_get() are pre-normalized for settings
1985 * set via php.ini or php_flag/php_admin_flag... but *not*
1986 * for those set via php_value/php_admin_value.
1987 *
1988 * It's fairly common for people to use php_value instead of php_flag,
1989 * which can leave you with an 'off' setting giving a false positive
1990 * for code that just takes the ini_get() return value as a boolean.
1991 *
1992 * To make things extra interesting, setting via php_value accepts
1993 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1994 * Unrecognized values go false... again opposite PHP's own coercion
1995 * from string to bool.
1996 *
1997 * Luckily, 'properly' set settings will always come back as '0' or '1',
1998 * so we only have to worry about them and the 'improper' settings.
1999 *
2000 * I frickin' hate PHP... :P
2001 *
2002 * @param string $setting
2003 * @return bool
2004 */
2005 function wfIniGetBool( $setting ) {
2006 $val = ini_get( $setting );
2007 // 'on' and 'true' can't have whitespace around them, but '1' can.
2008 return strtolower( $val ) == 'on'
2009 || strtolower( $val ) == 'true'
2010 || strtolower( $val ) == 'yes'
2011 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2012 }
2013
2014 /**
2015 * Execute a shell command, with time and memory limits mirrored from the PHP
2016 * configuration if supported.
2017 * @param $cmd Command line, properly escaped for shell.
2018 * @param &$retval optional, will receive the program's exit code.
2019 * (non-zero is usually failure)
2020 * @return collected stdout as a string (trailing newlines stripped)
2021 */
2022 function wfShellExec( $cmd, &$retval=null ) {
2023 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2024
2025 if( wfIniGetBool( 'safe_mode' ) ) {
2026 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2027 $retval = 1;
2028 return "Unable to run external programs in safe mode.";
2029 }
2030
2031 if ( php_uname( 's' ) == 'Linux' ) {
2032 $time = intval( ini_get( 'max_execution_time' ) );
2033 $mem = intval( $wgMaxShellMemory );
2034 $filesize = intval( $wgMaxShellFileSize );
2035
2036 if ( $time > 0 && $mem > 0 ) {
2037 $script = "$IP/bin/ulimit4.sh";
2038 if ( is_executable( $script ) ) {
2039 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2040 }
2041 }
2042 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2043 # This is a hack to work around PHP's flawed invocation of cmd.exe
2044 # http://news.php.net/php.internals/21796
2045 $cmd = '"' . $cmd . '"';
2046 }
2047 wfDebug( "wfShellExec: $cmd\n" );
2048
2049 $retval = 1; // error by default?
2050 ob_start();
2051 passthru( $cmd, $retval );
2052 $output = ob_get_contents();
2053 ob_end_clean();
2054 return $output;
2055
2056 }
2057
2058 /**
2059 * This function works like "use VERSION" in Perl, the program will die with a
2060 * backtrace if the current version of PHP is less than the version provided
2061 *
2062 * This is useful for extensions which due to their nature are not kept in sync
2063 * with releases, and might depend on other versions of PHP than the main code
2064 *
2065 * Note: PHP might die due to parsing errors in some cases before it ever
2066 * manages to call this function, such is life
2067 *
2068 * @see perldoc -f use
2069 *
2070 * @param mixed $version The version to check, can be a string, an integer, or
2071 * a float
2072 */
2073 function wfUsePHP( $req_ver ) {
2074 $php_ver = PHP_VERSION;
2075
2076 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2077 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2078 }
2079
2080 /**
2081 * This function works like "use VERSION" in Perl except it checks the version
2082 * of MediaWiki, the program will die with a backtrace if the current version
2083 * of MediaWiki is less than the version provided.
2084 *
2085 * This is useful for extensions which due to their nature are not kept in sync
2086 * with releases
2087 *
2088 * @see perldoc -f use
2089 *
2090 * @param mixed $version The version to check, can be a string, an integer, or
2091 * a float
2092 */
2093 function wfUseMW( $req_ver ) {
2094 global $wgVersion;
2095
2096 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2097 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2098 }
2099
2100 /**
2101 * @deprecated use StringUtils::escapeRegexReplacement
2102 */
2103 function wfRegexReplacement( $string ) {
2104 return StringUtils::escapeRegexReplacement( $string );
2105 }
2106
2107 /**
2108 * Return the final portion of a pathname.
2109 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2110 * http://bugs.php.net/bug.php?id=33898
2111 *
2112 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2113 * We'll consider it so always, as we don't want \s in our Unix paths either.
2114 *
2115 * @param string $path
2116 * @param string $suffix to remove if present
2117 * @return string
2118 */
2119 function wfBaseName( $path, $suffix='' ) {
2120 $encSuffix = ($suffix == '')
2121 ? ''
2122 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2123 $matches = array();
2124 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2125 return $matches[1];
2126 } else {
2127 return '';
2128 }
2129 }
2130
2131 /**
2132 * Generate a relative path name to the given file.
2133 * May explode on non-matching case-insensitive paths,
2134 * funky symlinks, etc.
2135 *
2136 * @param string $path Absolute destination path including target filename
2137 * @param string $from Absolute source path, directory only
2138 * @return string
2139 */
2140 function wfRelativePath( $path, $from ) {
2141 // Normalize mixed input on Windows...
2142 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2143 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2144
2145 // Trim trailing slashes -- fix for drive root
2146 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2147 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2148
2149 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2150 $against = explode( DIRECTORY_SEPARATOR, $from );
2151
2152 if( $pieces[0] !== $against[0] ) {
2153 // Non-matching Windows drive letters?
2154 // Return a full path.
2155 return $path;
2156 }
2157
2158 // Trim off common prefix
2159 while( count( $pieces ) && count( $against )
2160 && $pieces[0] == $against[0] ) {
2161 array_shift( $pieces );
2162 array_shift( $against );
2163 }
2164
2165 // relative dots to bump us to the parent
2166 while( count( $against ) ) {
2167 array_unshift( $pieces, '..' );
2168 array_shift( $against );
2169 }
2170
2171 array_push( $pieces, wfBaseName( $path ) );
2172
2173 return implode( DIRECTORY_SEPARATOR, $pieces );
2174 }
2175
2176 /**
2177 * array_merge() does awful things with "numeric" indexes, including
2178 * string indexes when happen to look like integers. When we want
2179 * to merge arrays with arbitrary string indexes, we don't want our
2180 * arrays to be randomly corrupted just because some of them consist
2181 * of numbers.
2182 *
2183 * Fuck you, PHP. Fuck you in the ear!
2184 *
2185 * @param array $array1, [$array2, [...]]
2186 * @return array
2187 */
2188 function wfArrayMerge( $array1/* ... */ ) {
2189 $out = $array1;
2190 for( $i = 1; $i < func_num_args(); $i++ ) {
2191 foreach( func_get_arg( $i ) as $key => $value ) {
2192 $out[$key] = $value;
2193 }
2194 }
2195 return $out;
2196 }
2197
2198 /**
2199 * Make a URL index, appropriate for the el_index field of externallinks.
2200 */
2201 function wfMakeUrlIndex( $url ) {
2202 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2203 wfSuppressWarnings();
2204 $bits = parse_url( $url );
2205 wfRestoreWarnings();
2206 if ( !$bits ) {
2207 return false;
2208 }
2209 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2210 $delimiter = '';
2211 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2212 $delimiter = '://';
2213 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2214 $delimiter = ':';
2215 // parse_url detects for news: and mailto: the host part of an url as path
2216 // We have to correct this wrong detection
2217 if ( isset ( $bits['path'] ) ) {
2218 $bits['host'] = $bits['path'];
2219 $bits['path'] = '';
2220 }
2221 } else {
2222 return false;
2223 }
2224
2225 // Reverse the labels in the hostname, convert to lower case
2226 // For emails reverse domainpart only
2227 if ( $bits['scheme'] == 'mailto' ) {
2228 $mailparts = explode( '@', $bits['host'], 2 );
2229 if ( count($mailparts) === 2 ) {
2230 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2231 } else {
2232 // No domain specified, don't mangle it
2233 $domainpart = '';
2234 }
2235 $reversedHost = $domainpart . '@' . $mailparts[0];
2236 } else {
2237 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2238 }
2239 // Add an extra dot to the end
2240 // Why? Is it in wrong place in mailto links?
2241 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2242 $reversedHost .= '.';
2243 }
2244 // Reconstruct the pseudo-URL
2245 $prot = $bits['scheme'];
2246 $index = "$prot$delimiter$reversedHost";
2247 // Leave out user and password. Add the port, path, query and fragment
2248 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2249 if ( isset( $bits['path'] ) ) {
2250 $index .= $bits['path'];
2251 } else {
2252 $index .= '/';
2253 }
2254 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2255 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2256 return $index;
2257 }
2258
2259 /**
2260 * Do any deferred updates and clear the list
2261 * TODO: This could be in Wiki.php if that class made any sense at all
2262 */
2263 function wfDoUpdates()
2264 {
2265 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2266 foreach ( $wgDeferredUpdateList as $update ) {
2267 $update->doUpdate();
2268 }
2269 foreach ( $wgPostCommitUpdateList as $update ) {
2270 $update->doUpdate();
2271 }
2272 $wgDeferredUpdateList = array();
2273 $wgPostCommitUpdateList = array();
2274 }
2275
2276 /**
2277 * @deprecated use StringUtils::explodeMarkup
2278 */
2279 function wfExplodeMarkup( $separator, $text ) {
2280 return StringUtils::explodeMarkup( $separator, $text );
2281 }
2282
2283 /**
2284 * Convert an arbitrarily-long digit string from one numeric base
2285 * to another, optionally zero-padding to a minimum column width.
2286 *
2287 * Supports base 2 through 36; digit values 10-36 are represented
2288 * as lowercase letters a-z. Input is case-insensitive.
2289 *
2290 * @param $input string of digits
2291 * @param $sourceBase int 2-36
2292 * @param $destBase int 2-36
2293 * @param $pad int 1 or greater
2294 * @param $lowercase bool
2295 * @return string or false on invalid input
2296 */
2297 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2298 $input = strval( $input );
2299 if( $sourceBase < 2 ||
2300 $sourceBase > 36 ||
2301 $destBase < 2 ||
2302 $destBase > 36 ||
2303 $pad < 1 ||
2304 $sourceBase != intval( $sourceBase ) ||
2305 $destBase != intval( $destBase ) ||
2306 $pad != intval( $pad ) ||
2307 !is_string( $input ) ||
2308 $input == '' ) {
2309 return false;
2310 }
2311 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2312 $inDigits = array();
2313 $outChars = '';
2314
2315 // Decode and validate input string
2316 $input = strtolower( $input );
2317 for( $i = 0; $i < strlen( $input ); $i++ ) {
2318 $n = strpos( $digitChars, $input{$i} );
2319 if( $n === false || $n > $sourceBase ) {
2320 return false;
2321 }
2322 $inDigits[] = $n;
2323 }
2324
2325 // Iterate over the input, modulo-ing out an output digit
2326 // at a time until input is gone.
2327 while( count( $inDigits ) ) {
2328 $work = 0;
2329 $workDigits = array();
2330
2331 // Long division...
2332 foreach( $inDigits as $digit ) {
2333 $work *= $sourceBase;
2334 $work += $digit;
2335
2336 if( $work < $destBase ) {
2337 // Gonna need to pull another digit.
2338 if( count( $workDigits ) ) {
2339 // Avoid zero-padding; this lets us find
2340 // the end of the input very easily when
2341 // length drops to zero.
2342 $workDigits[] = 0;
2343 }
2344 } else {
2345 // Finally! Actual division!
2346 $workDigits[] = intval( $work / $destBase );
2347
2348 // Isn't it annoying that most programming languages
2349 // don't have a single divide-and-remainder operator,
2350 // even though the CPU implements it that way?
2351 $work = $work % $destBase;
2352 }
2353 }
2354
2355 // All that division leaves us with a remainder,
2356 // which is conveniently our next output digit.
2357 $outChars .= $digitChars[$work];
2358
2359 // And we continue!
2360 $inDigits = $workDigits;
2361 }
2362
2363 while( strlen( $outChars ) < $pad ) {
2364 $outChars .= '0';
2365 }
2366
2367 return strrev( $outChars );
2368 }
2369
2370 /**
2371 * Create an object with a given name and an array of construct parameters
2372 * @param string $name
2373 * @param array $p parameters
2374 */
2375 function wfCreateObject( $name, $p ){
2376 $p = array_values( $p );
2377 switch ( count( $p ) ) {
2378 case 0:
2379 return new $name;
2380 case 1:
2381 return new $name( $p[0] );
2382 case 2:
2383 return new $name( $p[0], $p[1] );
2384 case 3:
2385 return new $name( $p[0], $p[1], $p[2] );
2386 case 4:
2387 return new $name( $p[0], $p[1], $p[2], $p[3] );
2388 case 5:
2389 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2390 case 6:
2391 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2392 default:
2393 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2394 }
2395 }
2396
2397 /**
2398 * Alias for modularized function
2399 * @deprecated Use Http::get() instead
2400 */
2401 function wfGetHTTP( $url, $timeout = 'default' ) {
2402 wfDeprecated(__FUNCTION__);
2403 return Http::get( $url, $timeout );
2404 }
2405
2406 /**
2407 * Alias for modularized function
2408 * @deprecated Use Http::isLocalURL() instead
2409 */
2410 function wfIsLocalURL( $url ) {
2411 wfDeprecated(__FUNCTION__);
2412 return Http::isLocalURL( $url );
2413 }
2414
2415 function wfHttpOnlySafe() {
2416 global $wgHttpOnlyBlacklist;
2417 if( !version_compare("5.2", PHP_VERSION, "<") )
2418 return false;
2419
2420 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2421 foreach( $wgHttpOnlyBlacklist as $regex ) {
2422 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2423 return false;
2424 }
2425 }
2426 }
2427
2428 return true;
2429 }
2430
2431 /**
2432 * Initialise php session
2433 */
2434 function wfSetupSession() {
2435 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2436 if( $wgSessionsInMemcached ) {
2437 require_once( 'MemcachedSessions.php' );
2438 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2439 # If it's left on 'user' or another setting from another
2440 # application, it will end up failing. Try to recover.
2441 ini_set ( 'session.save_handler', 'files' );
2442 }
2443 $httpOnlySafe = wfHttpOnlySafe();
2444 wfDebugLog( 'cookie',
2445 'session_set_cookie_params: "' . implode( '", "',
2446 array(
2447 0,
2448 $wgCookiePath,
2449 $wgCookieDomain,
2450 $wgCookieSecure,
2451 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2452 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2453 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2454 } else {
2455 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2456 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2457 }
2458 session_cache_limiter( 'private, must-revalidate' );
2459 wfSuppressWarnings();
2460 session_start();
2461 wfRestoreWarnings();
2462 }
2463
2464 /**
2465 * Get an object from the precompiled serialized directory
2466 *
2467 * @return mixed The variable on success, false on failure
2468 */
2469 function wfGetPrecompiledData( $name ) {
2470 global $IP;
2471
2472 $file = "$IP/serialized/$name";
2473 if ( file_exists( $file ) ) {
2474 $blob = file_get_contents( $file );
2475 if ( $blob ) {
2476 return unserialize( $blob );
2477 }
2478 }
2479 return false;
2480 }
2481
2482 function wfGetCaller( $level = 2 ) {
2483 $backtrace = wfDebugBacktrace();
2484 if ( isset( $backtrace[$level] ) ) {
2485 return wfFormatStackFrame($backtrace[$level]);
2486 } else {
2487 $caller = 'unknown';
2488 }
2489 return $caller;
2490 }
2491
2492 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2493 function wfGetAllCallers() {
2494 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2495 }
2496
2497 /** Return a string representation of frame */
2498 function wfFormatStackFrame($frame) {
2499 return isset( $frame["class"] )?
2500 $frame["class"]."::".$frame["function"]:
2501 $frame["function"];
2502 }
2503
2504 /**
2505 * Get a cache key
2506 */
2507 function wfMemcKey( /*... */ ) {
2508 $args = func_get_args();
2509 $key = wfWikiID() . ':' . implode( ':', $args );
2510 return $key;
2511 }
2512
2513 /**
2514 * Get a cache key for a foreign DB
2515 */
2516 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2517 $args = array_slice( func_get_args(), 2 );
2518 if ( $prefix ) {
2519 $key = "$db-$prefix:" . implode( ':', $args );
2520 } else {
2521 $key = $db . ':' . implode( ':', $args );
2522 }
2523 return $key;
2524 }
2525
2526 /**
2527 * Get an ASCII string identifying this wiki
2528 * This is used as a prefix in memcached keys
2529 */
2530 function wfWikiID( $db = null ) {
2531 if( $db instanceof Database ) {
2532 return $db->getWikiID();
2533 } else {
2534 global $wgDBprefix, $wgDBname;
2535 if ( $wgDBprefix ) {
2536 return "$wgDBname-$wgDBprefix";
2537 } else {
2538 return $wgDBname;
2539 }
2540 }
2541 }
2542
2543 /**
2544 * Split a wiki ID into DB name and table prefix
2545 */
2546 function wfSplitWikiID( $wiki ) {
2547 $bits = explode( '-', $wiki, 2 );
2548 if ( count( $bits ) < 2 ) {
2549 $bits[] = '';
2550 }
2551 return $bits;
2552 }
2553
2554 /*
2555 * Get a Database object.
2556 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2557 * master (for write queries), DB_SLAVE for potentially lagged
2558 * read queries, or an integer >= 0 for a particular server.
2559 *
2560 * @param mixed $groups Query groups. An array of group names that this query
2561 * belongs to. May contain a single string if the query is only
2562 * in one group.
2563 *
2564 * @param string $wiki The wiki ID, or false for the current wiki
2565 *
2566 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2567 * will always return the same object, unless the underlying connection or load
2568 * balancer is manually destroyed.
2569 */
2570 function &wfGetDB( $db = DB_LAST, $groups = array(), $wiki = false ) {
2571 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2572 }
2573
2574 /**
2575 * Get a load balancer object.
2576 *
2577 * @param array $groups List of query groups
2578 * @param string $wiki Wiki ID, or false for the current wiki
2579 * @return LoadBalancer
2580 */
2581 function wfGetLB( $wiki = false ) {
2582 return wfGetLBFactory()->getMainLB( $wiki );
2583 }
2584
2585 /**
2586 * Get the load balancer factory object
2587 */
2588 function &wfGetLBFactory() {
2589 return LBFactory::singleton();
2590 }
2591
2592 /**
2593 * Find a file.
2594 * Shortcut for RepoGroup::singleton()->findFile()
2595 * @param mixed $title Title object or string. May be interwiki.
2596 * @param mixed $time Requested time for an archived image, or false for the
2597 * current version. An image object will be returned which
2598 * was created at the specified time.
2599 * @param mixed $flags FileRepo::FIND_ flags
2600 * @return File, or false if the file does not exist
2601 */
2602 function wfFindFile( $title, $time = false, $flags = 0 ) {
2603 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2604 }
2605
2606 /**
2607 * Get an object referring to a locally registered file.
2608 * Returns a valid placeholder object if the file does not exist.
2609 */
2610 function wfLocalFile( $title ) {
2611 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2612 }
2613
2614 /**
2615 * Should low-performance queries be disabled?
2616 *
2617 * @return bool
2618 */
2619 function wfQueriesMustScale() {
2620 global $wgMiserMode;
2621 return $wgMiserMode
2622 || ( SiteStats::pages() > 100000
2623 && SiteStats::edits() > 1000000
2624 && SiteStats::users() > 10000 );
2625 }
2626
2627 /**
2628 * Get the path to a specified script file, respecting file
2629 * extensions; this is a wrapper around $wgScriptExtension etc.
2630 *
2631 * @param string $script Script filename, sans extension
2632 * @return string
2633 */
2634 function wfScript( $script = 'index' ) {
2635 global $wgScriptPath, $wgScriptExtension;
2636 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2637 }
2638
2639 /**
2640 * Convenience function converts boolean values into "true"
2641 * or "false" (string) values
2642 *
2643 * @param bool $value
2644 * @return string
2645 */
2646 function wfBoolToStr( $value ) {
2647 return $value ? 'true' : 'false';
2648 }
2649
2650 /**
2651 * Load an extension messages file
2652 *
2653 * @param string $extensionName Name of extension to load messages from\for.
2654 * @param string $langcode Language to load messages for, or false for default
2655 * behvaiour (en, content language and user language).
2656 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2657 * on MediaWiki prior to that
2658 */
2659 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2660 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2661
2662 #For recording whether extension message files have been loaded in a given language.
2663 static $loaded = array();
2664
2665 if( !array_key_exists( $extensionName, $loaded ) ) {
2666 $loaded[$extensionName] = array();
2667 }
2668
2669 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2670 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2671 }
2672
2673 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2674 # Just do en, content language and user language.
2675 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2676 # Mark that they have been loaded.
2677 $loaded[$extensionName]['en'] = true;
2678 $loaded[$extensionName][$wgLang->getCode()] = true;
2679 $loaded[$extensionName][$wgContLang->getCode()] = true;
2680 # Mark that this part has been done to avoid weird if statements.
2681 $loaded[$extensionName]['*'] = true;
2682 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2683 # Load messages for specified language.
2684 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2685 # Mark that they have been loaded.
2686 $loaded[$extensionName][$langcode] = true;
2687 }
2688 }
2689
2690 /**
2691 * Get a platform-independent path to the null file, e.g.
2692 * /dev/null
2693 *
2694 * @return string
2695 */
2696 function wfGetNull() {
2697 return wfIsWindows()
2698 ? 'NUL'
2699 : '/dev/null';
2700 }
2701
2702 /**
2703 * Displays a maxlag error
2704 *
2705 * @param string $host Server that lags the most
2706 * @param int $lag Maxlag (actual)
2707 * @param int $maxLag Maxlag (requested)
2708 */
2709 function wfMaxlagError( $host, $lag, $maxLag ) {
2710 global $wgShowHostnames;
2711 header( 'HTTP/1.1 503 Service Unavailable' );
2712 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2713 header( 'X-Database-Lag: ' . intval( $lag ) );
2714 header( 'Content-Type: text/plain' );
2715 if( $wgShowHostnames ) {
2716 echo "Waiting for $host: $lag seconds lagged\n";
2717 } else {
2718 echo "Waiting for a database server: $lag seconds lagged\n";
2719 }
2720 }
2721
2722 /**
2723 * Throws an E_USER_NOTICE saying that $function is deprecated
2724 * @param string $function
2725 * @return null
2726 */
2727 function wfDeprecated( $function ) {
2728 global $wgDebugLogFile;
2729 if ( !$wgDebugLogFile ) {
2730 return;
2731 }
2732 $callers = wfDebugBacktrace();
2733 if( isset( $callers[2] ) ){
2734 $callerfunc = $callers[2];
2735 $callerfile = $callers[1];
2736 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2737 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2738 } else {
2739 $file = '(internal function)';
2740 }
2741 $func = '';
2742 if( isset( $callerfunc['class'] ) )
2743 $func .= $callerfunc['class'] . '::';
2744 $func .= @$callerfunc['function'];
2745 $msg = "Use of $function is deprecated. Called from $func in $file";
2746 } else {
2747 $msg = "Use of $function is deprecated.";
2748 }
2749 wfDebug( "$msg\n" );
2750 }
2751
2752 /**
2753 * Sleep until the worst slave's replication lag is less than or equal to
2754 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2755 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2756 * a no-op if there are no slaves.
2757 *
2758 * Every time the function has to wait for a slave, it will print a message to
2759 * that effect (and then sleep for a little while), so it's probably not best
2760 * to use this outside maintenance scripts in its present form.
2761 *
2762 * @param int $maxLag
2763 * @return null
2764 */
2765 function wfWaitForSlaves( $maxLag ) {
2766 if( $maxLag ) {
2767 $lb = wfGetLB();
2768 list( $host, $lag ) = $lb->getMaxLag();
2769 while( $lag > $maxLag ) {
2770 $name = @gethostbyaddr( $host );
2771 if( $name !== false ) {
2772 $host = $name;
2773 }
2774 print "Waiting for $host (lagged $lag seconds)...\n";
2775 sleep($maxLag);
2776 list( $host, $lag ) = $lb->getMaxLag();
2777 }
2778 }
2779 }
2780
2781 /** Generate a random 32-character hexadecimal token.
2782 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2783 */
2784 function wfGenerateToken( $salt = '' ) {
2785 $salt = serialize($salt);
2786
2787 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2788 }
2789
2790 /**
2791 * Replace all invalid characters with -
2792 * @param mixed $title Filename to process
2793 */
2794 function wfStripIllegalFilenameChars( $name ) {
2795 $name = wfBaseName( $name );
2796 $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
2797 return $name;
2798 }