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