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