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