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