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