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