Refactor RC2UDP code some
[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, $wgRenderHashAppend, $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 // Use the extra hash appender to let eg SSL variants separately cache.
1767 $key = wfMemcKey( $name . $wgRenderHashAppend );
1768 $cachedNotice = $parserMemc->get( $key );
1769 if( is_array( $cachedNotice ) ) {
1770 if( md5( $notice ) == $cachedNotice['hash'] ) {
1771 $notice = $cachedNotice['html'];
1772 } else {
1773 $needParse = true;
1774 }
1775 } else {
1776 $needParse = true;
1777 }
1778
1779 if( $needParse ) {
1780 if( is_object( $wgOut ) ) {
1781 $parsed = $wgOut->parse( $notice );
1782 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1783 $notice = $parsed;
1784 } else {
1785 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1786 $notice = '';
1787 }
1788 }
1789
1790 wfProfileOut( $fname );
1791 return $notice;
1792 }
1793
1794 function wfGetNamespaceNotice() {
1795 global $wgTitle;
1796
1797 # Paranoia
1798 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1799 return "";
1800
1801 $fname = 'wfGetNamespaceNotice';
1802 wfProfileIn( $fname );
1803
1804 $key = "namespacenotice-" . $wgTitle->getNsText();
1805 $namespaceNotice = wfGetCachedNotice( $key );
1806 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1807 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1808 } else {
1809 $namespaceNotice = "";
1810 }
1811
1812 wfProfileOut( $fname );
1813 return $namespaceNotice;
1814 }
1815
1816 function wfGetSiteNotice() {
1817 global $wgUser, $wgSiteNotice;
1818 $fname = 'wfGetSiteNotice';
1819 wfProfileIn( $fname );
1820 $siteNotice = '';
1821
1822 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1823 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1824 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1825 } else {
1826 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1827 if( !$anonNotice ) {
1828 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1829 } else {
1830 $siteNotice = $anonNotice;
1831 }
1832 }
1833 if( !$siteNotice ) {
1834 $siteNotice = wfGetCachedNotice( 'default' );
1835 }
1836 }
1837
1838 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1839 wfProfileOut( $fname );
1840 return $siteNotice;
1841 }
1842
1843 /**
1844 * BC wrapper for MimeMagic::singleton()
1845 * @deprecated
1846 */
1847 function &wfGetMimeMagic() {
1848 return MimeMagic::singleton();
1849 }
1850
1851 /**
1852 * Tries to get the system directory for temporary files.
1853 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1854 * and if none are set /tmp is returned as the generic Unix default.
1855 *
1856 * NOTE: When possible, use the tempfile() function to create temporary
1857 * files to avoid race conditions on file creation, etc.
1858 *
1859 * @return string
1860 */
1861 function wfTempDir() {
1862 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1863 $tmp = getenv( $var );
1864 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1865 return $tmp;
1866 }
1867 }
1868 # Hope this is Unix of some kind!
1869 return '/tmp';
1870 }
1871
1872 /**
1873 * Make directory, and make all parent directories if they don't exist
1874 *
1875 * @param string $fullDir Full path to directory to create
1876 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1877 * @return bool
1878 */
1879 function wfMkdirParents( $fullDir, $mode = null ) {
1880 global $wgDirectoryMode;
1881 if( strval( $fullDir ) === '' )
1882 return true;
1883 if( file_exists( $fullDir ) )
1884 return true;
1885 // If not defined or isn't an int, set to default
1886 if ( is_null( $mode ) ) {
1887 $mode = $wgDirectoryMode;
1888 }
1889
1890
1891 # Go back through the paths to find the first directory that exists
1892 $currentDir = $fullDir;
1893 $createList = array();
1894 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1895 # Strip trailing slashes
1896 $currentDir = rtrim( $currentDir, '/\\' );
1897
1898 # Add to create list
1899 $createList[] = $currentDir;
1900
1901 # Find next delimiter searching from the end
1902 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1903 if ( $p === false ) {
1904 $currentDir = false;
1905 } else {
1906 $currentDir = substr( $currentDir, 0, $p );
1907 }
1908 }
1909
1910 if ( count( $createList ) == 0 ) {
1911 # Directory specified already exists
1912 return true;
1913 } elseif ( $currentDir === false ) {
1914 # Went all the way back to root and it apparently doesn't exist
1915 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1916 return false;
1917 }
1918 # Now go forward creating directories
1919 $createList = array_reverse( $createList );
1920
1921 # Is the parent directory writable?
1922 if ( $currentDir === '' ) {
1923 $currentDir = '/';
1924 }
1925 if ( !is_writable( $currentDir ) ) {
1926 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1927 return false;
1928 }
1929
1930 foreach ( $createList as $dir ) {
1931 # use chmod to override the umask, as suggested by the PHP manual
1932 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1933 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1934 return false;
1935 }
1936 }
1937 return true;
1938 }
1939
1940 /**
1941 * Increment a statistics counter
1942 */
1943 function wfIncrStats( $key ) {
1944 global $wgStatsMethod;
1945
1946 if( $wgStatsMethod == 'udp' ) {
1947 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1948 static $socket;
1949 if (!$socket) {
1950 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1951 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1952 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1953 }
1954 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1955 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1956 } elseif( $wgStatsMethod == 'cache' ) {
1957 global $wgMemc;
1958 $key = wfMemcKey( 'stats', $key );
1959 if ( is_null( $wgMemc->incr( $key ) ) ) {
1960 $wgMemc->add( $key, 1 );
1961 }
1962 } else {
1963 // Disabled
1964 }
1965 }
1966
1967 /**
1968 * @param mixed $nr The number to format
1969 * @param int $acc The number of digits after the decimal point, default 2
1970 * @param bool $round Whether or not to round the value, default true
1971 * @return float
1972 */
1973 function wfPercent( $nr, $acc = 2, $round = true ) {
1974 $ret = sprintf( "%.${acc}f", $nr );
1975 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1976 }
1977
1978 /**
1979 * Encrypt a username/password.
1980 *
1981 * @param string $userid ID of the user
1982 * @param string $password Password of the user
1983 * @return string Hashed password
1984 * @deprecated Use User::crypt() or User::oldCrypt() instead
1985 */
1986 function wfEncryptPassword( $userid, $password ) {
1987 wfDeprecated(__FUNCTION__);
1988 # Just wrap around User::oldCrypt()
1989 return User::oldCrypt($password, $userid);
1990 }
1991
1992 /**
1993 * Appends to second array if $value differs from that in $default
1994 */
1995 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1996 if ( is_null( $changed ) ) {
1997 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1998 }
1999 if ( $default[$key] !== $value ) {
2000 $changed[$key] = $value;
2001 }
2002 }
2003
2004 /**
2005 * Since wfMsg() and co suck, they don't return false if the message key they
2006 * looked up didn't exist but a XHTML string, this function checks for the
2007 * nonexistance of messages by looking at wfMsg() output
2008 *
2009 * @param $msg The message key looked up
2010 * @param $wfMsgOut The output of wfMsg*()
2011 * @return bool
2012 */
2013 function wfEmptyMsg( $msg, $wfMsgOut ) {
2014 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2015 }
2016
2017 /**
2018 * Find out whether or not a mixed variable exists in a string
2019 *
2020 * @param mixed needle
2021 * @param string haystack
2022 * @return bool
2023 */
2024 function in_string( $needle, $str ) {
2025 return strpos( $str, $needle ) !== false;
2026 }
2027
2028 function wfSpecialList( $page, $details ) {
2029 global $wgContLang;
2030 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
2031 return $page . $details;
2032 }
2033
2034 /**
2035 * Returns a regular expression of url protocols
2036 *
2037 * @return string
2038 */
2039 function wfUrlProtocols() {
2040 global $wgUrlProtocols;
2041
2042 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2043 // with LocalSettings files from 1.5
2044 if ( is_array( $wgUrlProtocols ) ) {
2045 $protocols = array();
2046 foreach ($wgUrlProtocols as $protocol)
2047 $protocols[] = preg_quote( $protocol, '/' );
2048
2049 return implode( '|', $protocols );
2050 } else {
2051 return $wgUrlProtocols;
2052 }
2053 }
2054
2055 /**
2056 * Safety wrapper around ini_get() for boolean settings.
2057 * The values returned from ini_get() are pre-normalized for settings
2058 * set via php.ini or php_flag/php_admin_flag... but *not*
2059 * for those set via php_value/php_admin_value.
2060 *
2061 * It's fairly common for people to use php_value instead of php_flag,
2062 * which can leave you with an 'off' setting giving a false positive
2063 * for code that just takes the ini_get() return value as a boolean.
2064 *
2065 * To make things extra interesting, setting via php_value accepts
2066 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2067 * Unrecognized values go false... again opposite PHP's own coercion
2068 * from string to bool.
2069 *
2070 * Luckily, 'properly' set settings will always come back as '0' or '1',
2071 * so we only have to worry about them and the 'improper' settings.
2072 *
2073 * I frickin' hate PHP... :P
2074 *
2075 * @param string $setting
2076 * @return bool
2077 */
2078 function wfIniGetBool( $setting ) {
2079 $val = ini_get( $setting );
2080 // 'on' and 'true' can't have whitespace around them, but '1' can.
2081 return strtolower( $val ) == 'on'
2082 || strtolower( $val ) == 'true'
2083 || strtolower( $val ) == 'yes'
2084 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2085 }
2086
2087 /**
2088 * Execute a shell command, with time and memory limits mirrored from the PHP
2089 * configuration if supported.
2090 * @param $cmd Command line, properly escaped for shell.
2091 * @param &$retval optional, will receive the program's exit code.
2092 * (non-zero is usually failure)
2093 * @return collected stdout as a string (trailing newlines stripped)
2094 */
2095 function wfShellExec( $cmd, &$retval=null ) {
2096 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2097
2098 if( wfIniGetBool( 'safe_mode' ) ) {
2099 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2100 $retval = 1;
2101 return "Unable to run external programs in safe mode.";
2102 }
2103
2104 if ( php_uname( 's' ) == 'Linux' ) {
2105 $time = intval( ini_get( 'max_execution_time' ) );
2106 $mem = intval( $wgMaxShellMemory );
2107 $filesize = intval( $wgMaxShellFileSize );
2108
2109 if ( $time > 0 && $mem > 0 ) {
2110 $script = "$IP/bin/ulimit4.sh";
2111 if ( is_executable( $script ) ) {
2112 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2113 }
2114 }
2115 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2116 # This is a hack to work around PHP's flawed invocation of cmd.exe
2117 # http://news.php.net/php.internals/21796
2118 $cmd = '"' . $cmd . '"';
2119 }
2120 wfDebug( "wfShellExec: $cmd\n" );
2121
2122 $retval = 1; // error by default?
2123 ob_start();
2124 passthru( $cmd, $retval );
2125 $output = ob_get_contents();
2126 ob_end_clean();
2127
2128 if ( $retval == 127 ) {
2129 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2130 }
2131 return $output;
2132
2133 }
2134
2135 /**
2136 * This function works like "use VERSION" in Perl, the program will die with a
2137 * backtrace if the current version of PHP is less than the version provided
2138 *
2139 * This is useful for extensions which due to their nature are not kept in sync
2140 * with releases, and might depend on other versions of PHP than the main code
2141 *
2142 * Note: PHP might die due to parsing errors in some cases before it ever
2143 * manages to call this function, such is life
2144 *
2145 * @see perldoc -f use
2146 *
2147 * @param mixed $version The version to check, can be a string, an integer, or
2148 * a float
2149 */
2150 function wfUsePHP( $req_ver ) {
2151 $php_ver = PHP_VERSION;
2152
2153 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2154 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2155 }
2156
2157 /**
2158 * This function works like "use VERSION" in Perl except it checks the version
2159 * of MediaWiki, the program will die with a backtrace if the current version
2160 * of MediaWiki is less than the version provided.
2161 *
2162 * This is useful for extensions which due to their nature are not kept in sync
2163 * with releases
2164 *
2165 * @see perldoc -f use
2166 *
2167 * @param mixed $version The version to check, can be a string, an integer, or
2168 * a float
2169 */
2170 function wfUseMW( $req_ver ) {
2171 global $wgVersion;
2172
2173 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2174 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2175 }
2176
2177 /**
2178 * @deprecated use StringUtils::escapeRegexReplacement
2179 */
2180 function wfRegexReplacement( $string ) {
2181 return StringUtils::escapeRegexReplacement( $string );
2182 }
2183
2184 /**
2185 * Return the final portion of a pathname.
2186 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2187 * http://bugs.php.net/bug.php?id=33898
2188 *
2189 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2190 * We'll consider it so always, as we don't want \s in our Unix paths either.
2191 *
2192 * @param string $path
2193 * @param string $suffix to remove if present
2194 * @return string
2195 */
2196 function wfBaseName( $path, $suffix='' ) {
2197 $encSuffix = ($suffix == '')
2198 ? ''
2199 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2200 $matches = array();
2201 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2202 return $matches[1];
2203 } else {
2204 return '';
2205 }
2206 }
2207
2208 /**
2209 * Generate a relative path name to the given file.
2210 * May explode on non-matching case-insensitive paths,
2211 * funky symlinks, etc.
2212 *
2213 * @param string $path Absolute destination path including target filename
2214 * @param string $from Absolute source path, directory only
2215 * @return string
2216 */
2217 function wfRelativePath( $path, $from ) {
2218 // Normalize mixed input on Windows...
2219 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2220 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2221
2222 // Trim trailing slashes -- fix for drive root
2223 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2224 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2225
2226 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2227 $against = explode( DIRECTORY_SEPARATOR, $from );
2228
2229 if( $pieces[0] !== $against[0] ) {
2230 // Non-matching Windows drive letters?
2231 // Return a full path.
2232 return $path;
2233 }
2234
2235 // Trim off common prefix
2236 while( count( $pieces ) && count( $against )
2237 && $pieces[0] == $against[0] ) {
2238 array_shift( $pieces );
2239 array_shift( $against );
2240 }
2241
2242 // relative dots to bump us to the parent
2243 while( count( $against ) ) {
2244 array_unshift( $pieces, '..' );
2245 array_shift( $against );
2246 }
2247
2248 array_push( $pieces, wfBaseName( $path ) );
2249
2250 return implode( DIRECTORY_SEPARATOR, $pieces );
2251 }
2252
2253 /**
2254 * array_merge() does awful things with "numeric" indexes, including
2255 * string indexes when happen to look like integers. When we want
2256 * to merge arrays with arbitrary string indexes, we don't want our
2257 * arrays to be randomly corrupted just because some of them consist
2258 * of numbers.
2259 *
2260 * Fuck you, PHP. Fuck you in the ear!
2261 *
2262 * @param array $array1, [$array2, [...]]
2263 * @return array
2264 */
2265 function wfArrayMerge( $array1/* ... */ ) {
2266 $out = $array1;
2267 for( $i = 1; $i < func_num_args(); $i++ ) {
2268 foreach( func_get_arg( $i ) as $key => $value ) {
2269 $out[$key] = $value;
2270 }
2271 }
2272 return $out;
2273 }
2274
2275 /**
2276 * Make a URL index, appropriate for the el_index field of externallinks.
2277 */
2278 function wfMakeUrlIndex( $url ) {
2279 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2280 wfSuppressWarnings();
2281 $bits = parse_url( $url );
2282 wfRestoreWarnings();
2283 if ( !$bits ) {
2284 return false;
2285 }
2286 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2287 $delimiter = '';
2288 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2289 $delimiter = '://';
2290 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2291 $delimiter = ':';
2292 // parse_url detects for news: and mailto: the host part of an url as path
2293 // We have to correct this wrong detection
2294 if ( isset ( $bits['path'] ) ) {
2295 $bits['host'] = $bits['path'];
2296 $bits['path'] = '';
2297 }
2298 } else {
2299 return false;
2300 }
2301
2302 // Reverse the labels in the hostname, convert to lower case
2303 // For emails reverse domainpart only
2304 if ( $bits['scheme'] == 'mailto' ) {
2305 $mailparts = explode( '@', $bits['host'], 2 );
2306 if ( count($mailparts) === 2 ) {
2307 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2308 } else {
2309 // No domain specified, don't mangle it
2310 $domainpart = '';
2311 }
2312 $reversedHost = $domainpart . '@' . $mailparts[0];
2313 } else {
2314 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2315 }
2316 // Add an extra dot to the end
2317 // Why? Is it in wrong place in mailto links?
2318 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2319 $reversedHost .= '.';
2320 }
2321 // Reconstruct the pseudo-URL
2322 $prot = $bits['scheme'];
2323 $index = "$prot$delimiter$reversedHost";
2324 // Leave out user and password. Add the port, path, query and fragment
2325 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2326 if ( isset( $bits['path'] ) ) {
2327 $index .= $bits['path'];
2328 } else {
2329 $index .= '/';
2330 }
2331 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2332 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2333 return $index;
2334 }
2335
2336 /**
2337 * Do any deferred updates and clear the list
2338 * TODO: This could be in Wiki.php if that class made any sense at all
2339 */
2340 function wfDoUpdates()
2341 {
2342 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2343 foreach ( $wgDeferredUpdateList as $update ) {
2344 $update->doUpdate();
2345 }
2346 foreach ( $wgPostCommitUpdateList as $update ) {
2347 $update->doUpdate();
2348 }
2349 $wgDeferredUpdateList = array();
2350 $wgPostCommitUpdateList = array();
2351 }
2352
2353 /**
2354 * @deprecated use StringUtils::explodeMarkup
2355 */
2356 function wfExplodeMarkup( $separator, $text ) {
2357 return StringUtils::explodeMarkup( $separator, $text );
2358 }
2359
2360 /**
2361 * Convert an arbitrarily-long digit string from one numeric base
2362 * to another, optionally zero-padding to a minimum column width.
2363 *
2364 * Supports base 2 through 36; digit values 10-36 are represented
2365 * as lowercase letters a-z. Input is case-insensitive.
2366 *
2367 * @param $input string of digits
2368 * @param $sourceBase int 2-36
2369 * @param $destBase int 2-36
2370 * @param $pad int 1 or greater
2371 * @param $lowercase bool
2372 * @return string or false on invalid input
2373 */
2374 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2375 $input = strval( $input );
2376 if( $sourceBase < 2 ||
2377 $sourceBase > 36 ||
2378 $destBase < 2 ||
2379 $destBase > 36 ||
2380 $pad < 1 ||
2381 $sourceBase != intval( $sourceBase ) ||
2382 $destBase != intval( $destBase ) ||
2383 $pad != intval( $pad ) ||
2384 !is_string( $input ) ||
2385 $input == '' ) {
2386 return false;
2387 }
2388 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2389 $inDigits = array();
2390 $outChars = '';
2391
2392 // Decode and validate input string
2393 $input = strtolower( $input );
2394 for( $i = 0; $i < strlen( $input ); $i++ ) {
2395 $n = strpos( $digitChars, $input{$i} );
2396 if( $n === false || $n > $sourceBase ) {
2397 return false;
2398 }
2399 $inDigits[] = $n;
2400 }
2401
2402 // Iterate over the input, modulo-ing out an output digit
2403 // at a time until input is gone.
2404 while( count( $inDigits ) ) {
2405 $work = 0;
2406 $workDigits = array();
2407
2408 // Long division...
2409 foreach( $inDigits as $digit ) {
2410 $work *= $sourceBase;
2411 $work += $digit;
2412
2413 if( $work < $destBase ) {
2414 // Gonna need to pull another digit.
2415 if( count( $workDigits ) ) {
2416 // Avoid zero-padding; this lets us find
2417 // the end of the input very easily when
2418 // length drops to zero.
2419 $workDigits[] = 0;
2420 }
2421 } else {
2422 // Finally! Actual division!
2423 $workDigits[] = intval( $work / $destBase );
2424
2425 // Isn't it annoying that most programming languages
2426 // don't have a single divide-and-remainder operator,
2427 // even though the CPU implements it that way?
2428 $work = $work % $destBase;
2429 }
2430 }
2431
2432 // All that division leaves us with a remainder,
2433 // which is conveniently our next output digit.
2434 $outChars .= $digitChars[$work];
2435
2436 // And we continue!
2437 $inDigits = $workDigits;
2438 }
2439
2440 while( strlen( $outChars ) < $pad ) {
2441 $outChars .= '0';
2442 }
2443
2444 return strrev( $outChars );
2445 }
2446
2447 /**
2448 * Create an object with a given name and an array of construct parameters
2449 * @param string $name
2450 * @param array $p parameters
2451 */
2452 function wfCreateObject( $name, $p ){
2453 $p = array_values( $p );
2454 switch ( count( $p ) ) {
2455 case 0:
2456 return new $name;
2457 case 1:
2458 return new $name( $p[0] );
2459 case 2:
2460 return new $name( $p[0], $p[1] );
2461 case 3:
2462 return new $name( $p[0], $p[1], $p[2] );
2463 case 4:
2464 return new $name( $p[0], $p[1], $p[2], $p[3] );
2465 case 5:
2466 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2467 case 6:
2468 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2469 default:
2470 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2471 }
2472 }
2473
2474 /**
2475 * Alias for modularized function
2476 * @deprecated Use Http::get() instead
2477 */
2478 function wfGetHTTP( $url, $timeout = 'default' ) {
2479 wfDeprecated(__FUNCTION__);
2480 return Http::get( $url, $timeout );
2481 }
2482
2483 /**
2484 * Alias for modularized function
2485 * @deprecated Use Http::isLocalURL() instead
2486 */
2487 function wfIsLocalURL( $url ) {
2488 wfDeprecated(__FUNCTION__);
2489 return Http::isLocalURL( $url );
2490 }
2491
2492 function wfHttpOnlySafe() {
2493 global $wgHttpOnlyBlacklist;
2494 if( !version_compare("5.2", PHP_VERSION, "<") )
2495 return false;
2496
2497 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2498 foreach( $wgHttpOnlyBlacklist as $regex ) {
2499 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2500 return false;
2501 }
2502 }
2503 }
2504
2505 return true;
2506 }
2507
2508 /**
2509 * Initialise php session
2510 */
2511 function wfSetupSession() {
2512 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2513 if( $wgSessionsInMemcached ) {
2514 require_once( 'MemcachedSessions.php' );
2515 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2516 # If it's left on 'user' or another setting from another
2517 # application, it will end up failing. Try to recover.
2518 ini_set ( 'session.save_handler', 'files' );
2519 }
2520 $httpOnlySafe = wfHttpOnlySafe();
2521 wfDebugLog( 'cookie',
2522 'session_set_cookie_params: "' . implode( '", "',
2523 array(
2524 0,
2525 $wgCookiePath,
2526 $wgCookieDomain,
2527 $wgCookieSecure,
2528 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2529 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2530 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2531 } else {
2532 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2533 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2534 }
2535 session_cache_limiter( 'private, must-revalidate' );
2536 wfSuppressWarnings();
2537 session_start();
2538 wfRestoreWarnings();
2539 }
2540
2541 /**
2542 * Get an object from the precompiled serialized directory
2543 *
2544 * @return mixed The variable on success, false on failure
2545 */
2546 function wfGetPrecompiledData( $name ) {
2547 global $IP;
2548
2549 $file = "$IP/serialized/$name";
2550 if ( file_exists( $file ) ) {
2551 $blob = file_get_contents( $file );
2552 if ( $blob ) {
2553 return unserialize( $blob );
2554 }
2555 }
2556 return false;
2557 }
2558
2559 function wfGetCaller( $level = 2 ) {
2560 $backtrace = wfDebugBacktrace();
2561 if ( isset( $backtrace[$level] ) ) {
2562 return wfFormatStackFrame($backtrace[$level]);
2563 } else {
2564 $caller = 'unknown';
2565 }
2566 return $caller;
2567 }
2568
2569 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2570 function wfGetAllCallers() {
2571 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2572 }
2573
2574 /** Return a string representation of frame */
2575 function wfFormatStackFrame($frame) {
2576 return isset( $frame["class"] )?
2577 $frame["class"]."::".$frame["function"]:
2578 $frame["function"];
2579 }
2580
2581 /**
2582 * Get a cache key
2583 */
2584 function wfMemcKey( /*... */ ) {
2585 $args = func_get_args();
2586 $key = wfWikiID() . ':' . implode( ':', $args );
2587 return $key;
2588 }
2589
2590 /**
2591 * Get a cache key for a foreign DB
2592 */
2593 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2594 $args = array_slice( func_get_args(), 2 );
2595 if ( $prefix ) {
2596 $key = "$db-$prefix:" . implode( ':', $args );
2597 } else {
2598 $key = $db . ':' . implode( ':', $args );
2599 }
2600 return $key;
2601 }
2602
2603 /**
2604 * Get an ASCII string identifying this wiki
2605 * This is used as a prefix in memcached keys
2606 */
2607 function wfWikiID( $db = null ) {
2608 if( $db instanceof Database ) {
2609 return $db->getWikiID();
2610 } else {
2611 global $wgDBprefix, $wgDBname;
2612 if ( $wgDBprefix ) {
2613 return "$wgDBname-$wgDBprefix";
2614 } else {
2615 return $wgDBname;
2616 }
2617 }
2618 }
2619
2620 /**
2621 * Split a wiki ID into DB name and table prefix
2622 */
2623 function wfSplitWikiID( $wiki ) {
2624 $bits = explode( '-', $wiki, 2 );
2625 if ( count( $bits ) < 2 ) {
2626 $bits[] = '';
2627 }
2628 return $bits;
2629 }
2630
2631 /*
2632 * Get a Database object.
2633 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2634 * master (for write queries), DB_SLAVE for potentially lagged
2635 * read queries, or an integer >= 0 for a particular server.
2636 *
2637 * @param mixed $groups Query groups. An array of group names that this query
2638 * belongs to. May contain a single string if the query is only
2639 * in one group.
2640 *
2641 * @param string $wiki The wiki ID, or false for the current wiki
2642 *
2643 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2644 * will always return the same object, unless the underlying connection or load
2645 * balancer is manually destroyed.
2646 */
2647 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2648 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2649 }
2650
2651 /**
2652 * Get a load balancer object.
2653 *
2654 * @param array $groups List of query groups
2655 * @param string $wiki Wiki ID, or false for the current wiki
2656 * @return LoadBalancer
2657 */
2658 function wfGetLB( $wiki = false ) {
2659 return wfGetLBFactory()->getMainLB( $wiki );
2660 }
2661
2662 /**
2663 * Get the load balancer factory object
2664 */
2665 function &wfGetLBFactory() {
2666 return LBFactory::singleton();
2667 }
2668
2669 /**
2670 * Find a file.
2671 * Shortcut for RepoGroup::singleton()->findFile()
2672 * @param mixed $title Title object or string. May be interwiki.
2673 * @param mixed $time Requested time for an archived image, or false for the
2674 * current version. An image object will be returned which
2675 * was created at the specified time.
2676 * @param mixed $flags FileRepo::FIND_ flags
2677 * @return File, or false if the file does not exist
2678 */
2679 function wfFindFile( $title, $time = false, $flags = 0 ) {
2680 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2681 }
2682
2683 /**
2684 * Get an object referring to a locally registered file.
2685 * Returns a valid placeholder object if the file does not exist.
2686 */
2687 function wfLocalFile( $title ) {
2688 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2689 }
2690
2691 /**
2692 * Should low-performance queries be disabled?
2693 *
2694 * @return bool
2695 */
2696 function wfQueriesMustScale() {
2697 global $wgMiserMode;
2698 return $wgMiserMode
2699 || ( SiteStats::pages() > 100000
2700 && SiteStats::edits() > 1000000
2701 && SiteStats::users() > 10000 );
2702 }
2703
2704 /**
2705 * Get the path to a specified script file, respecting file
2706 * extensions; this is a wrapper around $wgScriptExtension etc.
2707 *
2708 * @param string $script Script filename, sans extension
2709 * @return string
2710 */
2711 function wfScript( $script = 'index' ) {
2712 global $wgScriptPath, $wgScriptExtension;
2713 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2714 }
2715
2716 /**
2717 * Convenience function converts boolean values into "true"
2718 * or "false" (string) values
2719 *
2720 * @param bool $value
2721 * @return string
2722 */
2723 function wfBoolToStr( $value ) {
2724 return $value ? 'true' : 'false';
2725 }
2726
2727 /**
2728 * Load an extension messages file
2729 *
2730 * @param string $extensionName Name of extension to load messages from\for.
2731 * @param string $langcode Language to load messages for, or false for default
2732 * behvaiour (en, content language and user language).
2733 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2734 * on MediaWiki prior to that
2735 */
2736 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2737 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2738
2739 #For recording whether extension message files have been loaded in a given language.
2740 static $loaded = array();
2741
2742 if( !array_key_exists( $extensionName, $loaded ) ) {
2743 $loaded[$extensionName] = array();
2744 }
2745
2746 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2747 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2748 }
2749
2750 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2751 # Just do en, content language and user language.
2752 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2753 # Mark that they have been loaded.
2754 $loaded[$extensionName]['en'] = true;
2755 $loaded[$extensionName][$wgLang->getCode()] = true;
2756 $loaded[$extensionName][$wgContLang->getCode()] = true;
2757 # Mark that this part has been done to avoid weird if statements.
2758 $loaded[$extensionName]['*'] = true;
2759 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2760 # Load messages for specified language.
2761 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2762 # Mark that they have been loaded.
2763 $loaded[$extensionName][$langcode] = true;
2764 }
2765 }
2766
2767 /**
2768 * Get a platform-independent path to the null file, e.g.
2769 * /dev/null
2770 *
2771 * @return string
2772 */
2773 function wfGetNull() {
2774 return wfIsWindows()
2775 ? 'NUL'
2776 : '/dev/null';
2777 }
2778
2779 /**
2780 * Displays a maxlag error
2781 *
2782 * @param string $host Server that lags the most
2783 * @param int $lag Maxlag (actual)
2784 * @param int $maxLag Maxlag (requested)
2785 */
2786 function wfMaxlagError( $host, $lag, $maxLag ) {
2787 global $wgShowHostnames;
2788 header( 'HTTP/1.1 503 Service Unavailable' );
2789 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2790 header( 'X-Database-Lag: ' . intval( $lag ) );
2791 header( 'Content-Type: text/plain' );
2792 if( $wgShowHostnames ) {
2793 echo "Waiting for $host: $lag seconds lagged\n";
2794 } else {
2795 echo "Waiting for a database server: $lag seconds lagged\n";
2796 }
2797 }
2798
2799 /**
2800 * Throws an E_USER_NOTICE saying that $function is deprecated
2801 * @param string $function
2802 * @return null
2803 */
2804 function wfDeprecated( $function ) {
2805 global $wgDebugLogFile;
2806 if ( !$wgDebugLogFile ) {
2807 return;
2808 }
2809 $callers = wfDebugBacktrace();
2810 if( isset( $callers[2] ) ){
2811 $callerfunc = $callers[2];
2812 $callerfile = $callers[1];
2813 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2814 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2815 } else {
2816 $file = '(internal function)';
2817 }
2818 $func = '';
2819 if( isset( $callerfunc['class'] ) )
2820 $func .= $callerfunc['class'] . '::';
2821 $func .= @$callerfunc['function'];
2822 $msg = "Use of $function is deprecated. Called from $func in $file";
2823 } else {
2824 $msg = "Use of $function is deprecated.";
2825 }
2826 wfDebug( "$msg\n" );
2827 }
2828
2829 /**
2830 * Sleep until the worst slave's replication lag is less than or equal to
2831 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2832 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2833 * a no-op if there are no slaves.
2834 *
2835 * Every time the function has to wait for a slave, it will print a message to
2836 * that effect (and then sleep for a little while), so it's probably not best
2837 * to use this outside maintenance scripts in its present form.
2838 *
2839 * @param int $maxLag
2840 * @return null
2841 */
2842 function wfWaitForSlaves( $maxLag ) {
2843 if( $maxLag ) {
2844 $lb = wfGetLB();
2845 list( $host, $lag ) = $lb->getMaxLag();
2846 while( $lag > $maxLag ) {
2847 $name = @gethostbyaddr( $host );
2848 if( $name !== false ) {
2849 $host = $name;
2850 }
2851 print "Waiting for $host (lagged $lag seconds)...\n";
2852 sleep($maxLag);
2853 list( $host, $lag ) = $lb->getMaxLag();
2854 }
2855 }
2856 }
2857
2858 /** Generate a random 32-character hexadecimal token.
2859 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2860 */
2861 function wfGenerateToken( $salt = '' ) {
2862 $salt = serialize($salt);
2863
2864 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2865 }
2866
2867 /**
2868 * Replace all invalid characters with -
2869 * @param mixed $title Filename to process
2870 */
2871 function wfStripIllegalFilenameChars( $name ) {
2872 $name = wfBaseName( $name );
2873 $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
2874 return $name;
2875 }
2876
2877 /**
2878 * Send some text to
2879 * @param string $line
2880 */
2881 function wfRecentChange2UDP( $line ) {
2882 global $wgRC2UDPAddress, $wgRC2UDPPort, $wgRC2UDPPrefix;
2883 # Notify external application via UDP
2884 if( $wgRC2UDPAddress ) {
2885 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2886 if( $conn ) {
2887 $line = $wgRC2UDPPrefix . $line;
2888 socket_sendto( $conn, $line, strlen($line), 0, $wgRC2UDPAddress, $wgRC2UDPPort );
2889 socket_close( $conn );
2890 }
2891 }
2892 }