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