$out is needed here
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
5 }
6
7 /**
8 * Global functions used everywhere
9 */
10
11 require_once dirname(__FILE__) . '/LogPage.php';
12 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__) . '/XmlFunctions.php';
14
15 /**
16 * Compatibility functions
17 *
18 * We more or less support PHP 5.0.x and up.
19 * Re-implementations of newer functions or functions in non-standard
20 * PHP extensions may be included here.
21 */
22 if( !function_exists('iconv') ) {
23 # iconv support is not in the default configuration and so may not be present.
24 # Assume will only ever use utf-8 and iso-8859-1.
25 # This will *not* work in all circumstances.
26 function iconv( $from, $to, $string ) {
27 if(strcasecmp( $from, $to ) == 0) return $string;
28 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
29 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
30 return $string;
31 }
32 }
33
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
37 $ar = array();
38 preg_match_all( '/./us', $str, $ar );
39
40 if( func_num_args() >= 3 ) {
41 $end = func_get_arg( 2 );
42 return join( '', array_slice( $ar[0], $start, $end ) );
43 } else {
44 return join( '', array_slice( $ar[0], $start ) );
45 }
46 }
47 }
48
49 if ( !function_exists( 'mb_strlen' ) ) {
50 /**
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
52 * @param string $str
53 * @param string $enc optional encoding; ignored
54 * @return int
55 */
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
58 $total = 0;
59
60 // Count ASCII bytes
61 for( $i = 0; $i < 0x80; $i++ ) {
62 $total += $counts[$i];
63 }
64
65 // Count multibyte sequence heads
66 for( $i = 0xc0; $i < 0xff; $i++ ) {
67 $total += $counts[$i];
68 }
69 return $total;
70 }
71 }
72
73 if ( !function_exists( 'array_diff_key' ) ) {
74 /**
75 * Exists in PHP 5.1.0+
76 * Not quite compatible, two-argument version only
77 * Null values will cause problems due to this use of isset()
78 */
79 function array_diff_key( $left, $right ) {
80 $result = $left;
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
84 }
85 }
86 return $result;
87 }
88 }
89
90 /**
91 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
92 */
93 function wfArrayDiff2( $a, $b ) {
94 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
95 }
96 function wfArrayDiff2_cmp( $a, $b ) {
97 if ( !is_array( $a ) ) {
98 return strcmp( $a, $b );
99 } elseif ( count( $a ) !== count( $b ) ) {
100 return count( $a ) < count( $b ) ? -1 : 1;
101 } else {
102 reset( $a );
103 reset( $b );
104 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
105 $cmp = strcmp( $valueA, $valueB );
106 if ( $cmp !== 0 ) {
107 return $cmp;
108 }
109 }
110 return 0;
111 }
112 }
113
114 /**
115 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
116 * PHP 5 won't let you declare a 'clone' function, even conditionally,
117 * so it has to be a wrapper with a different name.
118 */
119 function wfClone( $object ) {
120 return clone( $object );
121 }
122
123 /**
124 * Seed Mersenne Twister
125 * No-op for compatibility; only necessary in PHP < 4.2.0
126 */
127 function wfSeedRandom() {
128 /* No-op */
129 }
130
131 /**
132 * Get a random decimal value between 0 and 1, in a way
133 * not likely to give duplicate values for any realistic
134 * number of articles.
135 *
136 * @return string
137 */
138 function wfRandom() {
139 # The maximum random value is "only" 2^31-1, so get two random
140 # values to reduce the chance of dupes
141 $max = mt_getrandmax() + 1;
142 $rand = number_format( (mt_rand() * $max + mt_rand())
143 / $max / $max, 12, '.', '' );
144 return $rand;
145 }
146
147 /**
148 * We want / and : to be included as literal characters in our title URLs.
149 * %2F in the page titles seems to fatally break for some reason.
150 *
151 * @param $s String:
152 * @return string
153 */
154 function wfUrlencode ( $s ) {
155 $s = urlencode( $s );
156 $s = preg_replace( '/%3[Aa]/', ':', $s );
157 $s = preg_replace( '/%2[Ff]/', '/', $s );
158
159 return $s;
160 }
161
162 /**
163 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
164 * In normal operation this is a NOP.
165 *
166 * Controlling globals:
167 * $wgDebugLogFile - points to the log file
168 * $wgProfileOnly - if set, normal debug messages will not be recorded.
169 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
170 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
171 *
172 * @param $text String
173 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
174 */
175 function wfDebug( $text, $logonly = false ) {
176 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
177 static $recursion = 0;
178
179 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
180 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
181 return;
182 }
183
184 if ( $wgDebugComments && !$logonly ) {
185 if ( !isset( $wgOut ) ) {
186 return;
187 }
188 if ( !StubObject::isRealObject( $wgOut ) ) {
189 if ( $recursion ) {
190 return;
191 }
192 $recursion++;
193 $wgOut->_unstub();
194 $recursion--;
195 }
196 $wgOut->debug( $text );
197 }
198 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
199 # Strip unprintables; they can switch terminal modes when binary data
200 # gets dumped, which is pretty annoying.
201 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
202 wfErrorLog( $text, $wgDebugLogFile );
203 }
204 }
205
206 /**
207 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
208 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
209 *
210 * @param $logGroup String
211 * @param $text String
212 * @param $public Bool: whether to log the event in the public log if no private
213 * log file is specified, (default true)
214 */
215 function wfDebugLog( $logGroup, $text, $public = true ) {
216 global $wgDebugLogGroups;
217 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
218 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
219 $time = wfTimestamp( TS_DB );
220 $wiki = wfWikiID();
221 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
222 } else if ( $public === true ) {
223 wfDebug( $text, true );
224 }
225 }
226
227 /**
228 * Log for database errors
229 * @param $text String: database error message.
230 */
231 function wfLogDBError( $text ) {
232 global $wgDBerrorLog, $wgDBname;
233 if ( $wgDBerrorLog ) {
234 $host = trim(`hostname`);
235 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
236 wfErrorLog( $text, $wgDBerrorLog );
237 }
238 }
239
240 /**
241 * Log to a file without getting "file size exceeded" signals
242 */
243 function wfErrorLog( $text, $file ) {
244 wfSuppressWarnings();
245 $exists = file_exists( $file );
246 $size = $exists ? filesize( $file ) : false;
247 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
248 error_log( $text, 3, $file );
249 }
250 wfRestoreWarnings();
251 }
252
253 /**
254 * @todo document
255 */
256 function wfLogProfilingData() {
257 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
258 global $wgProfiler, $wgUser;
259 if ( !isset( $wgProfiler ) )
260 return;
261
262 $now = wfTime();
263 $elapsed = $now - $wgRequestTime;
264 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
265 $forward = '';
266 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
267 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
268 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
269 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
270 if( !empty( $_SERVER['HTTP_FROM'] ) )
271 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
272 if( $forward )
273 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
274 // Don't unstub $wgUser at this late stage just for statistics purposes
275 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
276 $forward .= ' anon';
277 $log = sprintf( "%s\t%04.3f\t%s\n",
278 gmdate( 'YmdHis' ), $elapsed,
279 urldecode( $wgRequest->getRequestURL() . $forward ) );
280 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
281 wfErrorLog( $log . $prof, $wgDebugLogFile );
282 }
283 }
284
285 /**
286 * Check if the wiki read-only lock file is present. This can be used to lock
287 * off editing functions, but doesn't guarantee that the database will not be
288 * modified.
289 * @return bool
290 */
291 function wfReadOnly() {
292 global $wgReadOnlyFile, $wgReadOnly;
293
294 if ( !is_null( $wgReadOnly ) ) {
295 return (bool)$wgReadOnly;
296 }
297 if ( '' == $wgReadOnlyFile ) {
298 return false;
299 }
300 // Set $wgReadOnly for faster access next time
301 if ( is_file( $wgReadOnlyFile ) ) {
302 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
303 } else {
304 $wgReadOnly = false;
305 }
306 return (bool)$wgReadOnly;
307 }
308
309 function wfReadOnlyReason() {
310 global $wgReadOnly;
311 wfReadOnly();
312 return $wgReadOnly;
313 }
314
315 /**
316 * Get a message from anywhere, for the current user language.
317 *
318 * Use wfMsgForContent() instead if the message should NOT
319 * change depending on the user preferences.
320 *
321 * @param $key String: lookup key for the message, usually
322 * defined in languages/Language.php
323 *
324 * This function also takes extra optional parameters (not
325 * shown in the function definition), which can by used to
326 * insert variable text into the predefined message.
327 */
328 function wfMsg( $key ) {
329 $args = func_get_args();
330 array_shift( $args );
331 return wfMsgReal( $key, $args, true );
332 }
333
334 /**
335 * Same as above except doesn't transform the message
336 */
337 function wfMsgNoTrans( $key ) {
338 $args = func_get_args();
339 array_shift( $args );
340 return wfMsgReal( $key, $args, true, false, false );
341 }
342
343 /**
344 * Get a message from anywhere, for the current global language
345 * set with $wgLanguageCode.
346 *
347 * Use this if the message should NOT change dependent on the
348 * language set in the user's preferences. This is the case for
349 * most text written into logs, as well as link targets (such as
350 * the name of the copyright policy page). Link titles, on the
351 * other hand, should be shown in the UI language.
352 *
353 * Note that MediaWiki allows users to change the user interface
354 * language in their preferences, but a single installation
355 * typically only contains content in one language.
356 *
357 * Be wary of this distinction: If you use wfMsg() where you should
358 * use wfMsgForContent(), a user of the software may have to
359 * customize over 70 messages in order to, e.g., fix a link in every
360 * possible language.
361 *
362 * @param $key String: lookup key for the message, usually
363 * defined in languages/Language.php
364 */
365 function wfMsgForContent( $key ) {
366 global $wgForceUIMsgAsContentMsg;
367 $args = func_get_args();
368 array_shift( $args );
369 $forcontent = true;
370 if( is_array( $wgForceUIMsgAsContentMsg ) &&
371 in_array( $key, $wgForceUIMsgAsContentMsg ) )
372 $forcontent = false;
373 return wfMsgReal( $key, $args, true, $forcontent );
374 }
375
376 /**
377 * Same as above except doesn't transform the message
378 */
379 function wfMsgForContentNoTrans( $key ) {
380 global $wgForceUIMsgAsContentMsg;
381 $args = func_get_args();
382 array_shift( $args );
383 $forcontent = true;
384 if( is_array( $wgForceUIMsgAsContentMsg ) &&
385 in_array( $key, $wgForceUIMsgAsContentMsg ) )
386 $forcontent = false;
387 return wfMsgReal( $key, $args, true, $forcontent, false );
388 }
389
390 /**
391 * Get a message from the language file, for the UI elements
392 */
393 function wfMsgNoDB( $key ) {
394 $args = func_get_args();
395 array_shift( $args );
396 return wfMsgReal( $key, $args, false );
397 }
398
399 /**
400 * Get a message from the language file, for the content
401 */
402 function wfMsgNoDBForContent( $key ) {
403 global $wgForceUIMsgAsContentMsg;
404 $args = func_get_args();
405 array_shift( $args );
406 $forcontent = true;
407 if( is_array( $wgForceUIMsgAsContentMsg ) &&
408 in_array( $key, $wgForceUIMsgAsContentMsg ) )
409 $forcontent = false;
410 return wfMsgReal( $key, $args, false, $forcontent );
411 }
412
413
414 /**
415 * Really get a message
416 * @param $key String: key to get.
417 * @param $args
418 * @param $useDB Boolean
419 * @param $transform Boolean: Whether or not to transform the message.
420 * @param $forContent Boolean
421 * @return String: the requested message.
422 */
423 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
424 wfProfileIn( __METHOD__ );
425 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
426 $message = wfMsgReplaceArgs( $message, $args );
427 wfProfileOut( __METHOD__ );
428 return $message;
429 }
430
431 /**
432 * This function provides the message source for messages to be edited which are *not* stored in the database.
433 * @param $key String:
434 */
435 function wfMsgWeirdKey ( $key ) {
436 $source = wfMsgGetKey( $key, false, true, false );
437 if ( wfEmptyMsg( $key, $source ) )
438 return "";
439 else
440 return $source;
441 }
442
443 /**
444 * Fetch a message string value, but don't replace any keys yet.
445 * @param string $key
446 * @param bool $useDB
447 * @param bool $forContent
448 * @return string
449 * @private
450 */
451 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
452 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
453
454 # If $wgMessageCache isn't initialised yet, try to return something sensible.
455 if( is_object( $wgMessageCache ) ) {
456 $message = $wgMessageCache->get( $key, $useDB, $forContent );
457 if ( $transform ) {
458 $message = $wgMessageCache->transform( $message );
459 }
460 } else {
461 if( $forContent ) {
462 $lang = &$wgContLang;
463 } else {
464 $lang = &$wgLang;
465 }
466
467 # MessageCache::get() does this already, Language::getMessage() doesn't
468 # ISSUE: Should we try to handle "message/lang" here too?
469 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
470
471 if( is_object( $lang ) ) {
472 $message = $lang->getMessage( $key );
473 } else {
474 $message = false;
475 }
476 }
477
478 return $message;
479 }
480
481 /**
482 * Replace message parameter keys on the given formatted output.
483 *
484 * @param string $message
485 * @param array $args
486 * @return string
487 * @private
488 */
489 function wfMsgReplaceArgs( $message, $args ) {
490 # Fix windows line-endings
491 # Some messages are split with explode("\n", $msg)
492 $message = str_replace( "\r", '', $message );
493
494 // Replace arguments
495 if ( count( $args ) ) {
496 if ( is_array( $args[0] ) ) {
497 $args = array_values( $args[0] );
498 }
499 $replacementKeys = array();
500 foreach( $args as $n => $param ) {
501 $replacementKeys['$' . ($n + 1)] = $param;
502 }
503 $message = strtr( $message, $replacementKeys );
504 }
505
506 return $message;
507 }
508
509 /**
510 * Return an HTML-escaped version of a message.
511 * Parameter replacements, if any, are done *after* the HTML-escaping,
512 * so parameters may contain HTML (eg links or form controls). Be sure
513 * to pre-escape them if you really do want plaintext, or just wrap
514 * the whole thing in htmlspecialchars().
515 *
516 * @param string $key
517 * @param string ... parameters
518 * @return string
519 */
520 function wfMsgHtml( $key ) {
521 $args = func_get_args();
522 array_shift( $args );
523 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
524 }
525
526 /**
527 * Return an HTML version of message
528 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
529 * so parameters may contain HTML (eg links or form controls). Be sure
530 * to pre-escape them if you really do want plaintext, or just wrap
531 * the whole thing in htmlspecialchars().
532 *
533 * @param string $key
534 * @param string ... parameters
535 * @return string
536 */
537 function wfMsgWikiHtml( $key ) {
538 global $wgOut;
539 $args = func_get_args();
540 array_shift( $args );
541 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
542 }
543
544 /**
545 * Returns message in the requested format
546 * @param string $key Key of the message
547 * @param array $options Processing rules:
548 * <i>parse</i>: parses wikitext to html
549 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
550 * <i>escape</i>: filters message through htmlspecialchars
551 * <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
552 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
553 * <i>parsemag</i>: transform the message using magic phrases
554 * <i>content</i>: fetch message for content language instead of interface
555 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
556 */
557 function wfMsgExt( $key, $options ) {
558 global $wgOut, $wgParser;
559
560 $args = func_get_args();
561 array_shift( $args );
562 array_shift( $args );
563
564 if( !is_array($options) ) {
565 $options = array($options);
566 }
567
568 $forContent = false;
569 if( in_array('content', $options) ) {
570 $forContent = true;
571 }
572
573 $string = wfMsgGetKey( $key, /*DB*/true, $forContent, /*Transform*/false );
574
575 if( !in_array('replaceafter', $options) ) {
576 $string = wfMsgReplaceArgs( $string, $args );
577 }
578
579 if( in_array('parse', $options) ) {
580 $string = $wgOut->parse( $string, true, !$forContent );
581 } elseif ( in_array('parseinline', $options) ) {
582 $string = $wgOut->parse( $string, true, !$forContent );
583 $m = array();
584 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
585 $string = $m[1];
586 }
587 } elseif ( in_array('parsemag', $options) ) {
588 global $wgMessageCache;
589 if ( isset( $wgMessageCache ) ) {
590 $string = $wgMessageCache->transform( $string, !$forContent );
591 }
592 }
593
594 if ( in_array('escape', $options) ) {
595 $string = htmlspecialchars ( $string );
596 } elseif ( in_array( 'escapenoentities', $options ) ) {
597 $string = htmlspecialchars( $string );
598 $string = str_replace( '&amp;', '&', $string );
599 $string = Sanitizer::normalizeCharReferences( $string );
600 }
601
602 if( in_array('replaceafter', $options) ) {
603 $string = wfMsgReplaceArgs( $string, $args );
604 }
605
606 return $string;
607 }
608
609
610 /**
611 * Just like exit() but makes a note of it.
612 * Commits open transactions except if the error parameter is set
613 *
614 * @deprecated Please return control to the caller or throw an exception
615 */
616 function wfAbruptExit( $error = false ){
617 static $called = false;
618 if ( $called ){
619 exit( -1 );
620 }
621 $called = true;
622
623 $bt = wfDebugBacktrace();
624 if( $bt ) {
625 for($i = 0; $i < count($bt) ; $i++){
626 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
627 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
628 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
629 }
630 } else {
631 wfDebug('WARNING: Abrupt exit\n');
632 }
633
634 wfLogProfilingData();
635
636 if ( !$error ) {
637 wfGetLB()->closeAll();
638 }
639 exit( -1 );
640 }
641
642 /**
643 * @deprecated Please return control the caller or throw an exception
644 */
645 function wfErrorExit() {
646 wfAbruptExit( true );
647 }
648
649 /**
650 * Print a simple message and die, returning nonzero to the shell if any.
651 * Plain die() fails to return nonzero to the shell if you pass a string.
652 * @param string $msg
653 */
654 function wfDie( $msg='' ) {
655 echo $msg;
656 die( 1 );
657 }
658
659 /**
660 * Throw a debugging exception. This function previously once exited the process,
661 * but now throws an exception instead, with similar results.
662 *
663 * @param string $msg Message shown when dieing.
664 */
665 function wfDebugDieBacktrace( $msg = '' ) {
666 throw new MWException( $msg );
667 }
668
669 /**
670 * Fetch server name for use in error reporting etc.
671 * Use real server name if available, so we know which machine
672 * in a server farm generated the current page.
673 * @return string
674 */
675 function wfHostname() {
676 if ( function_exists( 'posix_uname' ) ) {
677 // This function not present on Windows
678 $uname = @posix_uname();
679 } else {
680 $uname = false;
681 }
682 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
683 return $uname['nodename'];
684 } else {
685 # This may be a virtual server.
686 return $_SERVER['SERVER_NAME'];
687 }
688 }
689
690 /**
691 * Returns a HTML comment with the elapsed time since request.
692 * This method has no side effects.
693 * @return string
694 */
695 function wfReportTime() {
696 global $wgRequestTime, $wgShowHostnames;
697
698 $now = wfTime();
699 $elapsed = $now - $wgRequestTime;
700
701 return $wgShowHostnames
702 ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
703 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
704 }
705
706 /**
707 * Safety wrapper for debug_backtrace().
708 *
709 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
710 * murky circumstances, which may be triggered in part by stub objects
711 * or other fancy talkin'.
712 *
713 * Will return an empty array if Zend Optimizer is detected, otherwise
714 * the output from debug_backtrace() (trimmed).
715 *
716 * @return array of backtrace information
717 */
718 function wfDebugBacktrace() {
719 if( extension_loaded( 'Zend Optimizer' ) ) {
720 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
721 return array();
722 } else {
723 return array_slice( debug_backtrace(), 1 );
724 }
725 }
726
727 function wfBacktrace() {
728 global $wgCommandLineMode;
729
730 if ( $wgCommandLineMode ) {
731 $msg = '';
732 } else {
733 $msg = "<ul>\n";
734 }
735 $backtrace = wfDebugBacktrace();
736 foreach( $backtrace as $call ) {
737 if( isset( $call['file'] ) ) {
738 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
739 $file = $f[count($f)-1];
740 } else {
741 $file = '-';
742 }
743 if( isset( $call['line'] ) ) {
744 $line = $call['line'];
745 } else {
746 $line = '-';
747 }
748 if ( $wgCommandLineMode ) {
749 $msg .= "$file line $line calls ";
750 } else {
751 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
752 }
753 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
754 $msg .= $call['function'] . '()';
755
756 if ( $wgCommandLineMode ) {
757 $msg .= "\n";
758 } else {
759 $msg .= "</li>\n";
760 }
761 }
762 if ( $wgCommandLineMode ) {
763 $msg .= "\n";
764 } else {
765 $msg .= "</ul>\n";
766 }
767
768 return $msg;
769 }
770
771
772 /* Some generic result counters, pulled out of SearchEngine */
773
774
775 /**
776 * @todo document
777 */
778 function wfShowingResults( $offset, $limit ) {
779 global $wgLang;
780 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
781 }
782
783 /**
784 * @todo document
785 */
786 function wfShowingResultsNum( $offset, $limit, $num ) {
787 global $wgLang;
788 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
789 }
790
791 /**
792 * @todo document
793 */
794 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
795 global $wgLang;
796 $fmtLimit = $wgLang->formatNum( $limit );
797 $prev = wfMsg( 'prevn', $fmtLimit );
798 $next = wfMsg( 'nextn', $fmtLimit );
799
800 if( is_object( $link ) ) {
801 $title =& $link;
802 } else {
803 $title = Title::newFromText( $link );
804 if( is_null( $title ) ) {
805 return false;
806 }
807 }
808
809 if ( 0 != $offset ) {
810 $po = $offset - $limit;
811 if ( $po < 0 ) { $po = 0; }
812 $q = "limit={$limit}&offset={$po}";
813 if ( '' != $query ) { $q .= '&'.$query; }
814 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
815 } else { $plink = $prev; }
816
817 $no = $offset + $limit;
818 $q = 'limit='.$limit.'&offset='.$no;
819 if ( '' != $query ) { $q .= '&'.$query; }
820
821 if ( $atend ) {
822 $nlink = $next;
823 } else {
824 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
825 }
826 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
827 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
828 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
829 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
830 wfNumLink( $offset, 500, $title, $query );
831
832 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
833 }
834
835 /**
836 * @todo document
837 */
838 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
839 global $wgLang;
840 if ( '' == $query ) { $q = ''; }
841 else { $q = $query.'&'; }
842 $q .= 'limit='.$limit.'&offset='.$offset;
843
844 $fmtLimit = $wgLang->formatNum( $limit );
845 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
846 return $s;
847 }
848
849 /**
850 * @todo document
851 * @todo FIXME: we may want to blacklist some broken browsers
852 *
853 * @return bool Whereas client accept gzip compression
854 */
855 function wfClientAcceptsGzip() {
856 global $wgUseGzip;
857 if( $wgUseGzip ) {
858 # FIXME: we may want to blacklist some broken browsers
859 $m = array();
860 if( preg_match(
861 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
862 $_SERVER['HTTP_ACCEPT_ENCODING'],
863 $m ) ) {
864 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
865 wfDebug( " accepts gzip\n" );
866 return true;
867 }
868 }
869 return false;
870 }
871
872 /**
873 * Obtain the offset and limit values from the request string;
874 * used in special pages
875 *
876 * @param $deflimit Default limit if none supplied
877 * @param $optionname Name of a user preference to check against
878 * @return array
879 *
880 */
881 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
882 global $wgRequest;
883 return $wgRequest->getLimitOffset( $deflimit, $optionname );
884 }
885
886 /**
887 * Escapes the given text so that it may be output using addWikiText()
888 * without any linking, formatting, etc. making its way through. This
889 * is achieved by substituting certain characters with HTML entities.
890 * As required by the callers, <nowiki> is not used. It currently does
891 * not filter out characters which have special meaning only at the
892 * start of a line, such as "*".
893 *
894 * @param string $text Text to be escaped
895 */
896 function wfEscapeWikiText( $text ) {
897 $text = str_replace(
898 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
899 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
900 htmlspecialchars($text) );
901 return $text;
902 }
903
904 /**
905 * @todo document
906 */
907 function wfQuotedPrintable( $string, $charset = '' ) {
908 # Probably incomplete; see RFC 2045
909 if( empty( $charset ) ) {
910 global $wgInputEncoding;
911 $charset = $wgInputEncoding;
912 }
913 $charset = strtoupper( $charset );
914 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
915
916 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
917 $replace = $illegal . '\t ?_';
918 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
919 $out = "=?$charset?Q?";
920 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
921 $out .= '?=';
922 return $out;
923 }
924
925
926 /**
927 * @todo document
928 * @return float
929 */
930 function wfTime() {
931 return microtime(true);
932 }
933
934 /**
935 * Sets dest to source and returns the original value of dest
936 * If source is NULL, it just returns the value, it doesn't set the variable
937 */
938 function wfSetVar( &$dest, $source ) {
939 $temp = $dest;
940 if ( !is_null( $source ) ) {
941 $dest = $source;
942 }
943 return $temp;
944 }
945
946 /**
947 * As for wfSetVar except setting a bit
948 */
949 function wfSetBit( &$dest, $bit, $state = true ) {
950 $temp = (bool)($dest & $bit );
951 if ( !is_null( $state ) ) {
952 if ( $state ) {
953 $dest |= $bit;
954 } else {
955 $dest &= ~$bit;
956 }
957 }
958 return $temp;
959 }
960
961 /**
962 * This function takes two arrays as input, and returns a CGI-style string, e.g.
963 * "days=7&limit=100". Options in the first array override options in the second.
964 * Options set to "" will not be output.
965 */
966 function wfArrayToCGI( $array1, $array2 = NULL )
967 {
968 if ( !is_null( $array2 ) ) {
969 $array1 = $array1 + $array2;
970 }
971
972 $cgi = '';
973 foreach ( $array1 as $key => $value ) {
974 if ( '' !== $value ) {
975 if ( '' != $cgi ) {
976 $cgi .= '&';
977 }
978 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
979 }
980 }
981 return $cgi;
982 }
983
984 /**
985 * Append a query string to an existing URL, which may or may not already
986 * have query string parameters already. If so, they will be combined.
987 *
988 * @param string $url
989 * @param string $query
990 * @return string
991 */
992 function wfAppendQuery( $url, $query ) {
993 if( $query != '' ) {
994 if( false === strpos( $url, '?' ) ) {
995 $url .= '?';
996 } else {
997 $url .= '&';
998 }
999 $url .= $query;
1000 }
1001 return $url;
1002 }
1003
1004 /**
1005 * Expand a potentially local URL to a fully-qualified URL.
1006 * Assumes $wgServer is correct. :)
1007 * @param string $url, either fully-qualified or a local path + query
1008 * @return string Fully-qualified URL
1009 */
1010 function wfExpandUrl( $url ) {
1011 if( substr( $url, 0, 1 ) == '/' ) {
1012 global $wgServer;
1013 return $wgServer . $url;
1014 } else {
1015 return $url;
1016 }
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 $wgStatsMethod;
1685
1686 if( $wgStatsMethod == 'udp' ) {
1687 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1688 static $socket;
1689 if (!$socket) {
1690 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1691 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1692 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1693 }
1694 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1695 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1696 } elseif( $wgStatsMethod == 'cache' ) {
1697 global $wgMemc;
1698 $key = wfMemcKey( 'stats', $key );
1699 if ( is_null( $wgMemc->incr( $key ) ) ) {
1700 $wgMemc->add( $key, 1 );
1701 }
1702 } else {
1703 // Disabled
1704 }
1705 }
1706
1707 /**
1708 * @param mixed $nr The number to format
1709 * @param int $acc The number of digits after the decimal point, default 2
1710 * @param bool $round Whether or not to round the value, default true
1711 * @return float
1712 */
1713 function wfPercent( $nr, $acc = 2, $round = true ) {
1714 $ret = sprintf( "%.${acc}f", $nr );
1715 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1716 }
1717
1718 /**
1719 * Encrypt a username/password.
1720 *
1721 * @param string $userid ID of the user
1722 * @param string $password Password of the user
1723 * @return string Hashed password
1724 */
1725 function wfEncryptPassword( $userid, $password ) {
1726 global $wgPasswordSalt;
1727 $p = md5( $password);
1728
1729 if($wgPasswordSalt)
1730 return md5( "{$userid}-{$p}" );
1731 else
1732 return $p;
1733 }
1734
1735 /**
1736 * Appends to second array if $value differs from that in $default
1737 */
1738 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1739 if ( is_null( $changed ) ) {
1740 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1741 }
1742 if ( $default[$key] !== $value ) {
1743 $changed[$key] = $value;
1744 }
1745 }
1746
1747 /**
1748 * Since wfMsg() and co suck, they don't return false if the message key they
1749 * looked up didn't exist but a XHTML string, this function checks for the
1750 * nonexistance of messages by looking at wfMsg() output
1751 *
1752 * @param $msg The message key looked up
1753 * @param $wfMsgOut The output of wfMsg*()
1754 * @return bool
1755 */
1756 function wfEmptyMsg( $msg, $wfMsgOut ) {
1757 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1758 }
1759
1760 /**
1761 * Find out whether or not a mixed variable exists in a string
1762 *
1763 * @param mixed needle
1764 * @param string haystack
1765 * @return bool
1766 */
1767 function in_string( $needle, $str ) {
1768 return strpos( $str, $needle ) !== false;
1769 }
1770
1771 function wfSpecialList( $page, $details ) {
1772 global $wgContLang;
1773 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1774 return $page . $details;
1775 }
1776
1777 /**
1778 * Returns a regular expression of url protocols
1779 *
1780 * @return string
1781 */
1782 function wfUrlProtocols() {
1783 global $wgUrlProtocols;
1784
1785 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1786 // with LocalSettings files from 1.5
1787 if ( is_array( $wgUrlProtocols ) ) {
1788 $protocols = array();
1789 foreach ($wgUrlProtocols as $protocol)
1790 $protocols[] = preg_quote( $protocol, '/' );
1791
1792 return implode( '|', $protocols );
1793 } else {
1794 return $wgUrlProtocols;
1795 }
1796 }
1797
1798 /**
1799 * Safety wrapper around ini_get() for boolean settings.
1800 * The values returned from ini_get() are pre-normalized for settings
1801 * set via php.ini or php_flag/php_admin_flag... but *not*
1802 * for those set via php_value/php_admin_value.
1803 *
1804 * It's fairly common for people to use php_value instead of php_flag,
1805 * which can leave you with an 'off' setting giving a false positive
1806 * for code that just takes the ini_get() return value as a boolean.
1807 *
1808 * To make things extra interesting, setting via php_value accepts
1809 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1810 * Unrecognized values go false... again opposite PHP's own coercion
1811 * from string to bool.
1812 *
1813 * Luckily, 'properly' set settings will always come back as '0' or '1',
1814 * so we only have to worry about them and the 'improper' settings.
1815 *
1816 * I frickin' hate PHP... :P
1817 *
1818 * @param string $setting
1819 * @return bool
1820 */
1821 function wfIniGetBool( $setting ) {
1822 $val = ini_get( $setting );
1823 // 'on' and 'true' can't have whitespace around them, but '1' can.
1824 return strtolower( $val ) == 'on'
1825 || strtolower( $val ) == 'true'
1826 || strtolower( $val ) == 'yes'
1827 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1828 }
1829
1830 /**
1831 * Execute a shell command, with time and memory limits mirrored from the PHP
1832 * configuration if supported.
1833 * @param $cmd Command line, properly escaped for shell.
1834 * @param &$retval optional, will receive the program's exit code.
1835 * (non-zero is usually failure)
1836 * @return collected stdout as a string (trailing newlines stripped)
1837 */
1838 function wfShellExec( $cmd, &$retval=null ) {
1839 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1840
1841 if( wfIniGetBool( 'safe_mode' ) ) {
1842 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1843 $retval = 1;
1844 return "Unable to run external programs in safe mode.";
1845 }
1846
1847 if ( php_uname( 's' ) == 'Linux' ) {
1848 $time = intval( ini_get( 'max_execution_time' ) );
1849 $mem = intval( $wgMaxShellMemory );
1850 $filesize = intval( $wgMaxShellFileSize );
1851
1852 if ( $time > 0 && $mem > 0 ) {
1853 $script = "$IP/bin/ulimit4.sh";
1854 if ( is_executable( $script ) ) {
1855 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1856 }
1857 }
1858 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1859 # This is a hack to work around PHP's flawed invocation of cmd.exe
1860 # http://news.php.net/php.internals/21796
1861 $cmd = '"' . $cmd . '"';
1862 }
1863 wfDebug( "wfShellExec: $cmd\n" );
1864
1865 $retval = 1; // error by default?
1866 ob_start();
1867 passthru( $cmd, $retval );
1868 $output = ob_get_contents();
1869 ob_end_clean();
1870 return $output;
1871
1872 }
1873
1874 /**
1875 * This function works like "use VERSION" in Perl, the program will die with a
1876 * backtrace if the current version of PHP is less than the version provided
1877 *
1878 * This is useful for extensions which due to their nature are not kept in sync
1879 * with releases, and might depend on other versions of PHP than the main code
1880 *
1881 * Note: PHP might die due to parsing errors in some cases before it ever
1882 * manages to call this function, such is life
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 wfUsePHP( $req_ver ) {
1890 $php_ver = PHP_VERSION;
1891
1892 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1893 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1894 }
1895
1896 /**
1897 * This function works like "use VERSION" in Perl except it checks the version
1898 * of MediaWiki, the program will die with a backtrace if the current version
1899 * of MediaWiki is less than the version provided.
1900 *
1901 * This is useful for extensions which due to their nature are not kept in sync
1902 * with releases
1903 *
1904 * @see perldoc -f use
1905 *
1906 * @param mixed $version The version to check, can be a string, an integer, or
1907 * a float
1908 */
1909 function wfUseMW( $req_ver ) {
1910 global $wgVersion;
1911
1912 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1913 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1914 }
1915
1916 /**
1917 * @deprecated use StringUtils::escapeRegexReplacement
1918 */
1919 function wfRegexReplacement( $string ) {
1920 return StringUtils::escapeRegexReplacement( $string );
1921 }
1922
1923 /**
1924 * Return the final portion of a pathname.
1925 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1926 * http://bugs.php.net/bug.php?id=33898
1927 *
1928 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1929 * We'll consider it so always, as we don't want \s in our Unix paths either.
1930 *
1931 * @param string $path
1932 * @param string $suffix to remove if present
1933 * @return string
1934 */
1935 function wfBaseName( $path, $suffix='' ) {
1936 $encSuffix = ($suffix == '')
1937 ? ''
1938 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1939 $matches = array();
1940 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1941 return $matches[1];
1942 } else {
1943 return '';
1944 }
1945 }
1946
1947 /**
1948 * Generate a relative path name to the given file.
1949 * May explode on non-matching case-insensitive paths,
1950 * funky symlinks, etc.
1951 *
1952 * @param string $path Absolute destination path including target filename
1953 * @param string $from Absolute source path, directory only
1954 * @return string
1955 */
1956 function wfRelativePath( $path, $from ) {
1957 // Normalize mixed input on Windows...
1958 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1959 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1960
1961 // Trim trailing slashes -- fix for drive root
1962 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1963 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1964
1965 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1966 $against = explode( DIRECTORY_SEPARATOR, $from );
1967
1968 if( $pieces[0] !== $against[0] ) {
1969 // Non-matching Windows drive letters?
1970 // Return a full path.
1971 return $path;
1972 }
1973
1974 // Trim off common prefix
1975 while( count( $pieces ) && count( $against )
1976 && $pieces[0] == $against[0] ) {
1977 array_shift( $pieces );
1978 array_shift( $against );
1979 }
1980
1981 // relative dots to bump us to the parent
1982 while( count( $against ) ) {
1983 array_unshift( $pieces, '..' );
1984 array_shift( $against );
1985 }
1986
1987 array_push( $pieces, wfBaseName( $path ) );
1988
1989 return implode( DIRECTORY_SEPARATOR, $pieces );
1990 }
1991
1992 /**
1993 * array_merge() does awful things with "numeric" indexes, including
1994 * string indexes when happen to look like integers. When we want
1995 * to merge arrays with arbitrary string indexes, we don't want our
1996 * arrays to be randomly corrupted just because some of them consist
1997 * of numbers.
1998 *
1999 * Fuck you, PHP. Fuck you in the ear!
2000 *
2001 * @param array $array1, [$array2, [...]]
2002 * @return array
2003 */
2004 function wfArrayMerge( $array1/* ... */ ) {
2005 $out = $array1;
2006 for( $i = 1; $i < func_num_args(); $i++ ) {
2007 foreach( func_get_arg( $i ) as $key => $value ) {
2008 $out[$key] = $value;
2009 }
2010 }
2011 return $out;
2012 }
2013
2014 /**
2015 * Make a URL index, appropriate for the el_index field of externallinks.
2016 */
2017 function wfMakeUrlIndex( $url ) {
2018 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2019 wfSuppressWarnings();
2020 $bits = parse_url( $url );
2021 wfRestoreWarnings();
2022 if ( !$bits ) {
2023 return false;
2024 }
2025 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2026 $delimiter = '';
2027 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2028 $delimiter = '://';
2029 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2030 $delimiter = ':';
2031 // parse_url detects for news: and mailto: the host part of an url as path
2032 // We have to correct this wrong detection
2033 if ( isset ( $bits['path'] ) ) {
2034 $bits['host'] = $bits['path'];
2035 $bits['path'] = '';
2036 }
2037 } else {
2038 return false;
2039 }
2040
2041 // Reverse the labels in the hostname, convert to lower case
2042 // For emails reverse domainpart only
2043 if ( $bits['scheme'] == 'mailto' ) {
2044 $mailparts = explode( '@', $bits['host'], 2 );
2045 if ( count($mailparts) === 2 ) {
2046 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2047 } else {
2048 // No domain specified, don't mangle it
2049 $domainpart = '';
2050 }
2051 $reversedHost = $domainpart . '@' . $mailparts[0];
2052 } else {
2053 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2054 }
2055 // Add an extra dot to the end
2056 // Why? Is it in wrong place in mailto links?
2057 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2058 $reversedHost .= '.';
2059 }
2060 // Reconstruct the pseudo-URL
2061 $prot = $bits['scheme'];
2062 $index = "$prot$delimiter$reversedHost";
2063 // Leave out user and password. Add the port, path, query and fragment
2064 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2065 if ( isset( $bits['path'] ) ) {
2066 $index .= $bits['path'];
2067 } else {
2068 $index .= '/';
2069 }
2070 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2071 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2072 return $index;
2073 }
2074
2075 /**
2076 * Do any deferred updates and clear the list
2077 * TODO: This could be in Wiki.php if that class made any sense at all
2078 */
2079 function wfDoUpdates()
2080 {
2081 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2082 foreach ( $wgDeferredUpdateList as $update ) {
2083 $update->doUpdate();
2084 }
2085 foreach ( $wgPostCommitUpdateList as $update ) {
2086 $update->doUpdate();
2087 }
2088 $wgDeferredUpdateList = array();
2089 $wgPostCommitUpdateList = array();
2090 }
2091
2092 /**
2093 * @deprecated use StringUtils::explodeMarkup
2094 */
2095 function wfExplodeMarkup( $separator, $text ) {
2096 return StringUtils::explodeMarkup( $separator, $text );
2097 }
2098
2099 /**
2100 * Convert an arbitrarily-long digit string from one numeric base
2101 * to another, optionally zero-padding to a minimum column width.
2102 *
2103 * Supports base 2 through 36; digit values 10-36 are represented
2104 * as lowercase letters a-z. Input is case-insensitive.
2105 *
2106 * @param $input string of digits
2107 * @param $sourceBase int 2-36
2108 * @param $destBase int 2-36
2109 * @param $pad int 1 or greater
2110 * @param $lowercase bool
2111 * @return string or false on invalid input
2112 */
2113 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2114 $input = strval( $input );
2115 if( $sourceBase < 2 ||
2116 $sourceBase > 36 ||
2117 $destBase < 2 ||
2118 $destBase > 36 ||
2119 $pad < 1 ||
2120 $sourceBase != intval( $sourceBase ) ||
2121 $destBase != intval( $destBase ) ||
2122 $pad != intval( $pad ) ||
2123 !is_string( $input ) ||
2124 $input == '' ) {
2125 return false;
2126 }
2127 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2128 $inDigits = array();
2129 $outChars = '';
2130
2131 // Decode and validate input string
2132 $input = strtolower( $input );
2133 for( $i = 0; $i < strlen( $input ); $i++ ) {
2134 $n = strpos( $digitChars, $input{$i} );
2135 if( $n === false || $n > $sourceBase ) {
2136 return false;
2137 }
2138 $inDigits[] = $n;
2139 }
2140
2141 // Iterate over the input, modulo-ing out an output digit
2142 // at a time until input is gone.
2143 while( count( $inDigits ) ) {
2144 $work = 0;
2145 $workDigits = array();
2146
2147 // Long division...
2148 foreach( $inDigits as $digit ) {
2149 $work *= $sourceBase;
2150 $work += $digit;
2151
2152 if( $work < $destBase ) {
2153 // Gonna need to pull another digit.
2154 if( count( $workDigits ) ) {
2155 // Avoid zero-padding; this lets us find
2156 // the end of the input very easily when
2157 // length drops to zero.
2158 $workDigits[] = 0;
2159 }
2160 } else {
2161 // Finally! Actual division!
2162 $workDigits[] = intval( $work / $destBase );
2163
2164 // Isn't it annoying that most programming languages
2165 // don't have a single divide-and-remainder operator,
2166 // even though the CPU implements it that way?
2167 $work = $work % $destBase;
2168 }
2169 }
2170
2171 // All that division leaves us with a remainder,
2172 // which is conveniently our next output digit.
2173 $outChars .= $digitChars[$work];
2174
2175 // And we continue!
2176 $inDigits = $workDigits;
2177 }
2178
2179 while( strlen( $outChars ) < $pad ) {
2180 $outChars .= '0';
2181 }
2182
2183 return strrev( $outChars );
2184 }
2185
2186 /**
2187 * Create an object with a given name and an array of construct parameters
2188 * @param string $name
2189 * @param array $p parameters
2190 */
2191 function wfCreateObject( $name, $p ){
2192 $p = array_values( $p );
2193 switch ( count( $p ) ) {
2194 case 0:
2195 return new $name;
2196 case 1:
2197 return new $name( $p[0] );
2198 case 2:
2199 return new $name( $p[0], $p[1] );
2200 case 3:
2201 return new $name( $p[0], $p[1], $p[2] );
2202 case 4:
2203 return new $name( $p[0], $p[1], $p[2], $p[3] );
2204 case 5:
2205 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2206 case 6:
2207 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2208 default:
2209 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2210 }
2211 }
2212
2213 /**
2214 * Aliases for modularized functions
2215 */
2216 function wfGetHTTP( $url, $timeout = 'default' ) {
2217 return Http::get( $url, $timeout );
2218 }
2219 function wfIsLocalURL( $url ) {
2220 return Http::isLocalURL( $url );
2221 }
2222
2223 /**
2224 * Initialise php session
2225 */
2226 function wfSetupSession() {
2227 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2228 if( $wgSessionsInMemcached ) {
2229 require_once( 'MemcachedSessions.php' );
2230 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2231 # If it's left on 'user' or another setting from another
2232 # application, it will end up failing. Try to recover.
2233 ini_set ( 'session.save_handler', 'files' );
2234 }
2235 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2236 session_cache_limiter( 'private, must-revalidate' );
2237 wfSuppressWarnings();
2238 session_start();
2239 wfRestoreWarnings();
2240 }
2241
2242 /**
2243 * Get an object from the precompiled serialized directory
2244 *
2245 * @return mixed The variable on success, false on failure
2246 */
2247 function wfGetPrecompiledData( $name ) {
2248 global $IP;
2249
2250 $file = "$IP/serialized/$name";
2251 if ( file_exists( $file ) ) {
2252 $blob = file_get_contents( $file );
2253 if ( $blob ) {
2254 return unserialize( $blob );
2255 }
2256 }
2257 return false;
2258 }
2259
2260 function wfGetCaller( $level = 2 ) {
2261 $backtrace = wfDebugBacktrace();
2262 if ( isset( $backtrace[$level] ) ) {
2263 return wfFormatStackFrame($backtrace[$level]);
2264 } else {
2265 $caller = 'unknown';
2266 }
2267 return $caller;
2268 }
2269
2270 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2271 function wfGetAllCallers() {
2272 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2273 }
2274
2275 /** Return a string representation of frame */
2276 function wfFormatStackFrame($frame) {
2277 return isset( $frame["class"] )?
2278 $frame["class"]."::".$frame["function"]:
2279 $frame["function"];
2280 }
2281
2282 /**
2283 * Get a cache key
2284 */
2285 function wfMemcKey( /*... */ ) {
2286 global $wgDBprefix, $wgDBname;
2287 $args = func_get_args();
2288 if ( $wgDBprefix ) {
2289 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2290 } else {
2291 $key = $wgDBname . ':' . implode( ':', $args );
2292 }
2293 return $key;
2294 }
2295
2296 /**
2297 * Get a cache key for a foreign DB
2298 */
2299 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2300 $args = array_slice( func_get_args(), 2 );
2301 if ( $prefix ) {
2302 $key = "$db-$prefix:" . implode( ':', $args );
2303 } else {
2304 $key = $db . ':' . implode( ':', $args );
2305 }
2306 return $key;
2307 }
2308
2309 /**
2310 * Get an ASCII string identifying this wiki
2311 * This is used as a prefix in memcached keys
2312 */
2313 function wfWikiID() {
2314 global $wgDBprefix, $wgDBname;
2315 if ( $wgDBprefix ) {
2316 return "$wgDBname-$wgDBprefix";
2317 } else {
2318 return $wgDBname;
2319 }
2320 }
2321
2322 /**
2323 * Split a wiki ID into DB name and table prefix
2324 */
2325 function wfSplitWikiID( $wiki ) {
2326 $bits = explode( '-', $wiki, 2 );
2327 if ( count( $bits ) < 2 ) {
2328 $bits[] = '';
2329 }
2330 return $bits;
2331 }
2332
2333 /*
2334 * Get a Database object
2335 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2336 * master (for write queries), DB_SLAVE for potentially lagged
2337 * read queries, or an integer >= 0 for a particular server.
2338 *
2339 * @param mixed $groups Query groups. An array of group names that this query
2340 * belongs to. May contain a single string if the query is only
2341 * in one group.
2342 *
2343 * @param string $wiki The wiki ID, or false for the current wiki
2344 */
2345 function &wfGetDB( $db = DB_LAST, $groups = array(), $wiki = false ) {
2346 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2347 }
2348
2349 /**
2350 * Get a load balancer object.
2351 *
2352 * @param array $groups List of query groups
2353 * @param string $wiki Wiki ID, or false for the current wiki
2354 * @return LoadBalancer
2355 */
2356 function wfGetLB( $wiki = false ) {
2357 return wfGetLBFactory()->getMainLB( $wiki );
2358 }
2359
2360 /**
2361 * Get the load balancer factory object
2362 */
2363 function &wfGetLBFactory() {
2364 return LBFactory::singleton();
2365 }
2366
2367 /**
2368 * Find a file.
2369 * Shortcut for RepoGroup::singleton()->findFile()
2370 * @param mixed $title Title object or string. May be interwiki.
2371 * @param mixed $time Requested time for an archived image, or false for the
2372 * current version. An image object will be returned which
2373 * was created at the specified time.
2374 * @return File, or false if the file does not exist
2375 */
2376 function wfFindFile( $title, $time = false ) {
2377 return RepoGroup::singleton()->findFile( $title, $time );
2378 }
2379
2380 /**
2381 * Get an object referring to a locally registered file.
2382 * Returns a valid placeholder object if the file does not exist.
2383 */
2384 function wfLocalFile( $title ) {
2385 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2386 }
2387
2388 /**
2389 * Should low-performance queries be disabled?
2390 *
2391 * @return bool
2392 */
2393 function wfQueriesMustScale() {
2394 global $wgMiserMode;
2395 return $wgMiserMode
2396 || ( SiteStats::pages() > 100000
2397 && SiteStats::edits() > 1000000
2398 && SiteStats::users() > 10000 );
2399 }
2400
2401 /**
2402 * Get the path to a specified script file, respecting file
2403 * extensions; this is a wrapper around $wgScriptExtension etc.
2404 *
2405 * @param string $script Script filename, sans extension
2406 * @return string
2407 */
2408 function wfScript( $script = 'index' ) {
2409 global $wgScriptPath, $wgScriptExtension;
2410 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2411 }
2412
2413 /**
2414 * Convenience function converts boolean values into "true"
2415 * or "false" (string) values
2416 *
2417 * @param bool $value
2418 * @return string
2419 */
2420 function wfBoolToStr( $value ) {
2421 return $value ? 'true' : 'false';
2422 }
2423
2424 /**
2425 * Load an extension messages file
2426 */
2427 function wfLoadExtensionMessages( $extensionName ) {
2428 global $wgExtensionMessagesFiles, $wgMessageCache;
2429 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2430 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2431 // Prevent double-loading
2432 $wgExtensionMessagesFiles[$extensionName] = false;
2433 }
2434 }
2435
2436 /**
2437 * Get a platform-independent path to the null file, e.g.
2438 * /dev/null
2439 *
2440 * @return string
2441 */
2442 function wfGetNull() {
2443 return wfIsWindows()
2444 ? 'NUL'
2445 : '/dev/null';
2446 }
2447
2448 /**
2449 * Displays a maxlag error
2450 *
2451 * @param string $host Server that lags the most
2452 * @param int $lag Maxlag (actual)
2453 * @param int $maxLag Maxlag (requested)
2454 */
2455 function wfMaxlagError( $host, $lag, $maxLag ) {
2456 global $wgShowHostnames;
2457 header( 'HTTP/1.1 503 Service Unavailable' );
2458 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2459 header( 'X-Database-Lag: ' . intval( $lag ) );
2460 header( 'Content-Type: text/plain' );
2461 if( $wgShowHostnames ) {
2462 echo "Waiting for $host: $lag seconds lagged\n";
2463 } else {
2464 echo "Waiting for a database server: $lag seconds lagged\n";
2465 }
2466 }
2467
2468 /**
2469 * Throws an E_USER_NOTICE saying that $function is deprecated
2470 * @param string $function
2471 * @return null
2472 */
2473 function wfDeprecated( $function ) {
2474 trigger_error( "Use of $function is deprecated", E_USER_NOTICE );
2475 }
2476
2477 /**
2478 * Sleep until the worst slave's replication lag is less than or equal to
2479 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2480 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2481 * a no-op if there are no slaves.
2482 *
2483 * Every time the function has to wait for a slave, it will print a message to
2484 * that effect (and then sleep for a little while), so it's probably not best
2485 * to use this outside maintenance scripts in its present form.
2486 *
2487 * @param int $maxLag
2488 * @return null
2489 */
2490 function wfWaitForSlaves( $maxLag ) {
2491 if( $maxLag ) {
2492 $lb = wfGetLB();
2493 list( $host, $lag ) = $lb->getMaxLag();
2494 while( $lag > $maxLag ) {
2495 $name = @gethostbyaddr( $host );
2496 if( $name !== false ) {
2497 $host = $name;
2498 }
2499 print "Waiting for $host (lagged $lag seconds)...\n";
2500 sleep($maxLag);
2501 list( $host, $lag ) = $lb->getMaxLag();
2502 }
2503 }
2504 }
2505
2506 /** Generate a random 32-character hexadecimal token.
2507 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2508 */
2509 function wfGenerateToken( $salt = '' ) {
2510 $salt = serialize($salt);
2511
2512 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2513 }