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