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