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