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