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