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