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