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