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