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