* (bug 14772) Disallow moving images to invalid titles
[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 ob_start();
866 var_dump( $var );
867 $s = str_replace("\n","<br />\n", ob_get_contents() . "\n");
868 ob_end_clean();
869 if ( headers_sent() || !@is_object( $wgOut ) ) {
870 print $s;
871 } else {
872 $wgOut->addHTML( $s );
873 }
874 }
875
876 /**
877 * Provide a simple HTTP error.
878 */
879 function wfHttpError( $code, $label, $desc ) {
880 global $wgOut;
881 $wgOut->disable();
882 header( "HTTP/1.0 $code $label" );
883 header( "Status: $code $label" );
884 $wgOut->sendCacheControl();
885
886 header( 'Content-type: text/html; charset=utf-8' );
887 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
888 "<html><head><title>" .
889 htmlspecialchars( $label ) .
890 "</title></head><body><h1>" .
891 htmlspecialchars( $label ) .
892 "</h1><p>" .
893 nl2br( htmlspecialchars( $desc ) ) .
894 "</p></body></html>\n";
895 }
896
897 /**
898 * Clear away any user-level output buffers, discarding contents.
899 *
900 * Suitable for 'starting afresh', for instance when streaming
901 * relatively large amounts of data without buffering, or wanting to
902 * output image files without ob_gzhandler's compression.
903 *
904 * The optional $resetGzipEncoding parameter controls suppression of
905 * the Content-Encoding header sent by ob_gzhandler; by default it
906 * is left. See comments for wfClearOutputBuffers() for why it would
907 * be used.
908 *
909 * Note that some PHP configuration options may add output buffer
910 * layers which cannot be removed; these are left in place.
911 *
912 * @param bool $resetGzipEncoding
913 */
914 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
915 if( $resetGzipEncoding ) {
916 // Suppress Content-Encoding and Content-Length
917 // headers from 1.10+s wfOutputHandler
918 global $wgDisableOutputCompression;
919 $wgDisableOutputCompression = true;
920 }
921 while( $status = ob_get_status() ) {
922 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
923 // Probably from zlib.output_compression or other
924 // PHP-internal setting which can't be removed.
925 //
926 // Give up, and hope the result doesn't break
927 // output behavior.
928 break;
929 }
930 if( !ob_end_clean() ) {
931 // Could not remove output buffer handler; abort now
932 // to avoid getting in some kind of infinite loop.
933 break;
934 }
935 if( $resetGzipEncoding ) {
936 if( $status['name'] == 'ob_gzhandler' ) {
937 // Reset the 'Content-Encoding' field set by this handler
938 // so we can start fresh.
939 header( 'Content-Encoding:' );
940 }
941 }
942 }
943 }
944
945 /**
946 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
947 *
948 * Clear away output buffers, but keep the Content-Encoding header
949 * produced by ob_gzhandler, if any.
950 *
951 * This should be used for HTTP 304 responses, where you need to
952 * preserve the Content-Encoding header of the real result, but
953 * also need to suppress the output of ob_gzhandler to keep to spec
954 * and avoid breaking Firefox in rare cases where the headers and
955 * body are broken over two packets.
956 */
957 function wfClearOutputBuffers() {
958 wfResetOutputBuffers( false );
959 }
960
961 /**
962 * Converts an Accept-* header into an array mapping string values to quality
963 * factors
964 */
965 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
966 # No arg means accept anything (per HTTP spec)
967 if( !$accept ) {
968 return array( $def => 1.0 );
969 }
970
971 $prefs = array();
972
973 $parts = explode( ',', $accept );
974
975 foreach( $parts as $part ) {
976 # FIXME: doesn't deal with params like 'text/html; level=1'
977 @list( $value, $qpart ) = explode( ';', trim( $part ) );
978 $match = array();
979 if( !isset( $qpart ) ) {
980 $prefs[$value] = 1.0;
981 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
982 $prefs[$value] = floatval($match[1]);
983 }
984 }
985
986 return $prefs;
987 }
988
989 /**
990 * Checks if a given MIME type matches any of the keys in the given
991 * array. Basic wildcards are accepted in the array keys.
992 *
993 * Returns the matching MIME type (or wildcard) if a match, otherwise
994 * NULL if no match.
995 *
996 * @param string $type
997 * @param array $avail
998 * @return string
999 * @private
1000 */
1001 function mimeTypeMatch( $type, $avail ) {
1002 if( array_key_exists($type, $avail) ) {
1003 return $type;
1004 } else {
1005 $parts = explode( '/', $type );
1006 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1007 return $parts[0] . '/*';
1008 } elseif( array_key_exists( '*/*', $avail ) ) {
1009 return '*/*';
1010 } else {
1011 return NULL;
1012 }
1013 }
1014 }
1015
1016 /**
1017 * Returns the 'best' match between a client's requested internet media types
1018 * and the server's list of available types. Each list should be an associative
1019 * array of type to preference (preference is a float between 0.0 and 1.0).
1020 * Wildcards in the types are acceptable.
1021 *
1022 * @param array $cprefs Client's acceptable type list
1023 * @param array $sprefs Server's offered types
1024 * @return string
1025 *
1026 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1027 * XXX: generalize to negotiate other stuff
1028 */
1029 function wfNegotiateType( $cprefs, $sprefs ) {
1030 $combine = array();
1031
1032 foreach( array_keys($sprefs) as $type ) {
1033 $parts = explode( '/', $type );
1034 if( $parts[1] != '*' ) {
1035 $ckey = mimeTypeMatch( $type, $cprefs );
1036 if( $ckey ) {
1037 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1038 }
1039 }
1040 }
1041
1042 foreach( array_keys( $cprefs ) as $type ) {
1043 $parts = explode( '/', $type );
1044 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1045 $skey = mimeTypeMatch( $type, $sprefs );
1046 if( $skey ) {
1047 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1048 }
1049 }
1050 }
1051
1052 $bestq = 0;
1053 $besttype = NULL;
1054
1055 foreach( array_keys( $combine ) as $type ) {
1056 if( $combine[$type] > $bestq ) {
1057 $besttype = $type;
1058 $bestq = $combine[$type];
1059 }
1060 }
1061
1062 return $besttype;
1063 }
1064
1065 /**
1066 * Array lookup
1067 * Returns an array where the values in the first array are replaced by the
1068 * values in the second array with the corresponding keys
1069 *
1070 * @return array
1071 */
1072 function wfArrayLookup( $a, $b ) {
1073 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1074 }
1075
1076 /**
1077 * Convenience function; returns MediaWiki timestamp for the present time.
1078 * @return string
1079 */
1080 function wfTimestampNow() {
1081 # return NOW
1082 return wfTimestamp( TS_MW, time() );
1083 }
1084
1085 /**
1086 * Reference-counted warning suppression
1087 */
1088 function wfSuppressWarnings( $end = false ) {
1089 static $suppressCount = 0;
1090 static $originalLevel = false;
1091
1092 if ( $end ) {
1093 if ( $suppressCount ) {
1094 --$suppressCount;
1095 if ( !$suppressCount ) {
1096 error_reporting( $originalLevel );
1097 }
1098 }
1099 } else {
1100 if ( !$suppressCount ) {
1101 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1102 }
1103 ++$suppressCount;
1104 }
1105 }
1106
1107 /**
1108 * Restore error level to previous value
1109 */
1110 function wfRestoreWarnings() {
1111 wfSuppressWarnings( true );
1112 }
1113
1114 # Autodetect, convert and provide timestamps of various types
1115
1116 /**
1117 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1118 */
1119 define('TS_UNIX', 0);
1120
1121 /**
1122 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1123 */
1124 define('TS_MW', 1);
1125
1126 /**
1127 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1128 */
1129 define('TS_DB', 2);
1130
1131 /**
1132 * RFC 2822 format, for E-mail and HTTP headers
1133 */
1134 define('TS_RFC2822', 3);
1135
1136 /**
1137 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1138 *
1139 * This is used by Special:Export
1140 */
1141 define('TS_ISO_8601', 4);
1142
1143 /**
1144 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1145 *
1146 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1147 * DateTime tag and page 36 for the DateTimeOriginal and
1148 * DateTimeDigitized tags.
1149 */
1150 define('TS_EXIF', 5);
1151
1152 /**
1153 * Oracle format time.
1154 */
1155 define('TS_ORACLE', 6);
1156
1157 /**
1158 * Postgres format time.
1159 */
1160 define('TS_POSTGRES', 7);
1161
1162 /**
1163 * @param mixed $outputtype A timestamp in one of the supported formats, the
1164 * function will autodetect which format is supplied
1165 * and act accordingly.
1166 * @return string Time in the format specified in $outputtype
1167 */
1168 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1169 $uts = 0;
1170 $da = array();
1171 if ($ts==0) {
1172 $uts=time();
1173 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1174 # TS_DB
1175 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1176 # TS_EXIF
1177 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1178 # TS_MW
1179 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1180 # TS_UNIX
1181 $uts = $ts;
1182 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1183 # TS_ORACLE
1184 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1185 str_replace("+00:00", "UTC", $ts)));
1186 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1187 # TS_ISO_8601
1188 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1189 # TS_POSTGRES
1190 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1191 # TS_POSTGRES
1192 } else {
1193 # Bogus value; fall back to the epoch...
1194 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1195 $uts = 0;
1196 }
1197
1198 if (count( $da ) ) {
1199 // Warning! gmmktime() acts oddly if the month or day is set to 0
1200 // We may want to handle that explicitly at some point
1201 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1202 (int)$da[2],(int)$da[3],(int)$da[1]);
1203 }
1204
1205 switch($outputtype) {
1206 case TS_UNIX:
1207 return $uts;
1208 case TS_MW:
1209 return gmdate( 'YmdHis', $uts );
1210 case TS_DB:
1211 return gmdate( 'Y-m-d H:i:s', $uts );
1212 case TS_ISO_8601:
1213 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1214 // This shouldn't ever be used, but is included for completeness
1215 case TS_EXIF:
1216 return gmdate( 'Y:m:d H:i:s', $uts );
1217 case TS_RFC2822:
1218 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1219 case TS_ORACLE:
1220 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1221 case TS_POSTGRES:
1222 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1223 default:
1224 throw new MWException( 'wfTimestamp() called with illegal output type.');
1225 }
1226 }
1227
1228 /**
1229 * Return a formatted timestamp, or null if input is null.
1230 * For dealing with nullable timestamp columns in the database.
1231 * @param int $outputtype
1232 * @param string $ts
1233 * @return string
1234 */
1235 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1236 if( is_null( $ts ) ) {
1237 return null;
1238 } else {
1239 return wfTimestamp( $outputtype, $ts );
1240 }
1241 }
1242
1243 /**
1244 * Check if the operating system is Windows
1245 *
1246 * @return bool True if it's Windows, False otherwise.
1247 */
1248 function wfIsWindows() {
1249 if (substr(php_uname(), 0, 7) == 'Windows') {
1250 return true;
1251 } else {
1252 return false;
1253 }
1254 }
1255
1256 /**
1257 * Swap two variables
1258 */
1259 function swap( &$x, &$y ) {
1260 $z = $x;
1261 $x = $y;
1262 $y = $z;
1263 }
1264
1265 function wfGetCachedNotice( $name ) {
1266 global $wgOut, $parserMemc;
1267 $fname = 'wfGetCachedNotice';
1268 wfProfileIn( $fname );
1269
1270 $needParse = false;
1271
1272 if( $name === 'default' ) {
1273 // special case
1274 global $wgSiteNotice;
1275 $notice = $wgSiteNotice;
1276 if( empty( $notice ) ) {
1277 wfProfileOut( $fname );
1278 return false;
1279 }
1280 } else {
1281 $notice = wfMsgForContentNoTrans( $name );
1282 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1283 wfProfileOut( $fname );
1284 return( false );
1285 }
1286 }
1287
1288 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1289 if( is_array( $cachedNotice ) ) {
1290 if( md5( $notice ) == $cachedNotice['hash'] ) {
1291 $notice = $cachedNotice['html'];
1292 } else {
1293 $needParse = true;
1294 }
1295 } else {
1296 $needParse = true;
1297 }
1298
1299 if( $needParse ) {
1300 if( is_object( $wgOut ) ) {
1301 $parsed = $wgOut->parse( $notice );
1302 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1303 $notice = $parsed;
1304 } else {
1305 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1306 $notice = '';
1307 }
1308 }
1309
1310 wfProfileOut( $fname );
1311 return $notice;
1312 }
1313
1314 function wfGetNamespaceNotice() {
1315 global $wgTitle;
1316
1317 # Paranoia
1318 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1319 return "";
1320
1321 $fname = 'wfGetNamespaceNotice';
1322 wfProfileIn( $fname );
1323
1324 $key = "namespacenotice-" . $wgTitle->getNsText();
1325 $namespaceNotice = wfGetCachedNotice( $key );
1326 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1327 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1328 } else {
1329 $namespaceNotice = "";
1330 }
1331
1332 wfProfileOut( $fname );
1333 return $namespaceNotice;
1334 }
1335
1336 function wfGetSiteNotice() {
1337 global $wgUser, $wgSiteNotice;
1338 $fname = 'wfGetSiteNotice';
1339 wfProfileIn( $fname );
1340 $siteNotice = '';
1341
1342 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1343 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1344 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1345 } else {
1346 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1347 if( !$anonNotice ) {
1348 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1349 } else {
1350 $siteNotice = $anonNotice;
1351 }
1352 }
1353 if( !$siteNotice ) {
1354 $siteNotice = wfGetCachedNotice( 'default' );
1355 }
1356 }
1357
1358 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1359 wfProfileOut( $fname );
1360 return $siteNotice;
1361 }
1362
1363 /**
1364 * BC wrapper for MimeMagic::singleton()
1365 * @deprecated
1366 */
1367 function &wfGetMimeMagic() {
1368 return MimeMagic::singleton();
1369 }
1370
1371 /**
1372 * Tries to get the system directory for temporary files.
1373 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1374 * and if none are set /tmp is returned as the generic Unix default.
1375 *
1376 * NOTE: When possible, use the tempfile() function to create temporary
1377 * files to avoid race conditions on file creation, etc.
1378 *
1379 * @return string
1380 */
1381 function wfTempDir() {
1382 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1383 $tmp = getenv( $var );
1384 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1385 return $tmp;
1386 }
1387 }
1388 # Hope this is Unix of some kind!
1389 return '/tmp';
1390 }
1391
1392 /**
1393 * Make directory, and make all parent directories if they don't exist
1394 */
1395 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1396 if( strval( $fullDir ) === '' )
1397 return true;
1398 if( file_exists( $fullDir ) )
1399 return true;
1400
1401 # Go back through the paths to find the first directory that exists
1402 $currentDir = $fullDir;
1403 $createList = array();
1404 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1405 # Strip trailing slashes
1406 $currentDir = rtrim( $currentDir, '/\\' );
1407
1408 # Add to create list
1409 $createList[] = $currentDir;
1410
1411 # Find next delimiter searching from the end
1412 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1413 if ( $p === false ) {
1414 $currentDir = false;
1415 } else {
1416 $currentDir = substr( $currentDir, 0, $p );
1417 }
1418 }
1419
1420 if ( count( $createList ) == 0 ) {
1421 # Directory specified already exists
1422 return true;
1423 } elseif ( $currentDir === false ) {
1424 # Went all the way back to root and it apparently doesn't exist
1425 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1426 return false;
1427 }
1428 # Now go forward creating directories
1429 $createList = array_reverse( $createList );
1430
1431 # Is the parent directory writable?
1432 if ( $currentDir === '' ) {
1433 $currentDir = '/';
1434 }
1435 if ( !is_writable( $currentDir ) ) {
1436 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1437 return false;
1438 }
1439
1440 foreach ( $createList as $dir ) {
1441 # use chmod to override the umask, as suggested by the PHP manual
1442 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1443 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1444 return false;
1445 }
1446 }
1447 return true;
1448 }
1449
1450 /**
1451 * Increment a statistics counter
1452 */
1453 function wfIncrStats( $key ) {
1454 global $wgStatsMethod;
1455
1456 if( $wgStatsMethod == 'udp' ) {
1457 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1458 static $socket;
1459 if (!$socket) {
1460 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1461 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1462 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1463 }
1464 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1465 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1466 } elseif( $wgStatsMethod == 'cache' ) {
1467 global $wgMemc;
1468 $key = wfMemcKey( 'stats', $key );
1469 if ( is_null( $wgMemc->incr( $key ) ) ) {
1470 $wgMemc->add( $key, 1 );
1471 }
1472 } else {
1473 // Disabled
1474 }
1475 }
1476
1477 /**
1478 * @param mixed $nr The number to format
1479 * @param int $acc The number of digits after the decimal point, default 2
1480 * @param bool $round Whether or not to round the value, default true
1481 * @return float
1482 */
1483 function wfPercent( $nr, $acc = 2, $round = true ) {
1484 $ret = sprintf( "%.${acc}f", $nr );
1485 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1486 }
1487
1488 /**
1489 * Encrypt a username/password.
1490 *
1491 * @param string $userid ID of the user
1492 * @param string $password Password of the user
1493 * @return string Hashed password
1494 * @deprecated Use User::crypt() or User::oldCrypt() instead
1495 */
1496 function wfEncryptPassword( $userid, $password ) {
1497 wfDeprecated(__FUNCTION__);
1498 # Just wrap around User::oldCrypt()
1499 return User::oldCrypt($password, $userid);
1500 }
1501
1502 /**
1503 * Appends to second array if $value differs from that in $default
1504 */
1505 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1506 if ( is_null( $changed ) ) {
1507 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1508 }
1509 if ( $default[$key] !== $value ) {
1510 $changed[$key] = $value;
1511 }
1512 }
1513
1514 /**
1515 * Since wfMsg() and co suck, they don't return false if the message key they
1516 * looked up didn't exist but a XHTML string, this function checks for the
1517 * nonexistance of messages by looking at wfMsg() output
1518 *
1519 * @param $msg The message key looked up
1520 * @param $wfMsgOut The output of wfMsg*()
1521 * @return bool
1522 */
1523 function wfEmptyMsg( $msg, $wfMsgOut ) {
1524 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1525 }
1526
1527 /**
1528 * Find out whether or not a mixed variable exists in a string
1529 *
1530 * @param mixed needle
1531 * @param string haystack
1532 * @return bool
1533 */
1534 function in_string( $needle, $str ) {
1535 return strpos( $str, $needle ) !== false;
1536 }
1537
1538 function wfSpecialList( $page, $details ) {
1539 global $wgContLang;
1540 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1541 return $page . $details;
1542 }
1543
1544 /**
1545 * Returns a regular expression of url protocols
1546 *
1547 * @return string
1548 */
1549 function wfUrlProtocols() {
1550 global $wgUrlProtocols;
1551
1552 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1553 // with LocalSettings files from 1.5
1554 if ( is_array( $wgUrlProtocols ) ) {
1555 $protocols = array();
1556 foreach ($wgUrlProtocols as $protocol)
1557 $protocols[] = preg_quote( $protocol, '/' );
1558
1559 return implode( '|', $protocols );
1560 } else {
1561 return $wgUrlProtocols;
1562 }
1563 }
1564
1565 /**
1566 * Safety wrapper around ini_get() for boolean settings.
1567 * The values returned from ini_get() are pre-normalized for settings
1568 * set via php.ini or php_flag/php_admin_flag... but *not*
1569 * for those set via php_value/php_admin_value.
1570 *
1571 * It's fairly common for people to use php_value instead of php_flag,
1572 * which can leave you with an 'off' setting giving a false positive
1573 * for code that just takes the ini_get() return value as a boolean.
1574 *
1575 * To make things extra interesting, setting via php_value accepts
1576 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1577 * Unrecognized values go false... again opposite PHP's own coercion
1578 * from string to bool.
1579 *
1580 * Luckily, 'properly' set settings will always come back as '0' or '1',
1581 * so we only have to worry about them and the 'improper' settings.
1582 *
1583 * I frickin' hate PHP... :P
1584 *
1585 * @param string $setting
1586 * @return bool
1587 */
1588 function wfIniGetBool( $setting ) {
1589 $val = ini_get( $setting );
1590 // 'on' and 'true' can't have whitespace around them, but '1' can.
1591 return strtolower( $val ) == 'on'
1592 || strtolower( $val ) == 'true'
1593 || strtolower( $val ) == 'yes'
1594 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1595 }
1596
1597 /**
1598 * Execute a shell command, with time and memory limits mirrored from the PHP
1599 * configuration if supported.
1600 * @param $cmd Command line, properly escaped for shell.
1601 * @param &$retval optional, will receive the program's exit code.
1602 * (non-zero is usually failure)
1603 * @return collected stdout as a string (trailing newlines stripped)
1604 */
1605 function wfShellExec( $cmd, &$retval=null ) {
1606 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1607
1608 if( wfIniGetBool( 'safe_mode' ) ) {
1609 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1610 $retval = 1;
1611 return "Unable to run external programs in safe mode.";
1612 }
1613
1614 if ( php_uname( 's' ) == 'Linux' ) {
1615 $time = intval( ini_get( 'max_execution_time' ) );
1616 $mem = intval( $wgMaxShellMemory );
1617 $filesize = intval( $wgMaxShellFileSize );
1618
1619 if ( $time > 0 && $mem > 0 ) {
1620 $script = "$IP/bin/ulimit4.sh";
1621 if ( is_executable( $script ) ) {
1622 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1623 }
1624 }
1625 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1626 # This is a hack to work around PHP's flawed invocation of cmd.exe
1627 # http://news.php.net/php.internals/21796
1628 $cmd = '"' . $cmd . '"';
1629 }
1630 wfDebug( "wfShellExec: $cmd\n" );
1631
1632 $retval = 1; // error by default?
1633 ob_start();
1634 passthru( $cmd, $retval );
1635 $output = ob_get_contents();
1636 ob_end_clean();
1637 return $output;
1638
1639 }
1640
1641 /**
1642 * This function works like "use VERSION" in Perl, the program will die with a
1643 * backtrace if the current version of PHP is less than the version provided
1644 *
1645 * This is useful for extensions which due to their nature are not kept in sync
1646 * with releases, and might depend on other versions of PHP than the main code
1647 *
1648 * Note: PHP might die due to parsing errors in some cases before it ever
1649 * manages to call this function, such is life
1650 *
1651 * @see perldoc -f use
1652 *
1653 * @param mixed $version The version to check, can be a string, an integer, or
1654 * a float
1655 */
1656 function wfUsePHP( $req_ver ) {
1657 $php_ver = PHP_VERSION;
1658
1659 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1660 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1661 }
1662
1663 /**
1664 * This function works like "use VERSION" in Perl except it checks the version
1665 * of MediaWiki, the program will die with a backtrace if the current version
1666 * of MediaWiki is less than the version provided.
1667 *
1668 * This is useful for extensions which due to their nature are not kept in sync
1669 * with releases
1670 *
1671 * @see perldoc -f use
1672 *
1673 * @param mixed $version The version to check, can be a string, an integer, or
1674 * a float
1675 */
1676 function wfUseMW( $req_ver ) {
1677 global $wgVersion;
1678
1679 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1680 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1681 }
1682
1683 /**
1684 * @deprecated use StringUtils::escapeRegexReplacement
1685 */
1686 function wfRegexReplacement( $string ) {
1687 return StringUtils::escapeRegexReplacement( $string );
1688 }
1689
1690 /**
1691 * Return the final portion of a pathname.
1692 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1693 * http://bugs.php.net/bug.php?id=33898
1694 *
1695 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1696 * We'll consider it so always, as we don't want \s in our Unix paths either.
1697 *
1698 * @param string $path
1699 * @param string $suffix to remove if present
1700 * @return string
1701 */
1702 function wfBaseName( $path, $suffix='' ) {
1703 $encSuffix = ($suffix == '')
1704 ? ''
1705 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1706 $matches = array();
1707 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1708 return $matches[1];
1709 } else {
1710 return '';
1711 }
1712 }
1713
1714 /**
1715 * Generate a relative path name to the given file.
1716 * May explode on non-matching case-insensitive paths,
1717 * funky symlinks, etc.
1718 *
1719 * @param string $path Absolute destination path including target filename
1720 * @param string $from Absolute source path, directory only
1721 * @return string
1722 */
1723 function wfRelativePath( $path, $from ) {
1724 // Normalize mixed input on Windows...
1725 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1726 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1727
1728 // Trim trailing slashes -- fix for drive root
1729 $path = rtrim( $path, DIRECTORY_SEPARATOR );
1730 $from = rtrim( $from, DIRECTORY_SEPARATOR );
1731
1732 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1733 $against = explode( DIRECTORY_SEPARATOR, $from );
1734
1735 if( $pieces[0] !== $against[0] ) {
1736 // Non-matching Windows drive letters?
1737 // Return a full path.
1738 return $path;
1739 }
1740
1741 // Trim off common prefix
1742 while( count( $pieces ) && count( $against )
1743 && $pieces[0] == $against[0] ) {
1744 array_shift( $pieces );
1745 array_shift( $against );
1746 }
1747
1748 // relative dots to bump us to the parent
1749 while( count( $against ) ) {
1750 array_unshift( $pieces, '..' );
1751 array_shift( $against );
1752 }
1753
1754 array_push( $pieces, wfBaseName( $path ) );
1755
1756 return implode( DIRECTORY_SEPARATOR, $pieces );
1757 }
1758
1759 /**
1760 * array_merge() does awful things with "numeric" indexes, including
1761 * string indexes when happen to look like integers. When we want
1762 * to merge arrays with arbitrary string indexes, we don't want our
1763 * arrays to be randomly corrupted just because some of them consist
1764 * of numbers.
1765 *
1766 * Fuck you, PHP. Fuck you in the ear!
1767 *
1768 * @param array $array1, [$array2, [...]]
1769 * @return array
1770 */
1771 function wfArrayMerge( $array1/* ... */ ) {
1772 $out = $array1;
1773 for( $i = 1; $i < func_num_args(); $i++ ) {
1774 foreach( func_get_arg( $i ) as $key => $value ) {
1775 $out[$key] = $value;
1776 }
1777 }
1778 return $out;
1779 }
1780
1781 /**
1782 * Make a URL index, appropriate for the el_index field of externallinks.
1783 */
1784 function wfMakeUrlIndex( $url ) {
1785 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1786 wfSuppressWarnings();
1787 $bits = parse_url( $url );
1788 wfRestoreWarnings();
1789 if ( !$bits ) {
1790 return false;
1791 }
1792 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1793 $delimiter = '';
1794 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1795 $delimiter = '://';
1796 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1797 $delimiter = ':';
1798 // parse_url detects for news: and mailto: the host part of an url as path
1799 // We have to correct this wrong detection
1800 if ( isset ( $bits['path'] ) ) {
1801 $bits['host'] = $bits['path'];
1802 $bits['path'] = '';
1803 }
1804 } else {
1805 return false;
1806 }
1807
1808 // Reverse the labels in the hostname, convert to lower case
1809 // For emails reverse domainpart only
1810 if ( $bits['scheme'] == 'mailto' ) {
1811 $mailparts = explode( '@', $bits['host'], 2 );
1812 if ( count($mailparts) === 2 ) {
1813 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1814 } else {
1815 // No domain specified, don't mangle it
1816 $domainpart = '';
1817 }
1818 $reversedHost = $domainpart . '@' . $mailparts[0];
1819 } else {
1820 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1821 }
1822 // Add an extra dot to the end
1823 // Why? Is it in wrong place in mailto links?
1824 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1825 $reversedHost .= '.';
1826 }
1827 // Reconstruct the pseudo-URL
1828 $prot = $bits['scheme'];
1829 $index = "$prot$delimiter$reversedHost";
1830 // Leave out user and password. Add the port, path, query and fragment
1831 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1832 if ( isset( $bits['path'] ) ) {
1833 $index .= $bits['path'];
1834 } else {
1835 $index .= '/';
1836 }
1837 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1838 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1839 return $index;
1840 }
1841
1842 /**
1843 * Do any deferred updates and clear the list
1844 * TODO: This could be in Wiki.php if that class made any sense at all
1845 */
1846 function wfDoUpdates()
1847 {
1848 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1849 foreach ( $wgDeferredUpdateList as $update ) {
1850 $update->doUpdate();
1851 }
1852 foreach ( $wgPostCommitUpdateList as $update ) {
1853 $update->doUpdate();
1854 }
1855 $wgDeferredUpdateList = array();
1856 $wgPostCommitUpdateList = array();
1857 }
1858
1859 /**
1860 * @deprecated use StringUtils::explodeMarkup
1861 */
1862 function wfExplodeMarkup( $separator, $text ) {
1863 return StringUtils::explodeMarkup( $separator, $text );
1864 }
1865
1866 /**
1867 * Convert an arbitrarily-long digit string from one numeric base
1868 * to another, optionally zero-padding to a minimum column width.
1869 *
1870 * Supports base 2 through 36; digit values 10-36 are represented
1871 * as lowercase letters a-z. Input is case-insensitive.
1872 *
1873 * @param $input string of digits
1874 * @param $sourceBase int 2-36
1875 * @param $destBase int 2-36
1876 * @param $pad int 1 or greater
1877 * @param $lowercase bool
1878 * @return string or false on invalid input
1879 */
1880 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
1881 $input = strval( $input );
1882 if( $sourceBase < 2 ||
1883 $sourceBase > 36 ||
1884 $destBase < 2 ||
1885 $destBase > 36 ||
1886 $pad < 1 ||
1887 $sourceBase != intval( $sourceBase ) ||
1888 $destBase != intval( $destBase ) ||
1889 $pad != intval( $pad ) ||
1890 !is_string( $input ) ||
1891 $input == '' ) {
1892 return false;
1893 }
1894 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
1895 $inDigits = array();
1896 $outChars = '';
1897
1898 // Decode and validate input string
1899 $input = strtolower( $input );
1900 for( $i = 0; $i < strlen( $input ); $i++ ) {
1901 $n = strpos( $digitChars, $input{$i} );
1902 if( $n === false || $n > $sourceBase ) {
1903 return false;
1904 }
1905 $inDigits[] = $n;
1906 }
1907
1908 // Iterate over the input, modulo-ing out an output digit
1909 // at a time until input is gone.
1910 while( count( $inDigits ) ) {
1911 $work = 0;
1912 $workDigits = array();
1913
1914 // Long division...
1915 foreach( $inDigits as $digit ) {
1916 $work *= $sourceBase;
1917 $work += $digit;
1918
1919 if( $work < $destBase ) {
1920 // Gonna need to pull another digit.
1921 if( count( $workDigits ) ) {
1922 // Avoid zero-padding; this lets us find
1923 // the end of the input very easily when
1924 // length drops to zero.
1925 $workDigits[] = 0;
1926 }
1927 } else {
1928 // Finally! Actual division!
1929 $workDigits[] = intval( $work / $destBase );
1930
1931 // Isn't it annoying that most programming languages
1932 // don't have a single divide-and-remainder operator,
1933 // even though the CPU implements it that way?
1934 $work = $work % $destBase;
1935 }
1936 }
1937
1938 // All that division leaves us with a remainder,
1939 // which is conveniently our next output digit.
1940 $outChars .= $digitChars[$work];
1941
1942 // And we continue!
1943 $inDigits = $workDigits;
1944 }
1945
1946 while( strlen( $outChars ) < $pad ) {
1947 $outChars .= '0';
1948 }
1949
1950 return strrev( $outChars );
1951 }
1952
1953 /**
1954 * Create an object with a given name and an array of construct parameters
1955 * @param string $name
1956 * @param array $p parameters
1957 */
1958 function wfCreateObject( $name, $p ){
1959 $p = array_values( $p );
1960 switch ( count( $p ) ) {
1961 case 0:
1962 return new $name;
1963 case 1:
1964 return new $name( $p[0] );
1965 case 2:
1966 return new $name( $p[0], $p[1] );
1967 case 3:
1968 return new $name( $p[0], $p[1], $p[2] );
1969 case 4:
1970 return new $name( $p[0], $p[1], $p[2], $p[3] );
1971 case 5:
1972 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1973 case 6:
1974 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
1975 default:
1976 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
1977 }
1978 }
1979
1980 /**
1981 * Alias for modularized function
1982 * @deprecated Use Http::get() instead
1983 */
1984 function wfGetHTTP( $url, $timeout = 'default' ) {
1985 wfDeprecated(__FUNCTION__);
1986 return Http::get( $url, $timeout );
1987 }
1988
1989 /**
1990 * Alias for modularized function
1991 * @deprecated Use Http::isLocalURL() instead
1992 */
1993 function wfIsLocalURL( $url ) {
1994 wfDeprecated(__FUNCTION__);
1995 return Http::isLocalURL( $url );
1996 }
1997
1998 function wfHttpOnlySafe() {
1999 global $wgHttpOnlyBlacklist;
2000 if( !version_compare("5.2", PHP_VERSION, "<") )
2001 return false;
2002
2003 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2004 foreach( $wgHttpOnlyBlacklist as $regex ) {
2005 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2006 return false;
2007 }
2008 }
2009 }
2010
2011 return true;
2012 }
2013
2014 /**
2015 * Initialise php session
2016 */
2017 function wfSetupSession() {
2018 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2019 if( $wgSessionsInMemcached ) {
2020 require_once( 'MemcachedSessions.php' );
2021 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2022 # If it's left on 'user' or another setting from another
2023 # application, it will end up failing. Try to recover.
2024 ini_set ( 'session.save_handler', 'files' );
2025 }
2026 $httpOnlySafe = wfHttpOnlySafe();
2027 wfDebugLog( 'cookie',
2028 'session_set_cookie_params: "' . implode( '", "',
2029 array(
2030 0,
2031 $wgCookiePath,
2032 $wgCookieDomain,
2033 $wgCookieSecure,
2034 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2035 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2036 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2037 } else {
2038 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2039 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2040 }
2041 session_cache_limiter( 'private, must-revalidate' );
2042 wfSuppressWarnings();
2043 session_start();
2044 wfRestoreWarnings();
2045 }
2046
2047 /**
2048 * Get an object from the precompiled serialized directory
2049 *
2050 * @return mixed The variable on success, false on failure
2051 */
2052 function wfGetPrecompiledData( $name ) {
2053 global $IP;
2054
2055 $file = "$IP/serialized/$name";
2056 if ( file_exists( $file ) ) {
2057 $blob = file_get_contents( $file );
2058 if ( $blob ) {
2059 return unserialize( $blob );
2060 }
2061 }
2062 return false;
2063 }
2064
2065 function wfGetCaller( $level = 2 ) {
2066 $backtrace = wfDebugBacktrace();
2067 if ( isset( $backtrace[$level] ) ) {
2068 return wfFormatStackFrame($backtrace[$level]);
2069 } else {
2070 $caller = 'unknown';
2071 }
2072 return $caller;
2073 }
2074
2075 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2076 function wfGetAllCallers() {
2077 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2078 }
2079
2080 /** Return a string representation of frame */
2081 function wfFormatStackFrame($frame) {
2082 return isset( $frame["class"] )?
2083 $frame["class"]."::".$frame["function"]:
2084 $frame["function"];
2085 }
2086
2087 /**
2088 * Get a cache key
2089 */
2090 function wfMemcKey( /*... */ ) {
2091 $args = func_get_args();
2092 $key = wfWikiID() . ':' . implode( ':', $args );
2093 return $key;
2094 }
2095
2096 /**
2097 * Get a cache key for a foreign DB
2098 */
2099 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2100 $args = array_slice( func_get_args(), 2 );
2101 if ( $prefix ) {
2102 $key = "$db-$prefix:" . implode( ':', $args );
2103 } else {
2104 $key = $db . ':' . implode( ':', $args );
2105 }
2106 return $key;
2107 }
2108
2109 /**
2110 * Get an ASCII string identifying this wiki
2111 * This is used as a prefix in memcached keys
2112 */
2113 function wfWikiID( $db = null ) {
2114 if( $db instanceof Database ) {
2115 return $db->getWikiID();
2116 } else {
2117 global $wgDBprefix, $wgDBname;
2118 if ( $wgDBprefix ) {
2119 return "$wgDBname-$wgDBprefix";
2120 } else {
2121 return $wgDBname;
2122 }
2123 }
2124 }
2125
2126 /**
2127 * Split a wiki ID into DB name and table prefix
2128 */
2129 function wfSplitWikiID( $wiki ) {
2130 $bits = explode( '-', $wiki, 2 );
2131 if ( count( $bits ) < 2 ) {
2132 $bits[] = '';
2133 }
2134 return $bits;
2135 }
2136
2137 /*
2138 * Get a Database object.
2139 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2140 * master (for write queries), DB_SLAVE for potentially lagged
2141 * read queries, or an integer >= 0 for a particular server.
2142 *
2143 * @param mixed $groups Query groups. An array of group names that this query
2144 * belongs to. May contain a single string if the query is only
2145 * in one group.
2146 *
2147 * @param string $wiki The wiki ID, or false for the current wiki
2148 *
2149 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2150 * will always return the same object, unless the underlying connection or load
2151 * balancer is manually destroyed.
2152 */
2153 function &wfGetDB( $db = DB_LAST, $groups = array(), $wiki = false ) {
2154 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2155 }
2156
2157 /**
2158 * Get a load balancer object.
2159 *
2160 * @param array $groups List of query groups
2161 * @param string $wiki Wiki ID, or false for the current wiki
2162 * @return LoadBalancer
2163 */
2164 function wfGetLB( $wiki = false ) {
2165 return wfGetLBFactory()->getMainLB( $wiki );
2166 }
2167
2168 /**
2169 * Get the load balancer factory object
2170 */
2171 function &wfGetLBFactory() {
2172 return LBFactory::singleton();
2173 }
2174
2175 /**
2176 * Find a file.
2177 * Shortcut for RepoGroup::singleton()->findFile()
2178 * @param mixed $title Title object or string. May be interwiki.
2179 * @param mixed $time Requested time for an archived image, or false for the
2180 * current version. An image object will be returned which
2181 * was created at the specified time.
2182 * @param mixed $flags FileRepo::FIND_ flags
2183 * @return File, or false if the file does not exist
2184 */
2185 function wfFindFile( $title, $time = false, $flags = 0 ) {
2186 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2187 }
2188
2189 /**
2190 * Get an object referring to a locally registered file.
2191 * Returns a valid placeholder object if the file does not exist.
2192 */
2193 function wfLocalFile( $title ) {
2194 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2195 }
2196
2197 /**
2198 * Should low-performance queries be disabled?
2199 *
2200 * @return bool
2201 */
2202 function wfQueriesMustScale() {
2203 global $wgMiserMode;
2204 return $wgMiserMode
2205 || ( SiteStats::pages() > 100000
2206 && SiteStats::edits() > 1000000
2207 && SiteStats::users() > 10000 );
2208 }
2209
2210 /**
2211 * Get the path to a specified script file, respecting file
2212 * extensions; this is a wrapper around $wgScriptExtension etc.
2213 *
2214 * @param string $script Script filename, sans extension
2215 * @return string
2216 */
2217 function wfScript( $script = 'index' ) {
2218 global $wgScriptPath, $wgScriptExtension;
2219 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2220 }
2221
2222 /**
2223 * Convenience function converts boolean values into "true"
2224 * or "false" (string) values
2225 *
2226 * @param bool $value
2227 * @return string
2228 */
2229 function wfBoolToStr( $value ) {
2230 return $value ? 'true' : 'false';
2231 }
2232
2233 /**
2234 * Load an extension messages file
2235 *
2236 * @param string $extensionName Name of extension to load messages from\for.
2237 * @param string $langcode Language to load messages for, or false for default
2238 * behvaiour (en, content language and user language).
2239 */
2240 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2241 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2242
2243 #For recording whether extension message files have been loaded in a given language.
2244 static $loaded = array();
2245
2246 if( !array_key_exists( $extensionName, $loaded ) ) {
2247 $loaded[$extensionName] = array();
2248 }
2249
2250 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2251 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2252 }
2253
2254 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2255 # Just do en, content language and user language.
2256 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2257 # Mark that they have been loaded.
2258 $loaded[$extensionName]['en'] = true;
2259 $loaded[$extensionName][$wgLang->getCode()] = true;
2260 $loaded[$extensionName][$wgContLang->getCode()] = true;
2261 # Mark that this part has been done to avoid weird if statements.
2262 $loaded[$extensionName]['*'] = true;
2263 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2264 # Load messages for specified language.
2265 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2266 # Mark that they have been loaded.
2267 $loaded[$extensionName][$langcode] = true;
2268 }
2269 }
2270
2271 /**
2272 * Get a platform-independent path to the null file, e.g.
2273 * /dev/null
2274 *
2275 * @return string
2276 */
2277 function wfGetNull() {
2278 return wfIsWindows()
2279 ? 'NUL'
2280 : '/dev/null';
2281 }
2282
2283 /**
2284 * Displays a maxlag error
2285 *
2286 * @param string $host Server that lags the most
2287 * @param int $lag Maxlag (actual)
2288 * @param int $maxLag Maxlag (requested)
2289 */
2290 function wfMaxlagError( $host, $lag, $maxLag ) {
2291 global $wgShowHostnames;
2292 header( 'HTTP/1.1 503 Service Unavailable' );
2293 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2294 header( 'X-Database-Lag: ' . intval( $lag ) );
2295 header( 'Content-Type: text/plain' );
2296 if( $wgShowHostnames ) {
2297 echo "Waiting for $host: $lag seconds lagged\n";
2298 } else {
2299 echo "Waiting for a database server: $lag seconds lagged\n";
2300 }
2301 }
2302
2303 /**
2304 * Throws an E_USER_NOTICE saying that $function is deprecated
2305 * @param string $function
2306 * @return null
2307 */
2308 function wfDeprecated( $function ) {
2309 global $wgDebugLogFile;
2310 if ( !$wgDebugLogFile ) {
2311 return;
2312 }
2313 $callers = wfDebugBacktrace();
2314 if( isset( $callers[2] ) ){
2315 $callerfunc = $callers[2];
2316 $callerfile = $callers[1];
2317 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2318 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2319 } else {
2320 $file = '(internal function)';
2321 }
2322 $func = '';
2323 if( isset( $callerfunc['class'] ) )
2324 $func .= $callerfunc['class'] . '::';
2325 $func .= @$callerfunc['function'];
2326 $msg = "Use of $function is deprecated. Called from $func in $file";
2327 } else {
2328 $msg = "Use of $function is deprecated.";
2329 }
2330 wfDebug( "$msg\n" );
2331 }
2332
2333 /**
2334 * Sleep until the worst slave's replication lag is less than or equal to
2335 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2336 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2337 * a no-op if there are no slaves.
2338 *
2339 * Every time the function has to wait for a slave, it will print a message to
2340 * that effect (and then sleep for a little while), so it's probably not best
2341 * to use this outside maintenance scripts in its present form.
2342 *
2343 * @param int $maxLag
2344 * @return null
2345 */
2346 function wfWaitForSlaves( $maxLag ) {
2347 if( $maxLag ) {
2348 $lb = wfGetLB();
2349 list( $host, $lag ) = $lb->getMaxLag();
2350 while( $lag > $maxLag ) {
2351 $name = @gethostbyaddr( $host );
2352 if( $name !== false ) {
2353 $host = $name;
2354 }
2355 print "Waiting for $host (lagged $lag seconds)...\n";
2356 sleep($maxLag);
2357 list( $host, $lag ) = $lb->getMaxLag();
2358 }
2359 }
2360 }
2361
2362 /** Generate a random 32-character hexadecimal token.
2363 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2364 */
2365 function wfGenerateToken( $salt = '' ) {
2366 $salt = serialize($salt);
2367
2368 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2369 }
2370
2371 /**
2372 * Replace all invalid characters with -
2373 * @param mixed $title Filename to process
2374 */
2375 function wfStripIllegalFilenameChars( $name ) {
2376 $name = wfBaseName( $name );
2377 $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
2378 return $name;
2379 }