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