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