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