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