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