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