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