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