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