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