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