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