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