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