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