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