8f9513b17de467a19567a20967ac14f930a5aa95
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2 /**
3 * Global functions used everywhere
4 * @file
5 */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die( "This file is part of MediaWiki, it is not a valid entry point" );
9 }
10
11 // Hide compatibility functions from Doxygen
12 /// @cond
13
14 /**
15 * Compatibility functions
16 *
17 * We support PHP 5.2.3 and up.
18 * Re-implementations of newer functions or functions in non-standard
19 * PHP extensions may be included here.
20 */
21
22 if( !function_exists( 'iconv' ) ) {
23 /** @codeCoverageIgnore */
24 function iconv( $from, $to, $string ) {
25 return Fallback::iconv( $from, $to, $string );
26 }
27 }
28
29 if ( !function_exists( 'mb_substr' ) ) {
30 /** @codeCoverageIgnore */
31 function mb_substr( $str, $start, $count='end' ) {
32 return Fallback::mb_substr( $str, $start, $count );
33 }
34
35 /** @codeCoverageIgnore */
36 function mb_substr_split_unicode( $str, $splitPos ) {
37 return Fallback::mb_substr_split_unicode( $str, $splitPos );
38 }
39 }
40
41 if ( !function_exists( 'mb_strlen' ) ) {
42 /** @codeCoverageIgnore */
43 function mb_strlen( $str, $enc = '' ) {
44 return Fallback::mb_strlen( $str, $enc );
45 }
46 }
47
48 if( !function_exists( 'mb_strpos' ) ) {
49 /** @codeCoverageIgnore */
50 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
51 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
52 }
53
54 }
55
56 if( !function_exists( 'mb_strrpos' ) ) {
57 /** @codeCoverageIgnore */
58 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
59 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
60 }
61 }
62
63
64 // Support for Wietse Venema's taint feature
65 if ( !function_exists( 'istainted' ) ) {
66 /** @codeCoverageIgnore */
67 function istainted( $var ) {
68 return 0;
69 }
70 /** @codeCoverageIgnore */
71 function taint( $var, $level = 0 ) {}
72 /** @codeCoverageIgnore */
73 function untaint( $var, $level = 0 ) {}
74 define( 'TC_HTML', 1 );
75 define( 'TC_SHELL', 1 );
76 define( 'TC_MYSQL', 1 );
77 define( 'TC_PCRE', 1 );
78 define( 'TC_SELF', 1 );
79 }
80 /// @endcond
81
82 /**
83 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
84 */
85 function wfArrayDiff2( $a, $b ) {
86 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
87 }
88
89 /**
90 * @param $a
91 * @param $b
92 * @return int
93 */
94 function wfArrayDiff2_cmp( $a, $b ) {
95 if ( !is_array( $a ) ) {
96 return strcmp( $a, $b );
97 } elseif ( count( $a ) !== count( $b ) ) {
98 return count( $a ) < count( $b ) ? -1 : 1;
99 } else {
100 reset( $a );
101 reset( $b );
102 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
103 $cmp = strcmp( $valueA, $valueB );
104 if ( $cmp !== 0 ) {
105 return $cmp;
106 }
107 }
108 return 0;
109 }
110 }
111
112 /**
113 * Array lookup
114 * Returns an array where the values in the first array are replaced by the
115 * values in the second array with the corresponding keys
116 *
117 * @param $a Array
118 * @param $b Array
119 * @return array
120 */
121 function wfArrayLookup( $a, $b ) {
122 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
123 }
124
125 /**
126 * Appends to second array if $value differs from that in $default
127 *
128 * @param $key String|Int
129 * @param $value Mixed
130 * @param $default Mixed
131 * @param $changed Array to alter
132 */
133 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
134 if ( is_null( $changed ) ) {
135 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
136 }
137 if ( $default[$key] !== $value ) {
138 $changed[$key] = $value;
139 }
140 }
141
142 /**
143 * Backwards array plus for people who haven't bothered to read the PHP manual
144 * XXX: will not darn your socks for you.
145 *
146 * @param $array1 Array
147 * @param [$array2, [...]] Arrays
148 * @return Array
149 */
150 function wfArrayMerge( $array1/* ... */ ) {
151 $args = func_get_args();
152 $args = array_reverse( $args, true );
153 $out = array();
154 foreach ( $args as $arg ) {
155 $out += $arg;
156 }
157 return $out;
158 }
159
160 /**
161 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
162 * e.g.
163 * wfMergeErrorArrays(
164 * array( array( 'x' ) ),
165 * array( array( 'x', '2' ) ),
166 * array( array( 'x' ) ),
167 * array( array( 'y' ) )
168 * );
169 * returns:
170 * array(
171 * array( 'x', '2' ),
172 * array( 'x' ),
173 * array( 'y' )
174 * )
175 * @param varargs
176 * @return Array
177 */
178 function wfMergeErrorArrays( /*...*/ ) {
179 $args = func_get_args();
180 $out = array();
181 foreach ( $args as $errors ) {
182 foreach ( $errors as $params ) {
183 # @todo FIXME: Sometimes get nested arrays for $params,
184 # which leads to E_NOTICEs
185 $spec = implode( "\t", $params );
186 $out[$spec] = $params;
187 }
188 }
189 return array_values( $out );
190 }
191
192 /**
193 * Insert array into another array after the specified *KEY*
194 *
195 * @param $array Array: The array.
196 * @param $insert Array: The array to insert.
197 * @param $after Mixed: The key to insert after
198 * @return Array
199 */
200 function wfArrayInsertAfter( $array, $insert, $after ) {
201 // Find the offset of the element to insert after.
202 $keys = array_keys( $array );
203 $offsetByKey = array_flip( $keys );
204
205 $offset = $offsetByKey[$after];
206
207 // Insert at the specified offset
208 $before = array_slice( $array, 0, $offset + 1, true );
209 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
210
211 $output = $before + $insert + $after;
212
213 return $output;
214 }
215
216 /**
217 * Recursively converts the parameter (an object) to an array with the same data
218 *
219 * @param $objOrArray Object|Array
220 * @param $recursive Bool
221 * @return Array
222 */
223 function wfObjectToArray( $objOrArray, $recursive = true ) {
224 $array = array();
225 if( is_object( $objOrArray ) ) {
226 $objOrArray = get_object_vars( $objOrArray );
227 }
228 foreach ( $objOrArray as $key => $value ) {
229 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
230 $value = wfObjectToArray( $value );
231 }
232
233 $array[$key] = $value;
234 }
235
236 return $array;
237 }
238
239 /**
240 * Wrapper around array_map() which also taints variables
241 *
242 * @param $function Callback
243 * @param $input Array
244 * @return Array
245 */
246 function wfArrayMap( $function, $input ) {
247 $ret = array_map( $function, $input );
248 foreach ( $ret as $key => $value ) {
249 $taint = istainted( $input[$key] );
250 if ( $taint ) {
251 taint( $ret[$key], $taint );
252 }
253 }
254 return $ret;
255 }
256
257 /**
258 * Get a random decimal value between 0 and 1, in a way
259 * not likely to give duplicate values for any realistic
260 * number of articles.
261 *
262 * @return string
263 */
264 function wfRandom() {
265 # The maximum random value is "only" 2^31-1, so get two random
266 # values to reduce the chance of dupes
267 $max = mt_getrandmax() + 1;
268 $rand = number_format( ( mt_rand() * $max + mt_rand() )
269 / $max / $max, 12, '.', '' );
270 return $rand;
271 }
272
273 /**
274 * We want some things to be included as literal characters in our title URLs
275 * for prettiness, which urlencode encodes by default. According to RFC 1738,
276 * all of the following should be safe:
277 *
278 * ;:@&=$-_.+!*'(),
279 *
280 * But + is not safe because it's used to indicate a space; &= are only safe in
281 * paths and not in queries (and we don't distinguish here); ' seems kind of
282 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
283 * is reserved, we don't care. So the list we unescape is:
284 *
285 * ;:@$!*(),/
286 *
287 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
288 * so no fancy : for IIS7.
289 *
290 * %2F in the page titles seems to fatally break for some reason.
291 *
292 * @param $s String:
293 * @return string
294 */
295 function wfUrlencode( $s ) {
296 static $needle;
297 if ( is_null( $s ) ) {
298 $needle = null;
299 return '';
300 }
301
302 if ( is_null( $needle ) ) {
303 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
304 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
305 $needle[] = '%3A';
306 }
307 }
308
309 $s = urlencode( $s );
310 $s = str_ireplace(
311 $needle,
312 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
313 $s
314 );
315
316 return $s;
317 }
318
319 /**
320 * This function takes two arrays as input, and returns a CGI-style string, e.g.
321 * "days=7&limit=100". Options in the first array override options in the second.
322 * Options set to "" will not be output.
323 *
324 * @param $array1 Array ( String|Array )
325 * @param $array2 Array ( String|Array )
326 * @param $prefix String
327 * @return String
328 */
329 function wfArrayToCGI( $array1, $array2 = null, $prefix = '' ) {
330 if ( !is_null( $array2 ) ) {
331 $array1 = $array1 + $array2;
332 }
333
334 $cgi = '';
335 foreach ( $array1 as $key => $value ) {
336 if ( $value !== '' ) {
337 if ( $cgi != '' ) {
338 $cgi .= '&';
339 }
340 if ( $prefix !== '' ) {
341 $key = $prefix . "[$key]";
342 }
343 if ( is_array( $value ) ) {
344 $firstTime = true;
345 foreach ( $value as $k => $v ) {
346 $cgi .= $firstTime ? '' : '&';
347 if ( is_array( $v ) ) {
348 $cgi .= wfArrayToCGI( $v, null, $key . "[$k]" );
349 } else {
350 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
351 }
352 $firstTime = false;
353 }
354 } else {
355 if ( is_object( $value ) ) {
356 $value = $value->__toString();
357 }
358 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
359 }
360 }
361 }
362 return $cgi;
363 }
364
365 /**
366 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
367 * its argument and returns the same string in array form. This allows compa-
368 * tibility with legacy functions that accept raw query strings instead of nice
369 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
370 * valid query strings, or it will explode.
371 *
372 * @param $query String: query string
373 * @return array Array version of input
374 */
375 function wfCgiToArray( $query ) {
376 if ( isset( $query[0] ) && $query[0] == '?' ) {
377 $query = substr( $query, 1 );
378 }
379 $bits = explode( '&', $query );
380 $ret = array();
381 foreach ( $bits as $bit ) {
382 if ( $bit === '' ) {
383 continue;
384 }
385 list( $key, $value ) = explode( '=', $bit );
386 $key = urldecode( $key );
387 $value = urldecode( $value );
388 if ( strpos( $key, '[' ) !== false ) {
389 $keys = array_reverse( explode( '[', $key ) );
390 $key = array_pop( $keys );
391 $temp = $value;
392 foreach ( $keys as $k ) {
393 $k = substr( $k, 0, -1 );
394 $temp = array( $k => $temp );
395 }
396 if ( isset( $ret[$key] ) ) {
397 $ret[$key] = array_merge( $ret[$key], $temp );
398 } else {
399 $ret[$key] = $temp;
400 }
401 } else {
402 $ret[$key] = $value;
403 }
404 }
405 return $ret;
406 }
407
408 /**
409 * Append a query string to an existing URL, which may or may not already
410 * have query string parameters already. If so, they will be combined.
411 *
412 * @param $url String
413 * @param $query Mixed: string or associative array
414 * @return string
415 */
416 function wfAppendQuery( $url, $query ) {
417 if ( is_array( $query ) ) {
418 $query = wfArrayToCGI( $query );
419 }
420 if( $query != '' ) {
421 if( false === strpos( $url, '?' ) ) {
422 $url .= '?';
423 } else {
424 $url .= '&';
425 }
426 $url .= $query;
427 }
428 return $url;
429 }
430
431 /**
432 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
433 * is correct.
434 *
435 * The meaning of the PROTO_* constants is as follows:
436 * PROTO_HTTP: Output a URL starting with http://
437 * PROTO_HTTPS: Output a URL starting with https://
438 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
439 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending on which protocol was used for the current incoming request
440 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer. For protocol-relative URLs, use the protocol of $wgCanonicalServer
441 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
442 *
443 * @todo this won't work with current-path-relative URLs
444 * like "subdir/foo.html", etc.
445 *
446 * @param $url String: either fully-qualified or a local path + query
447 * @param $defaultProto Mixed: one of the PROTO_* constants. Determines the protocol to use if $url or $wgServer is protocol-relative
448 * @return string Fully-qualified URL
449 */
450 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
451 global $wgServer, $wgCanonicalServer, $wgInternalServer;
452 $serverUrl = $wgServer;
453 if ( $defaultProto === PROTO_CANONICAL ) {
454 $serverUrl = $wgCanonicalServer;
455 }
456 // Make $wgInternalServer fall back to $wgServer if not set
457 if ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
458 $serverUrl = $wgInternalServer;
459 }
460 if ( $defaultProto === PROTO_CURRENT ) {
461 $defaultProto = WebRequest::detectProtocol() . '://';
462 }
463
464 // Analyze $serverUrl to obtain its protocol
465 $bits = wfParseUrl( $serverUrl );
466 $serverHasProto = $bits && $bits['scheme'] != '';
467
468 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
469 if ( $serverHasProto ) {
470 $defaultProto = $bits['scheme'] . '://';
471 } else {
472 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol. This really isn't supposed to happen
473 // Fall back to HTTP in this ridiculous case
474 $defaultProto = PROTO_HTTP;
475 }
476 }
477
478 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
479
480 if( substr( $url, 0, 2 ) == '//' ) {
481 return $defaultProtoWithoutSlashes . $url;
482 } elseif( substr( $url, 0, 1 ) == '/' ) {
483 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes, otherwise leave it alone
484 return ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
485 } else {
486 return $url;
487 }
488 }
489
490 /**
491 * Returns a regular expression of url protocols
492 *
493 * @param $includeProtocolRelative bool If false, remove '//' from the returned protocol list.
494 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
495 * @return String
496 */
497 function wfUrlProtocols( $includeProtocolRelative = true ) {
498 global $wgUrlProtocols;
499
500 // Cache return values separately based on $includeProtocolRelative
501 static $withProtRel = null, $withoutProtRel = null;
502 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
503 if ( !is_null( $cachedValue ) ) {
504 return $cachedValue;
505 }
506
507 // Support old-style $wgUrlProtocols strings, for backwards compatibility
508 // with LocalSettings files from 1.5
509 if ( is_array( $wgUrlProtocols ) ) {
510 $protocols = array();
511 foreach ( $wgUrlProtocols as $protocol ) {
512 // Filter out '//' if !$includeProtocolRelative
513 if ( $includeProtocolRelative || $protocol !== '//' ) {
514 $protocols[] = preg_quote( $protocol, '/' );
515 }
516 }
517
518 $retval = implode( '|', $protocols );
519 } else {
520 // Ignore $includeProtocolRelative in this case
521 // This case exists for pre-1.6 compatibility, and we can safely assume
522 // that '//' won't appear in a pre-1.6 config because protocol-relative
523 // URLs weren't supported until 1.18
524 $retval = $wgUrlProtocols;
525 }
526
527 // Cache return value
528 if ( $includeProtocolRelative ) {
529 $withProtRel = $retval;
530 } else {
531 $withoutProtRel = $retval;
532 }
533 return $retval;
534 }
535
536 /**
537 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
538 * you need a regex that matches all URL protocols but does not match protocol-
539 * relative URLs
540 * @return String
541 */
542 function wfUrlProtocolsWithoutProtRel() {
543 return wfUrlProtocols( false );
544 }
545
546 /**
547 * parse_url() work-alike, but non-broken. Differences:
548 *
549 * 1) Does not raise warnings on bad URLs (just returns false)
550 * 2) Handles protocols that don't use :// (e.g., mailto: and news: , as well as protocol-relative URLs) correctly
551 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2))
552 *
553 * @param $url String: a URL to parse
554 * @return Array: bits of the URL in an associative array, per PHP docs
555 */
556 function wfParseUrl( $url ) {
557 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
558
559 // Protocol-relative URLs are handled really badly by parse_url(). It's so bad that the easiest
560 // way to handle them is to just prepend 'http:' and strip the protocol out later
561 $wasRelative = substr( $url, 0, 2 ) == '//';
562 if ( $wasRelative ) {
563 $url = "http:$url";
564 }
565 wfSuppressWarnings();
566 $bits = parse_url( $url );
567 wfRestoreWarnings();
568 // parse_url() returns an array without scheme for some invalid URLs, e.g.
569 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
570 if ( !$bits || !isset( $bits['scheme'] ) ) {
571 return false;
572 }
573
574 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
575 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
576 $bits['delimiter'] = '://';
577 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
578 $bits['delimiter'] = ':';
579 // parse_url detects for news: and mailto: the host part of an url as path
580 // We have to correct this wrong detection
581 if ( isset( $bits['path'] ) ) {
582 $bits['host'] = $bits['path'];
583 $bits['path'] = '';
584 }
585 } else {
586 return false;
587 }
588
589 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
590 if ( !isset( $bits['host'] ) ) {
591 $bits['host'] = '';
592
593 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
594 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
595 $bits['path'] = '/' . $bits['path'];
596 }
597 }
598
599 // If the URL was protocol-relative, fix scheme and delimiter
600 if ( $wasRelative ) {
601 $bits['scheme'] = '';
602 $bits['delimiter'] = '//';
603 }
604 return $bits;
605 }
606
607 /**
608 * Make a URL index, appropriate for the el_index field of externallinks.
609 *
610 * @param $url String
611 * @return String
612 */
613 function wfMakeUrlIndex( $url ) {
614 $bits = wfParseUrl( $url );
615
616 // Reverse the labels in the hostname, convert to lower case
617 // For emails reverse domainpart only
618 if ( $bits['scheme'] == 'mailto' ) {
619 $mailparts = explode( '@', $bits['host'], 2 );
620 if ( count( $mailparts ) === 2 ) {
621 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
622 } else {
623 // No domain specified, don't mangle it
624 $domainpart = '';
625 }
626 $reversedHost = $domainpart . '@' . $mailparts[0];
627 } else {
628 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
629 }
630 // Add an extra dot to the end
631 // Why? Is it in wrong place in mailto links?
632 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
633 $reversedHost .= '.';
634 }
635 // Reconstruct the pseudo-URL
636 $prot = $bits['scheme'];
637 $index = $prot . $bits['delimiter'] . $reversedHost;
638 // Leave out user and password. Add the port, path, query and fragment
639 if ( isset( $bits['port'] ) ) {
640 $index .= ':' . $bits['port'];
641 }
642 if ( isset( $bits['path'] ) ) {
643 $index .= $bits['path'];
644 } else {
645 $index .= '/';
646 }
647 if ( isset( $bits['query'] ) ) {
648 $index .= '?' . $bits['query'];
649 }
650 if ( isset( $bits['fragment'] ) ) {
651 $index .= '#' . $bits['fragment'];
652 }
653 return $index;
654 }
655
656 /**
657 * Check whether a given URL has a domain that occurs in a given set of domains
658 * @param $url string URL
659 * @param $domains array Array of domains (strings)
660 * @return bool True if the host part of $url ends in one of the strings in $domains
661 */
662 function wfMatchesDomainList( $url, $domains ) {
663 $bits = wfParseUrl( $url );
664 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
665 foreach ( (array)$domains as $domain ) {
666 // FIXME: This gives false positives. http://nds-nl.wikipedia.org will match nl.wikipedia.org
667 // We should use something that interprets dots instead
668 if ( substr( $bits['host'], -strlen( $domain ) ) === $domain ) {
669 return true;
670 }
671 }
672 }
673 return false;
674 }
675
676 /**
677 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
678 * In normal operation this is a NOP.
679 *
680 * Controlling globals:
681 * $wgDebugLogFile - points to the log file
682 * $wgProfileOnly - if set, normal debug messages will not be recorded.
683 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
684 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
685 *
686 * @param $text String
687 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
688 */
689 function wfDebug( $text, $logonly = false ) {
690 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
691 global $wgDebugLogPrefix, $wgShowDebug;
692
693 static $cache = array(); // Cache of unoutputted messages
694 $text = wfDebugTimer() . $text;
695
696 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
697 return;
698 }
699
700 if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
701 $cache[] = $text;
702
703 if ( isset( $wgOut ) && is_object( $wgOut ) ) {
704 // add the message and any cached messages to the output
705 array_map( array( $wgOut, 'debug' ), $cache );
706 $cache = array();
707 }
708 }
709 if ( wfRunHooks( 'Debug', array( $text, null /* no log group */ ) ) ) {
710 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
711 # Strip unprintables; they can switch terminal modes when binary data
712 # gets dumped, which is pretty annoying.
713 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
714 $text = $wgDebugLogPrefix . $text;
715 wfErrorLog( $text, $wgDebugLogFile );
716 }
717 }
718 }
719
720 /**
721 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
722 */
723 function wfIsDebugRawPage() {
724 static $cache;
725 if ( $cache !== null ) {
726 return $cache;
727 }
728 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
729 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
730 || (
731 isset( $_SERVER['SCRIPT_NAME'] )
732 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
733 ) )
734 {
735 $cache = true;
736 } else {
737 $cache = false;
738 }
739 return $cache;
740 }
741
742 /**
743 * Get microsecond timestamps for debug logs
744 *
745 * @return string
746 */
747 function wfDebugTimer() {
748 global $wgDebugTimestamps;
749 if ( !$wgDebugTimestamps ) {
750 return '';
751 }
752 static $start = null;
753
754 if ( $start === null ) {
755 $start = microtime( true );
756 $prefix = "\n$start";
757 } else {
758 $prefix = sprintf( "%6.4f", microtime( true ) - $start );
759 }
760 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / (1024*1024) ) );
761 return "$prefix $mem " ;
762 }
763
764 /**
765 * Send a line giving PHP memory usage.
766 *
767 * @param $exact Bool: print exact values instead of kilobytes (default: false)
768 */
769 function wfDebugMem( $exact = false ) {
770 $mem = memory_get_usage();
771 if( !$exact ) {
772 $mem = floor( $mem / 1024 ) . ' kilobytes';
773 } else {
774 $mem .= ' bytes';
775 }
776 wfDebug( "Memory usage: $mem\n" );
777 }
778
779 /**
780 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
781 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
782 *
783 * @param $logGroup String
784 * @param $text String
785 * @param $public Bool: whether to log the event in the public log if no private
786 * log file is specified, (default true)
787 */
788 function wfDebugLog( $logGroup, $text, $public = true ) {
789 global $wgDebugLogGroups, $wgShowHostnames;
790 $text = trim( $text ) . "\n";
791 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
792 $time = wfTimestamp( TS_DB );
793 $wiki = wfWikiID();
794 if ( $wgShowHostnames ) {
795 $host = wfHostname();
796 } else {
797 $host = '';
798 }
799 if ( wfRunHooks( 'Debug', array( $text, $logGroup ) ) ) {
800 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
801 }
802 } elseif ( $public === true ) {
803 wfDebug( $text, true );
804 }
805 }
806
807 /**
808 * Log for database errors
809 *
810 * @param $text String: database error message.
811 */
812 function wfLogDBError( $text ) {
813 global $wgDBerrorLog, $wgDBname;
814 if ( $wgDBerrorLog ) {
815 $host = trim(`hostname`);
816 $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
817 wfErrorLog( $text, $wgDBerrorLog );
818 }
819 }
820
821 /**
822 * Log to a file without getting "file size exceeded" signals.
823 *
824 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
825 * send lines to the specified port, prefixed by the specified prefix and a space.
826 *
827 * @param $text String
828 * @param $file String filename
829 */
830 function wfErrorLog( $text, $file ) {
831 if ( substr( $file, 0, 4 ) == 'udp:' ) {
832 # Needs the sockets extension
833 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
834 // IPv6 bracketed host
835 $host = $m[2];
836 $port = intval( $m[3] );
837 $prefix = isset( $m[4] ) ? $m[4] : false;
838 $domain = AF_INET6;
839 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
840 $host = $m[2];
841 if ( !IP::isIPv4( $host ) ) {
842 $host = gethostbyname( $host );
843 }
844 $port = intval( $m[3] );
845 $prefix = isset( $m[4] ) ? $m[4] : false;
846 $domain = AF_INET;
847 } else {
848 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
849 }
850
851 // Clean it up for the multiplexer
852 if ( strval( $prefix ) !== '' ) {
853 $text = preg_replace( '/^/m', $prefix . ' ', $text );
854
855 // Limit to 64KB
856 if ( strlen( $text ) > 65506 ) {
857 $text = substr( $text, 0, 65506 );
858 }
859
860 if ( substr( $text, -1 ) != "\n" ) {
861 $text .= "\n";
862 }
863 } elseif ( strlen( $text ) > 65507 ) {
864 $text = substr( $text, 0, 65507 );
865 }
866
867 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
868 if ( !$sock ) {
869 return;
870 }
871
872 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
873 socket_close( $sock );
874 } else {
875 wfSuppressWarnings();
876 $exists = file_exists( $file );
877 $size = $exists ? filesize( $file ) : false;
878 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
879 file_put_contents( $file, $text, FILE_APPEND );
880 }
881 wfRestoreWarnings();
882 }
883 }
884
885 /**
886 * @todo document
887 */
888 function wfLogProfilingData() {
889 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
890 global $wgProfileLimit, $wgUser;
891
892 $profiler = Profiler::instance();
893
894 # Profiling must actually be enabled...
895 if ( $profiler->isStub() ) {
896 return;
897 }
898
899 // Get total page request time and only show pages that longer than
900 // $wgProfileLimit time (default is 0)
901 $now = wfTime();
902 $elapsed = $now - $wgRequestTime;
903 if ( $elapsed <= $wgProfileLimit ) {
904 return;
905 }
906
907 $profiler->logData();
908
909 // Check whether this should be logged in the debug file.
910 if ( $wgDebugLogFile == '' || ( !$wgDebugRawPage && wfIsDebugRawPage() ) ) {
911 return;
912 }
913
914 $forward = '';
915 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
916 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
917 }
918 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
919 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
920 }
921 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
922 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
923 }
924 if ( $forward ) {
925 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
926 }
927 // Don't load $wgUser at this late stage just for statistics purposes
928 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
929 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
930 $forward .= ' anon';
931 }
932 $log = sprintf( "%s\t%04.3f\t%s\n",
933 gmdate( 'YmdHis' ), $elapsed,
934 urldecode( $wgRequest->getRequestURL() . $forward ) );
935
936 wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
937 }
938
939 /**
940 * Check if the wiki read-only lock file is present. This can be used to lock
941 * off editing functions, but doesn't guarantee that the database will not be
942 * modified.
943 *
944 * @return bool
945 */
946 function wfReadOnly() {
947 global $wgReadOnlyFile, $wgReadOnly;
948
949 if ( !is_null( $wgReadOnly ) ) {
950 return (bool)$wgReadOnly;
951 }
952 if ( $wgReadOnlyFile == '' ) {
953 return false;
954 }
955 // Set $wgReadOnly for faster access next time
956 if ( is_file( $wgReadOnlyFile ) ) {
957 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
958 } else {
959 $wgReadOnly = false;
960 }
961 return (bool)$wgReadOnly;
962 }
963
964 /**
965 * @return bool
966 */
967 function wfReadOnlyReason() {
968 global $wgReadOnly;
969 wfReadOnly();
970 return $wgReadOnly;
971 }
972
973 /**
974 * Return a Language object from $langcode
975 *
976 * @param $langcode Mixed: either:
977 * - a Language object
978 * - code of the language to get the message for, if it is
979 * a valid code create a language for that language, if
980 * it is a string but not a valid code then make a basic
981 * language object
982 * - a boolean: if it's false then use the global object for
983 * the current user's language (as a fallback for the old parameter
984 * functionality), or if it is true then use global object
985 * for the wiki's content language.
986 * @return Language object
987 */
988 function wfGetLangObj( $langcode = false ) {
989 # Identify which language to get or create a language object for.
990 # Using is_object here due to Stub objects.
991 if( is_object( $langcode ) ) {
992 # Great, we already have the object (hopefully)!
993 return $langcode;
994 }
995
996 global $wgContLang, $wgLanguageCode;
997 if( $langcode === true || $langcode === $wgLanguageCode ) {
998 # $langcode is the language code of the wikis content language object.
999 # or it is a boolean and value is true
1000 return $wgContLang;
1001 }
1002
1003 global $wgLang;
1004 if( $langcode === false || $langcode === $wgLang->getCode() ) {
1005 # $langcode is the language code of user language object.
1006 # or it was a boolean and value is false
1007 return $wgLang;
1008 }
1009
1010 $validCodes = array_keys( Language::getLanguageNames() );
1011 if( in_array( $langcode, $validCodes ) ) {
1012 # $langcode corresponds to a valid language.
1013 return Language::factory( $langcode );
1014 }
1015
1016 # $langcode is a string, but not a valid language code; use content language.
1017 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1018 return $wgContLang;
1019 }
1020
1021 /**
1022 * Old function when $wgBetterDirectionality existed
1023 * Removed in core, kept in extensions for backwards compat.
1024 *
1025 * @deprecated since 1.18
1026 * @return Language
1027 */
1028 function wfUILang() {
1029 global $wgLang;
1030 return $wgLang;
1031 }
1032
1033 /**
1034 * This is the new function for getting translated interface messages.
1035 * See the Message class for documentation how to use them.
1036 * The intention is that this function replaces all old wfMsg* functions.
1037 * @param $key \string Message key.
1038 * Varargs: normal message parameters.
1039 * @return Message
1040 * @since 1.17
1041 */
1042 function wfMessage( $key /*...*/) {
1043 $params = func_get_args();
1044 array_shift( $params );
1045 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1046 $params = $params[0];
1047 }
1048 return new Message( $key, $params );
1049 }
1050
1051 /**
1052 * This function accepts multiple message keys and returns a message instance
1053 * for the first message which is non-empty. If all messages are empty then an
1054 * instance of the first message key is returned.
1055 * @param varargs: message keys
1056 * @return Message
1057 * @since 1.18
1058 */
1059 function wfMessageFallback( /*...*/ ) {
1060 $args = func_get_args();
1061 return MWFunction::callArray( 'Message::newFallbackSequence', $args );
1062 }
1063
1064 /**
1065 * Get a message from anywhere, for the current user language.
1066 *
1067 * Use wfMsgForContent() instead if the message should NOT
1068 * change depending on the user preferences.
1069 *
1070 * @param $key String: lookup key for the message, usually
1071 * defined in languages/Language.php
1072 *
1073 * Parameters to the message, which can be used to insert variable text into
1074 * it, can be passed to this function in the following formats:
1075 * - One per argument, starting at the second parameter
1076 * - As an array in the second parameter
1077 * These are not shown in the function definition.
1078 *
1079 * @return String
1080 */
1081 function wfMsg( $key ) {
1082 $args = func_get_args();
1083 array_shift( $args );
1084 return wfMsgReal( $key, $args );
1085 }
1086
1087 /**
1088 * Same as above except doesn't transform the message
1089 *
1090 * @param $key String
1091 * @return String
1092 */
1093 function wfMsgNoTrans( $key ) {
1094 $args = func_get_args();
1095 array_shift( $args );
1096 return wfMsgReal( $key, $args, true, false, false );
1097 }
1098
1099 /**
1100 * Get a message from anywhere, for the current global language
1101 * set with $wgLanguageCode.
1102 *
1103 * Use this if the message should NOT change dependent on the
1104 * language set in the user's preferences. This is the case for
1105 * most text written into logs, as well as link targets (such as
1106 * the name of the copyright policy page). Link titles, on the
1107 * other hand, should be shown in the UI language.
1108 *
1109 * Note that MediaWiki allows users to change the user interface
1110 * language in their preferences, but a single installation
1111 * typically only contains content in one language.
1112 *
1113 * Be wary of this distinction: If you use wfMsg() where you should
1114 * use wfMsgForContent(), a user of the software may have to
1115 * customize potentially hundreds of messages in
1116 * order to, e.g., fix a link in every possible language.
1117 *
1118 * @param $key String: lookup key for the message, usually
1119 * defined in languages/Language.php
1120 * @return String
1121 */
1122 function wfMsgForContent( $key ) {
1123 global $wgForceUIMsgAsContentMsg;
1124 $args = func_get_args();
1125 array_shift( $args );
1126 $forcontent = true;
1127 if( is_array( $wgForceUIMsgAsContentMsg ) &&
1128 in_array( $key, $wgForceUIMsgAsContentMsg ) )
1129 {
1130 $forcontent = false;
1131 }
1132 return wfMsgReal( $key, $args, true, $forcontent );
1133 }
1134
1135 /**
1136 * Same as above except doesn't transform the message
1137 *
1138 * @param $key String
1139 * @return String
1140 */
1141 function wfMsgForContentNoTrans( $key ) {
1142 global $wgForceUIMsgAsContentMsg;
1143 $args = func_get_args();
1144 array_shift( $args );
1145 $forcontent = true;
1146 if( is_array( $wgForceUIMsgAsContentMsg ) &&
1147 in_array( $key, $wgForceUIMsgAsContentMsg ) )
1148 {
1149 $forcontent = false;
1150 }
1151 return wfMsgReal( $key, $args, true, $forcontent, false );
1152 }
1153
1154 /**
1155 * Really get a message
1156 *
1157 * @param $key String: key to get.
1158 * @param $args
1159 * @param $useDB Boolean
1160 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
1161 * @param $transform Boolean: Whether or not to transform the message.
1162 * @return String: the requested message.
1163 */
1164 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1165 wfProfileIn( __METHOD__ );
1166 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1167 $message = wfMsgReplaceArgs( $message, $args );
1168 wfProfileOut( __METHOD__ );
1169 return $message;
1170 }
1171
1172 /**
1173 * Fetch a message string value, but don't replace any keys yet.
1174 *
1175 * @param $key String
1176 * @param $useDB Bool
1177 * @param $langCode String: Code of the language to get the message for, or
1178 * behaves as a content language switch if it is a boolean.
1179 * @param $transform Boolean: whether to parse magic words, etc.
1180 * @return string
1181 */
1182 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1183 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1184
1185 $cache = MessageCache::singleton();
1186 $message = $cache->get( $key, $useDB, $langCode );
1187 if( $message === false ) {
1188 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
1189 } elseif ( $transform ) {
1190 $message = $cache->transform( $message );
1191 }
1192 return $message;
1193 }
1194
1195 /**
1196 * Replace message parameter keys on the given formatted output.
1197 *
1198 * @param $message String
1199 * @param $args Array
1200 * @return string
1201 * @private
1202 */
1203 function wfMsgReplaceArgs( $message, $args ) {
1204 # Fix windows line-endings
1205 # Some messages are split with explode("\n", $msg)
1206 $message = str_replace( "\r", '', $message );
1207
1208 // Replace arguments
1209 if ( count( $args ) ) {
1210 if ( is_array( $args[0] ) ) {
1211 $args = array_values( $args[0] );
1212 }
1213 $replacementKeys = array();
1214 foreach( $args as $n => $param ) {
1215 $replacementKeys['$' . ( $n + 1 )] = $param;
1216 }
1217 $message = strtr( $message, $replacementKeys );
1218 }
1219
1220 return $message;
1221 }
1222
1223 /**
1224 * Return an HTML-escaped version of a message.
1225 * Parameter replacements, if any, are done *after* the HTML-escaping,
1226 * so parameters may contain HTML (eg links or form controls). Be sure
1227 * to pre-escape them if you really do want plaintext, or just wrap
1228 * the whole thing in htmlspecialchars().
1229 *
1230 * @param $key String
1231 * @param string ... parameters
1232 * @return string
1233 */
1234 function wfMsgHtml( $key ) {
1235 $args = func_get_args();
1236 array_shift( $args );
1237 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1238 }
1239
1240 /**
1241 * Return an HTML version of message
1242 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1243 * so parameters may contain HTML (eg links or form controls). Be sure
1244 * to pre-escape them if you really do want plaintext, or just wrap
1245 * the whole thing in htmlspecialchars().
1246 *
1247 * @param $key String
1248 * @param string ... parameters
1249 * @return string
1250 */
1251 function wfMsgWikiHtml( $key ) {
1252 $args = func_get_args();
1253 array_shift( $args );
1254 return wfMsgReplaceArgs(
1255 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
1256 /* can't be set to false */ true, /* interface */ true )->getText(),
1257 $args );
1258 }
1259
1260 /**
1261 * Returns message in the requested format
1262 * @param $key String: key of the message
1263 * @param $options Array: processing rules. Can take the following options:
1264 * <i>parse</i>: parses wikitext to HTML
1265 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
1266 * p's added by parser or tidy
1267 * <i>escape</i>: filters message through htmlspecialchars
1268 * <i>escapenoentities</i>: same, but allows entity references like &#160; through
1269 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
1270 * <i>parsemag</i>: transform the message using magic phrases
1271 * <i>content</i>: fetch message for content language instead of interface
1272 * Also can accept a single associative argument, of the form 'language' => 'xx':
1273 * <i>language</i>: Language object or language code to fetch message for
1274 * (overriden by <i>content</i>).
1275 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1276 *
1277 * @return String
1278 */
1279 function wfMsgExt( $key, $options ) {
1280 $args = func_get_args();
1281 array_shift( $args );
1282 array_shift( $args );
1283 $options = (array)$options;
1284
1285 foreach( $options as $arrayKey => $option ) {
1286 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1287 # An unknown index, neither numeric nor "language"
1288 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
1289 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1290 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1291 'replaceafter', 'parsemag', 'content' ) ) ) {
1292 # A numeric index with unknown value
1293 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
1294 }
1295 }
1296
1297 if( in_array( 'content', $options, true ) ) {
1298 $forContent = true;
1299 $langCode = true;
1300 $langCodeObj = null;
1301 } elseif( array_key_exists( 'language', $options ) ) {
1302 $forContent = false;
1303 $langCode = wfGetLangObj( $options['language'] );
1304 $langCodeObj = $langCode;
1305 } else {
1306 $forContent = false;
1307 $langCode = false;
1308 $langCodeObj = null;
1309 }
1310
1311 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1312
1313 if( !in_array( 'replaceafter', $options, true ) ) {
1314 $string = wfMsgReplaceArgs( $string, $args );
1315 }
1316
1317 $messageCache = MessageCache::singleton();
1318 if( in_array( 'parse', $options, true ) ) {
1319 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
1320 } elseif ( in_array( 'parseinline', $options, true ) ) {
1321 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj )->getText();
1322 $m = array();
1323 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
1324 $string = $m[1];
1325 }
1326 } elseif ( in_array( 'parsemag', $options, true ) ) {
1327 $string = $messageCache->transform( $string,
1328 !$forContent, $langCodeObj );
1329 }
1330
1331 if ( in_array( 'escape', $options, true ) ) {
1332 $string = htmlspecialchars ( $string );
1333 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1334 $string = Sanitizer::escapeHtmlAllowEntities( $string );
1335 }
1336
1337 if( in_array( 'replaceafter', $options, true ) ) {
1338 $string = wfMsgReplaceArgs( $string, $args );
1339 }
1340
1341 return $string;
1342 }
1343
1344 /**
1345 * Since wfMsg() and co suck, they don't return false if the message key they
1346 * looked up didn't exist but a XHTML string, this function checks for the
1347 * nonexistance of messages by checking the MessageCache::get() result directly.
1348 *
1349 * @param $key String: the message key looked up
1350 * @return Boolean True if the message *doesn't* exist.
1351 */
1352 function wfEmptyMsg( $key ) {
1353 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1354 }
1355
1356 /**
1357 * Throw a debugging exception. This function previously once exited the process,
1358 * but now throws an exception instead, with similar results.
1359 *
1360 * @param $msg String: message shown when dying.
1361 */
1362 function wfDebugDieBacktrace( $msg = '' ) {
1363 throw new MWException( $msg );
1364 }
1365
1366 /**
1367 * Fetch server name for use in error reporting etc.
1368 * Use real server name if available, so we know which machine
1369 * in a server farm generated the current page.
1370 *
1371 * @return string
1372 */
1373 function wfHostname() {
1374 static $host;
1375 if ( is_null( $host ) ) {
1376 if ( function_exists( 'posix_uname' ) ) {
1377 // This function not present on Windows
1378 $uname = posix_uname();
1379 } else {
1380 $uname = false;
1381 }
1382 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1383 $host = $uname['nodename'];
1384 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1385 # Windows computer name
1386 $host = getenv( 'COMPUTERNAME' );
1387 } else {
1388 # This may be a virtual server.
1389 $host = $_SERVER['SERVER_NAME'];
1390 }
1391 }
1392 return $host;
1393 }
1394
1395 /**
1396 * Returns a HTML comment with the elapsed time since request.
1397 * This method has no side effects.
1398 *
1399 * @return string
1400 */
1401 function wfReportTime() {
1402 global $wgRequestTime, $wgShowHostnames;
1403
1404 $now = wfTime();
1405 $elapsed = $now - $wgRequestTime;
1406
1407 return $wgShowHostnames
1408 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1409 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1410 }
1411
1412 /**
1413 * Safety wrapper for debug_backtrace().
1414 *
1415 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1416 * murky circumstances, which may be triggered in part by stub objects
1417 * or other fancy talkin'.
1418 *
1419 * Will return an empty array if Zend Optimizer is detected or if
1420 * debug_backtrace is disabled, otherwise the output from
1421 * debug_backtrace() (trimmed).
1422 *
1423 * @param $limit int This parameter can be used to limit the number of stack frames returned
1424 *
1425 * @return array of backtrace information
1426 */
1427 function wfDebugBacktrace( $limit = 0 ) {
1428 static $disabled = null;
1429
1430 if( extension_loaded( 'Zend Optimizer' ) ) {
1431 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1432 return array();
1433 }
1434
1435 if ( is_null( $disabled ) ) {
1436 $disabled = false;
1437 $functions = explode( ',', ini_get( 'disable_functions' ) );
1438 $functions = array_map( 'trim', $functions );
1439 $functions = array_map( 'strtolower', $functions );
1440 if ( in_array( 'debug_backtrace', $functions ) ) {
1441 wfDebug( "debug_backtrace is in disabled_functions\n" );
1442 $disabled = true;
1443 }
1444 }
1445 if ( $disabled ) {
1446 return array();
1447 }
1448
1449 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
1450 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit ), 1 );
1451 } else {
1452 return array_slice( debug_backtrace(), 1 );
1453 }
1454 }
1455
1456 /**
1457 * Get a debug backtrace as a string
1458 *
1459 * @return string
1460 */
1461 function wfBacktrace() {
1462 global $wgCommandLineMode;
1463
1464 if ( $wgCommandLineMode ) {
1465 $msg = '';
1466 } else {
1467 $msg = "<ul>\n";
1468 }
1469 $backtrace = wfDebugBacktrace();
1470 foreach( $backtrace as $call ) {
1471 if( isset( $call['file'] ) ) {
1472 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
1473 $file = $f[count( $f ) - 1];
1474 } else {
1475 $file = '-';
1476 }
1477 if( isset( $call['line'] ) ) {
1478 $line = $call['line'];
1479 } else {
1480 $line = '-';
1481 }
1482 if ( $wgCommandLineMode ) {
1483 $msg .= "$file line $line calls ";
1484 } else {
1485 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1486 }
1487 if( !empty( $call['class'] ) ) {
1488 $msg .= $call['class'] . $call['type'];
1489 }
1490 $msg .= $call['function'] . '()';
1491
1492 if ( $wgCommandLineMode ) {
1493 $msg .= "\n";
1494 } else {
1495 $msg .= "</li>\n";
1496 }
1497 }
1498 if ( $wgCommandLineMode ) {
1499 $msg .= "\n";
1500 } else {
1501 $msg .= "</ul>\n";
1502 }
1503
1504 return $msg;
1505 }
1506
1507 /**
1508 * Get the name of the function which called this function
1509 *
1510 * @param $level Int
1511 * @return Bool|string
1512 */
1513 function wfGetCaller( $level = 2 ) {
1514 $backtrace = wfDebugBacktrace( $level );
1515 if ( isset( $backtrace[$level] ) ) {
1516 return wfFormatStackFrame( $backtrace[$level] );
1517 } else {
1518 $caller = 'unknown';
1519 }
1520 return $caller;
1521 }
1522
1523 /**
1524 * Return a string consisting of callers in the stack. Useful sometimes
1525 * for profiling specific points.
1526 *
1527 * @param $limit The maximum depth of the stack frame to return, or false for
1528 * the entire stack.
1529 * @return String
1530 */
1531 function wfGetAllCallers( $limit = 3 ) {
1532 $trace = array_reverse( wfDebugBacktrace() );
1533 if ( !$limit || $limit > count( $trace ) - 1 ) {
1534 $limit = count( $trace ) - 1;
1535 }
1536 $trace = array_slice( $trace, -$limit - 1, $limit );
1537 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1538 }
1539
1540 /**
1541 * Return a string representation of frame
1542 *
1543 * @param $frame Array
1544 * @return Bool
1545 */
1546 function wfFormatStackFrame( $frame ) {
1547 return isset( $frame['class'] ) ?
1548 $frame['class'] . '::' . $frame['function'] :
1549 $frame['function'];
1550 }
1551
1552
1553 /* Some generic result counters, pulled out of SearchEngine */
1554
1555
1556 /**
1557 * @todo document
1558 *
1559 * @param $offset Int
1560 * @param $limit Int
1561 * @return String
1562 */
1563 function wfShowingResults( $offset, $limit ) {
1564 global $wgLang;
1565 return wfMsgExt(
1566 'showingresults',
1567 array( 'parseinline' ),
1568 $wgLang->formatNum( $limit ),
1569 $wgLang->formatNum( $offset + 1 )
1570 );
1571 }
1572
1573 /**
1574 * Generate (prev x| next x) (20|50|100...) type links for paging
1575 *
1576 * @param $offset String
1577 * @param $limit Integer
1578 * @param $link String
1579 * @param $query String: optional URL query parameter string
1580 * @param $atend Bool: optional param for specified if this is the last page
1581 * @return String
1582 * @deprecated in 1.19; use Language::viewPrevNext() instead
1583 */
1584 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1585 global $wgLang;
1586
1587 $query = wfCgiToArray( $query );
1588
1589 if( is_object( $link ) ) {
1590 $title = $link;
1591 } else {
1592 $title = Title::newFromText( $link );
1593 if( is_null( $title ) ) {
1594 return false;
1595 }
1596 }
1597
1598 return $wgLang->viewPrevNext( $title, $offset, $limit, $query, $atend );
1599 }
1600
1601 /**
1602 * Make a list item, used by various special pages
1603 *
1604 * @param $page String Page link
1605 * @param $details String Text between brackets
1606 * @param $oppositedm Boolean Add the direction mark opposite to your
1607 * language, to display text properly
1608 * @return String
1609 * @deprecated since 1.19; use Language::specialList() instead
1610 */
1611 function wfSpecialList( $page, $details, $oppositedm = true ) {
1612 global $wgLang;
1613 return $wgLang->specialList( $page, $details, $oppositedm );
1614 }
1615
1616 /**
1617 * @todo document
1618 * @todo FIXME: We may want to blacklist some broken browsers
1619 *
1620 * @param $force Bool
1621 * @return bool Whereas client accept gzip compression
1622 */
1623 function wfClientAcceptsGzip( $force = false ) {
1624 static $result = null;
1625 if ( $result === null || $force ) {
1626 $result = false;
1627 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1628 # @todo FIXME: We may want to blacklist some broken browsers
1629 $m = array();
1630 if( preg_match(
1631 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1632 $_SERVER['HTTP_ACCEPT_ENCODING'],
1633 $m )
1634 )
1635 {
1636 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1637 $result = false;
1638 return $result;
1639 }
1640 wfDebug( " accepts gzip\n" );
1641 $result = true;
1642 }
1643 }
1644 }
1645 return $result;
1646 }
1647
1648 /**
1649 * Obtain the offset and limit values from the request string;
1650 * used in special pages
1651 *
1652 * @param $deflimit Int default limit if none supplied
1653 * @param $optionname String Name of a user preference to check against
1654 * @return array
1655 *
1656 */
1657 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1658 global $wgRequest;
1659 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1660 }
1661
1662 /**
1663 * Escapes the given text so that it may be output using addWikiText()
1664 * without any linking, formatting, etc. making its way through. This
1665 * is achieved by substituting certain characters with HTML entities.
1666 * As required by the callers, <nowiki> is not used.
1667 *
1668 * @param $text String: text to be escaped
1669 * @return String
1670 */
1671 function wfEscapeWikiText( $text ) {
1672 $text = strtr( "\n$text", array(
1673 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
1674 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
1675 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
1676 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
1677 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
1678 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
1679 ) );
1680 return substr( $text, 1 );
1681 }
1682
1683 /**
1684 * Get the current unix timetstamp with microseconds. Useful for profiling
1685 * @return Float
1686 */
1687 function wfTime() {
1688 return microtime( true );
1689 }
1690
1691 /**
1692 * Sets dest to source and returns the original value of dest
1693 * If source is NULL, it just returns the value, it doesn't set the variable
1694 * If force is true, it will set the value even if source is NULL
1695 *
1696 * @param $dest Mixed
1697 * @param $source Mixed
1698 * @param $force Bool
1699 * @return Mixed
1700 */
1701 function wfSetVar( &$dest, $source, $force = false ) {
1702 $temp = $dest;
1703 if ( !is_null( $source ) || $force ) {
1704 $dest = $source;
1705 }
1706 return $temp;
1707 }
1708
1709 /**
1710 * As for wfSetVar except setting a bit
1711 *
1712 * @param $dest Int
1713 * @param $bit Int
1714 * @param $state Bool
1715 */
1716 function wfSetBit( &$dest, $bit, $state = true ) {
1717 $temp = (bool)( $dest & $bit );
1718 if ( !is_null( $state ) ) {
1719 if ( $state ) {
1720 $dest |= $bit;
1721 } else {
1722 $dest &= ~$bit;
1723 }
1724 }
1725 return $temp;
1726 }
1727
1728 /**
1729 * A wrapper around the PHP function var_export().
1730 * Either print it or add it to the regular output ($wgOut).
1731 *
1732 * @param $var A PHP variable to dump.
1733 */
1734 function wfVarDump( $var ) {
1735 global $wgOut;
1736 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1737 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
1738 print $s;
1739 } else {
1740 $wgOut->addHTML( $s );
1741 }
1742 }
1743
1744 /**
1745 * Provide a simple HTTP error.
1746 *
1747 * @param $code Int|String
1748 * @param $label String
1749 * @param $desc String
1750 */
1751 function wfHttpError( $code, $label, $desc ) {
1752 global $wgOut;
1753 $wgOut->disable();
1754 header( "HTTP/1.0 $code $label" );
1755 header( "Status: $code $label" );
1756 $wgOut->sendCacheControl();
1757
1758 header( 'Content-type: text/html; charset=utf-8' );
1759 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1760 '<html><head><title>' .
1761 htmlspecialchars( $label ) .
1762 '</title></head><body><h1>' .
1763 htmlspecialchars( $label ) .
1764 '</h1><p>' .
1765 nl2br( htmlspecialchars( $desc ) ) .
1766 "</p></body></html>\n";
1767 }
1768
1769 /**
1770 * Clear away any user-level output buffers, discarding contents.
1771 *
1772 * Suitable for 'starting afresh', for instance when streaming
1773 * relatively large amounts of data without buffering, or wanting to
1774 * output image files without ob_gzhandler's compression.
1775 *
1776 * The optional $resetGzipEncoding parameter controls suppression of
1777 * the Content-Encoding header sent by ob_gzhandler; by default it
1778 * is left. See comments for wfClearOutputBuffers() for why it would
1779 * be used.
1780 *
1781 * Note that some PHP configuration options may add output buffer
1782 * layers which cannot be removed; these are left in place.
1783 *
1784 * @param $resetGzipEncoding Bool
1785 */
1786 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1787 if( $resetGzipEncoding ) {
1788 // Suppress Content-Encoding and Content-Length
1789 // headers from 1.10+s wfOutputHandler
1790 global $wgDisableOutputCompression;
1791 $wgDisableOutputCompression = true;
1792 }
1793 while( $status = ob_get_status() ) {
1794 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1795 // Probably from zlib.output_compression or other
1796 // PHP-internal setting which can't be removed.
1797 //
1798 // Give up, and hope the result doesn't break
1799 // output behavior.
1800 break;
1801 }
1802 if( !ob_end_clean() ) {
1803 // Could not remove output buffer handler; abort now
1804 // to avoid getting in some kind of infinite loop.
1805 break;
1806 }
1807 if( $resetGzipEncoding ) {
1808 if( $status['name'] == 'ob_gzhandler' ) {
1809 // Reset the 'Content-Encoding' field set by this handler
1810 // so we can start fresh.
1811 if ( function_exists( 'header_remove' ) ) {
1812 // Available since PHP 5.3.0
1813 header_remove( 'Content-Encoding' );
1814 } else {
1815 // We need to provide a valid content-coding. See bug 28069
1816 header( 'Content-Encoding: identity' );
1817 }
1818 break;
1819 }
1820 }
1821 }
1822 }
1823
1824 /**
1825 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1826 *
1827 * Clear away output buffers, but keep the Content-Encoding header
1828 * produced by ob_gzhandler, if any.
1829 *
1830 * This should be used for HTTP 304 responses, where you need to
1831 * preserve the Content-Encoding header of the real result, but
1832 * also need to suppress the output of ob_gzhandler to keep to spec
1833 * and avoid breaking Firefox in rare cases where the headers and
1834 * body are broken over two packets.
1835 */
1836 function wfClearOutputBuffers() {
1837 wfResetOutputBuffers( false );
1838 }
1839
1840 /**
1841 * Converts an Accept-* header into an array mapping string values to quality
1842 * factors
1843 *
1844 * @param $accept String
1845 * @param $def String default
1846 * @return Array
1847 */
1848 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1849 # No arg means accept anything (per HTTP spec)
1850 if( !$accept ) {
1851 return array( $def => 1.0 );
1852 }
1853
1854 $prefs = array();
1855
1856 $parts = explode( ',', $accept );
1857
1858 foreach( $parts as $part ) {
1859 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1860 $values = explode( ';', trim( $part ) );
1861 $match = array();
1862 if ( count( $values ) == 1 ) {
1863 $prefs[$values[0]] = 1.0;
1864 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1865 $prefs[$values[0]] = floatval( $match[1] );
1866 }
1867 }
1868
1869 return $prefs;
1870 }
1871
1872 /**
1873 * Checks if a given MIME type matches any of the keys in the given
1874 * array. Basic wildcards are accepted in the array keys.
1875 *
1876 * Returns the matching MIME type (or wildcard) if a match, otherwise
1877 * NULL if no match.
1878 *
1879 * @param $type String
1880 * @param $avail Array
1881 * @return string
1882 * @private
1883 */
1884 function mimeTypeMatch( $type, $avail ) {
1885 if( array_key_exists( $type, $avail ) ) {
1886 return $type;
1887 } else {
1888 $parts = explode( '/', $type );
1889 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1890 return $parts[0] . '/*';
1891 } elseif( array_key_exists( '*/*', $avail ) ) {
1892 return '*/*';
1893 } else {
1894 return null;
1895 }
1896 }
1897 }
1898
1899 /**
1900 * Returns the 'best' match between a client's requested internet media types
1901 * and the server's list of available types. Each list should be an associative
1902 * array of type to preference (preference is a float between 0.0 and 1.0).
1903 * Wildcards in the types are acceptable.
1904 *
1905 * @param $cprefs Array: client's acceptable type list
1906 * @param $sprefs Array: server's offered types
1907 * @return string
1908 *
1909 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1910 * XXX: generalize to negotiate other stuff
1911 */
1912 function wfNegotiateType( $cprefs, $sprefs ) {
1913 $combine = array();
1914
1915 foreach( array_keys( $sprefs ) as $type ) {
1916 $parts = explode( '/', $type );
1917 if( $parts[1] != '*' ) {
1918 $ckey = mimeTypeMatch( $type, $cprefs );
1919 if( $ckey ) {
1920 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1921 }
1922 }
1923 }
1924
1925 foreach( array_keys( $cprefs ) as $type ) {
1926 $parts = explode( '/', $type );
1927 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1928 $skey = mimeTypeMatch( $type, $sprefs );
1929 if( $skey ) {
1930 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1931 }
1932 }
1933 }
1934
1935 $bestq = 0;
1936 $besttype = null;
1937
1938 foreach( array_keys( $combine ) as $type ) {
1939 if( $combine[$type] > $bestq ) {
1940 $besttype = $type;
1941 $bestq = $combine[$type];
1942 }
1943 }
1944
1945 return $besttype;
1946 }
1947
1948 /**
1949 * Reference-counted warning suppression
1950 *
1951 * @param $end Bool
1952 */
1953 function wfSuppressWarnings( $end = false ) {
1954 static $suppressCount = 0;
1955 static $originalLevel = false;
1956
1957 if ( $end ) {
1958 if ( $suppressCount ) {
1959 --$suppressCount;
1960 if ( !$suppressCount ) {
1961 error_reporting( $originalLevel );
1962 }
1963 }
1964 } else {
1965 if ( !$suppressCount ) {
1966 // E_DEPRECATED is undefined in PHP 5.2
1967 if( !defined( 'E_DEPRECATED' ) ) {
1968 define( 'E_DEPRECATED', 8192 );
1969 }
1970 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED ) );
1971 }
1972 ++$suppressCount;
1973 }
1974 }
1975
1976 /**
1977 * Restore error level to previous value
1978 */
1979 function wfRestoreWarnings() {
1980 wfSuppressWarnings( true );
1981 }
1982
1983 # Autodetect, convert and provide timestamps of various types
1984
1985 /**
1986 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1987 */
1988 define( 'TS_UNIX', 0 );
1989
1990 /**
1991 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1992 */
1993 define( 'TS_MW', 1 );
1994
1995 /**
1996 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1997 */
1998 define( 'TS_DB', 2 );
1999
2000 /**
2001 * RFC 2822 format, for E-mail and HTTP headers
2002 */
2003 define( 'TS_RFC2822', 3 );
2004
2005 /**
2006 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2007 *
2008 * This is used by Special:Export
2009 */
2010 define( 'TS_ISO_8601', 4 );
2011
2012 /**
2013 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2014 *
2015 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2016 * DateTime tag and page 36 for the DateTimeOriginal and
2017 * DateTimeDigitized tags.
2018 */
2019 define( 'TS_EXIF', 5 );
2020
2021 /**
2022 * Oracle format time.
2023 */
2024 define( 'TS_ORACLE', 6 );
2025
2026 /**
2027 * Postgres format time.
2028 */
2029 define( 'TS_POSTGRES', 7 );
2030
2031 /**
2032 * DB2 format time
2033 */
2034 define( 'TS_DB2', 8 );
2035
2036 /**
2037 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2038 */
2039 define( 'TS_ISO_8601_BASIC', 9 );
2040
2041 /**
2042 * Get a timestamp string in one of various formats
2043 *
2044 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
2045 * function will autodetect which format is supplied and act
2046 * accordingly.
2047 * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
2048 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2049 */
2050 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2051 $uts = 0;
2052 $da = array();
2053 $strtime = '';
2054
2055 if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
2056 $uts = time();
2057 $strtime = "@$uts";
2058 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2059 # TS_DB
2060 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
2061 # TS_EXIF
2062 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
2063 # TS_MW
2064 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
2065 # TS_UNIX
2066 $uts = $ts;
2067 $strtime = "@$ts"; // Undocumented?
2068 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
2069 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
2070 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
2071 str_replace( '+00:00', 'UTC', $ts ) );
2072 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2073 # TS_ISO_8601
2074 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
2075 #TS_ISO_8601_BASIC
2076 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
2077 # TS_POSTGRES
2078 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
2079 # TS_POSTGRES
2080 } elseif (preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/', $ts, $da ) ) {
2081 # TS_DB2
2082 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
2083 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
2084 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
2085 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
2086 # The regex is a superset of rfc2822 for readability
2087 $strtime = strtok( $ts, ';' );
2088 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
2089 # TS_RFC850
2090 $strtime = $ts;
2091 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
2092 # asctime
2093 $strtime = $ts;
2094 } else {
2095 # Bogus value...
2096 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
2097
2098 return false;
2099 }
2100
2101 static $formats = array(
2102 TS_UNIX => 'U',
2103 TS_MW => 'YmdHis',
2104 TS_DB => 'Y-m-d H:i:s',
2105 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
2106 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
2107 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
2108 TS_RFC2822 => 'D, d M Y H:i:s',
2109 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
2110 TS_POSTGRES => 'Y-m-d H:i:s',
2111 TS_DB2 => 'Y-m-d H:i:s',
2112 );
2113
2114 if ( !isset( $formats[$outputtype] ) ) {
2115 throw new MWException( 'wfTimestamp() called with illegal output type.' );
2116 }
2117
2118 if ( function_exists( "date_create" ) ) {
2119 if ( count( $da ) ) {
2120 $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
2121 (int)$da[1], (int)$da[2], (int)$da[3],
2122 (int)$da[4], (int)$da[5], (int)$da[6]);
2123
2124 $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
2125 } elseif ( $strtime ) {
2126 $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
2127 } else {
2128 return false;
2129 }
2130
2131 if ( !$d ) {
2132 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
2133 return false;
2134 }
2135
2136 $output = $d->format( $formats[$outputtype] );
2137 } else {
2138 if ( count( $da ) ) {
2139 // Warning! gmmktime() acts oddly if the month or day is set to 0
2140 // We may want to handle that explicitly at some point
2141 $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
2142 (int)$da[2], (int)$da[3], (int)$da[1] );
2143 } elseif ( $strtime ) {
2144 $uts = strtotime( $strtime );
2145 }
2146
2147 if ( $uts === false ) {
2148 wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
2149 return false;
2150 }
2151
2152 if ( TS_UNIX == $outputtype ) {
2153 return $uts;
2154 }
2155 $output = gmdate( $formats[$outputtype], $uts );
2156 }
2157
2158 if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
2159 $output .= ' GMT';
2160 }
2161
2162 return $output;
2163 }
2164
2165 /**
2166 * Return a formatted timestamp, or null if input is null.
2167 * For dealing with nullable timestamp columns in the database.
2168 *
2169 * @param $outputtype Integer
2170 * @param $ts String
2171 * @return String
2172 */
2173 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2174 if( is_null( $ts ) ) {
2175 return null;
2176 } else {
2177 return wfTimestamp( $outputtype, $ts );
2178 }
2179 }
2180
2181 /**
2182 * Convenience function; returns MediaWiki timestamp for the present time.
2183 *
2184 * @return string
2185 */
2186 function wfTimestampNow() {
2187 # return NOW
2188 return wfTimestamp( TS_MW, time() );
2189 }
2190
2191 /**
2192 * Check if the operating system is Windows
2193 *
2194 * @return Bool: true if it's Windows, False otherwise.
2195 */
2196 function wfIsWindows() {
2197 static $isWindows = null;
2198 if ( $isWindows === null ) {
2199 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2200 }
2201 return $isWindows;
2202 }
2203
2204 /**
2205 * Check if we are running under HipHop
2206 *
2207 * @return Bool
2208 */
2209 function wfIsHipHop() {
2210 return function_exists( 'hphp_thread_set_warmup_enabled' );
2211 }
2212
2213 /**
2214 * Swap two variables
2215 *
2216 * @param $x Mixed
2217 * @param $y Mixed
2218 */
2219 function swap( &$x, &$y ) {
2220 $z = $x;
2221 $x = $y;
2222 $y = $z;
2223 }
2224
2225 /**
2226 * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
2227 * TEMP environment variables are then checked in sequence, and if none are set
2228 * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
2229 * or C:\Windows\Temp for Windows and hope for the best.
2230 * It is common to call it with tempnam().
2231 *
2232 * NOTE: When possible, use instead the tmpfile() function to create
2233 * temporary files to avoid race conditions on file creation, etc.
2234 *
2235 * @return String
2236 */
2237 function wfTempDir() {
2238 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
2239 $tmp = getenv( $var );
2240 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2241 return $tmp;
2242 }
2243 }
2244 if( function_exists( 'sys_get_temp_dir' ) ) {
2245 return sys_get_temp_dir();
2246 }
2247 # Usual defaults
2248 return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
2249 }
2250
2251 /**
2252 * Make directory, and make all parent directories if they don't exist
2253 *
2254 * @param $dir String: full path to directory to create
2255 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2256 * @param $caller String: optional caller param for debugging.
2257 * @return bool
2258 */
2259 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2260 global $wgDirectoryMode;
2261
2262 if ( !is_null( $caller ) ) {
2263 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2264 }
2265
2266 if( strval( $dir ) === '' || file_exists( $dir ) ) {
2267 return true;
2268 }
2269
2270 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2271
2272 if ( is_null( $mode ) ) {
2273 $mode = $wgDirectoryMode;
2274 }
2275
2276 // Turn off the normal warning, we're doing our own below
2277 wfSuppressWarnings();
2278 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2279 wfRestoreWarnings();
2280
2281 if( !$ok ) {
2282 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2283 trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
2284 }
2285 return $ok;
2286 }
2287
2288 /**
2289 * Increment a statistics counter
2290 *
2291 * @param $key String
2292 * @param $count Int
2293 */
2294 function wfIncrStats( $key, $count = 1 ) {
2295 global $wgStatsMethod;
2296
2297 $count = intval( $count );
2298
2299 if( $wgStatsMethod == 'udp' ) {
2300 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
2301 static $socket;
2302
2303 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname;
2304
2305 if ( !$socket ) {
2306 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
2307 $statline = "stats/{$id} - {$count} 1 1 1 1 -total\n";
2308 socket_sendto(
2309 $socket,
2310 $statline,
2311 strlen( $statline ),
2312 0,
2313 $wgUDPProfilerHost,
2314 $wgUDPProfilerPort
2315 );
2316 }
2317 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
2318 wfSuppressWarnings();
2319 socket_sendto(
2320 $socket,
2321 $statline,
2322 strlen( $statline ),
2323 0,
2324 $wgUDPProfilerHost,
2325 $wgUDPProfilerPort
2326 );
2327 wfRestoreWarnings();
2328 } elseif( $wgStatsMethod == 'cache' ) {
2329 global $wgMemc;
2330 $key = wfMemcKey( 'stats', $key );
2331 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
2332 $wgMemc->add( $key, $count );
2333 }
2334 } else {
2335 // Disabled
2336 }
2337 }
2338
2339 /**
2340 * @param $nr Mixed: the number to format
2341 * @param $acc Integer: the number of digits after the decimal point, default 2
2342 * @param $round Boolean: whether or not to round the value, default true
2343 * @return float
2344 */
2345 function wfPercent( $nr, $acc = 2, $round = true ) {
2346 $ret = sprintf( "%.${acc}f", $nr );
2347 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2348 }
2349
2350 /**
2351 * Find out whether or not a mixed variable exists in a string
2352 *
2353 * @param $needle String
2354 * @param $str String
2355 * @param $insensitive Boolean
2356 * @return Boolean
2357 */
2358 function in_string( $needle, $str, $insensitive = false ) {
2359 $func = 'strpos';
2360 if( $insensitive ) $func = 'stripos';
2361
2362 return $func( $str, $needle ) !== false;
2363 }
2364
2365 /**
2366 * Safety wrapper around ini_get() for boolean settings.
2367 * The values returned from ini_get() are pre-normalized for settings
2368 * set via php.ini or php_flag/php_admin_flag... but *not*
2369 * for those set via php_value/php_admin_value.
2370 *
2371 * It's fairly common for people to use php_value instead of php_flag,
2372 * which can leave you with an 'off' setting giving a false positive
2373 * for code that just takes the ini_get() return value as a boolean.
2374 *
2375 * To make things extra interesting, setting via php_value accepts
2376 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2377 * Unrecognized values go false... again opposite PHP's own coercion
2378 * from string to bool.
2379 *
2380 * Luckily, 'properly' set settings will always come back as '0' or '1',
2381 * so we only have to worry about them and the 'improper' settings.
2382 *
2383 * I frickin' hate PHP... :P
2384 *
2385 * @param $setting String
2386 * @return Bool
2387 */
2388 function wfIniGetBool( $setting ) {
2389 $val = ini_get( $setting );
2390 // 'on' and 'true' can't have whitespace around them, but '1' can.
2391 return strtolower( $val ) == 'on'
2392 || strtolower( $val ) == 'true'
2393 || strtolower( $val ) == 'yes'
2394 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2395 }
2396
2397 /**
2398 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2399 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2400 *
2401 * @param $extension String A PHP extension. The file suffix (.so or .dll)
2402 * should be omitted
2403 * @param $fileName String Name of the library, if not $extension.suffix
2404 * @return Bool - Whether or not the extension is loaded
2405 */
2406 function wfDl( $extension, $fileName = null ) {
2407 if( extension_loaded( $extension ) ) {
2408 return true;
2409 }
2410
2411 $canDl = false;
2412 $sapi = php_sapi_name();
2413 if( version_compare( PHP_VERSION, '5.3.0', '<' ) ||
2414 $sapi == 'cli' || $sapi == 'cgi' || $sapi == 'embed' )
2415 {
2416 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2417 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2418 }
2419
2420 if( $canDl ) {
2421 $fileName = $fileName ? $fileName : $extension;
2422 if( wfIsWindows() ) {
2423 $fileName = 'php_' . $fileName;
2424 }
2425 wfSuppressWarnings();
2426 dl( $fileName . '.' . PHP_SHLIB_SUFFIX );
2427 wfRestoreWarnings();
2428 }
2429 return extension_loaded( $extension );
2430 }
2431
2432 /**
2433 * Windows-compatible version of escapeshellarg()
2434 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2435 * function puts single quotes in regardless of OS.
2436 *
2437 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2438 * earlier distro releases of PHP)
2439 *
2440 * @param varargs
2441 * @return String
2442 */
2443 function wfEscapeShellArg( ) {
2444 wfInitShellLocale();
2445
2446 $args = func_get_args();
2447 $first = true;
2448 $retVal = '';
2449 foreach ( $args as $arg ) {
2450 if ( !$first ) {
2451 $retVal .= ' ';
2452 } else {
2453 $first = false;
2454 }
2455
2456 if ( wfIsWindows() ) {
2457 // Escaping for an MSVC-style command line parser and CMD.EXE
2458 // Refs:
2459 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2460 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2461 // * Bug #13518
2462 // * CR r63214
2463 // Double the backslashes before any double quotes. Escape the double quotes.
2464 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
2465 $arg = '';
2466 $iteration = 0;
2467 foreach ( $tokens as $token ) {
2468 if ( $iteration % 2 == 1 ) {
2469 // Delimiter, a double quote preceded by zero or more slashes
2470 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2471 } elseif ( $iteration % 4 == 2 ) {
2472 // ^ in $token will be outside quotes, need to be escaped
2473 $arg .= str_replace( '^', '^^', $token );
2474 } else { // $iteration % 4 == 0
2475 // ^ in $token will appear inside double quotes, so leave as is
2476 $arg .= $token;
2477 }
2478 $iteration++;
2479 }
2480 // Double the backslashes before the end of the string, because
2481 // we will soon add a quote
2482 $m = array();
2483 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2484 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2485 }
2486
2487 // Add surrounding quotes
2488 $retVal .= '"' . $arg . '"';
2489 } else {
2490 $retVal .= escapeshellarg( $arg );
2491 }
2492 }
2493 return $retVal;
2494 }
2495
2496 /**
2497 * Execute a shell command, with time and memory limits mirrored from the PHP
2498 * configuration if supported.
2499 * @param $cmd String Command line, properly escaped for shell.
2500 * @param &$retval optional, will receive the program's exit code.
2501 * (non-zero is usually failure)
2502 * @param $environ Array optional environment variables which should be
2503 * added to the executed command environment.
2504 * @return collected stdout as a string (trailing newlines stripped)
2505 */
2506 function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
2507 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2508
2509 static $disabled;
2510 if ( is_null( $disabled ) ) {
2511 $disabled = false;
2512 if( wfIniGetBool( 'safe_mode' ) ) {
2513 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2514 $disabled = 'safemode';
2515 } else {
2516 $functions = explode( ',', ini_get( 'disable_functions' ) );
2517 $functions = array_map( 'trim', $functions );
2518 $functions = array_map( 'strtolower', $functions );
2519 if ( in_array( 'passthru', $functions ) ) {
2520 wfDebug( "passthru is in disabled_functions\n" );
2521 $disabled = 'passthru';
2522 }
2523 }
2524 }
2525 if ( $disabled ) {
2526 $retval = 1;
2527 return $disabled == 'safemode' ?
2528 'Unable to run external programs in safe mode.' :
2529 'Unable to run external programs, passthru() is disabled.';
2530 }
2531
2532 wfInitShellLocale();
2533
2534 $envcmd = '';
2535 foreach( $environ as $k => $v ) {
2536 if ( wfIsWindows() ) {
2537 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2538 * appear in the environment variable, so we must use carat escaping as documented in
2539 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2540 * Note however that the quote isn't listed there, but is needed, and the parentheses
2541 * are listed there but doesn't appear to need it.
2542 */
2543 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2544 } else {
2545 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2546 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2547 */
2548 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2549 }
2550 }
2551 $cmd = $envcmd . $cmd;
2552
2553 if ( wfIsWindows() ) {
2554 if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
2555 ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
2556 {
2557 # Hack to work around PHP's flawed invocation of cmd.exe
2558 # http://news.php.net/php.internals/21796
2559 # Windows 9x doesn't accept any kind of quotes
2560 $cmd = '"' . $cmd . '"';
2561 }
2562 } elseif ( php_uname( 's' ) == 'Linux' ) {
2563 $time = intval( $wgMaxShellTime );
2564 $mem = intval( $wgMaxShellMemory );
2565 $filesize = intval( $wgMaxShellFileSize );
2566
2567 if ( $time > 0 && $mem > 0 ) {
2568 $script = "$IP/bin/ulimit4.sh";
2569 if ( is_executable( $script ) ) {
2570 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2571 }
2572 }
2573 }
2574 wfDebug( "wfShellExec: $cmd\n" );
2575
2576 $retval = 1; // error by default?
2577 ob_start();
2578 passthru( $cmd, $retval );
2579 $output = ob_get_contents();
2580 ob_end_clean();
2581
2582 if ( $retval == 127 ) {
2583 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2584 }
2585 return $output;
2586 }
2587
2588 /**
2589 * Workaround for http://bugs.php.net/bug.php?id=45132
2590 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2591 */
2592 function wfInitShellLocale() {
2593 static $done = false;
2594 if ( $done ) {
2595 return;
2596 }
2597 $done = true;
2598 global $wgShellLocale;
2599 if ( !wfIniGetBool( 'safe_mode' ) ) {
2600 putenv( "LC_CTYPE=$wgShellLocale" );
2601 setlocale( LC_CTYPE, $wgShellLocale );
2602 }
2603 }
2604
2605 /**
2606 * Generate a shell-escaped command line string to run a maintenance script.
2607 * Note that $parameters should be a flat array and an option with an argument
2608 * should consist of two consecutive items in the array (do not use "--option value").
2609 * @param $script string MediaWiki maintenance script path
2610 * @param $parameters Array Arguments and options to the script
2611 * @param $options Array Associative array of options:
2612 * 'php': The path to the php executable
2613 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
2614 * @return Array
2615 */
2616 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
2617 global $wgPhpCli;
2618 // Give site config file a chance to run the script in a wrapper.
2619 // The caller may likely want to call wfBasename() on $script.
2620 wfRunHooks( 'wfShellMaintenanceCmd', array( &$script, &$parameters, &$options ) );
2621 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
2622 if ( isset( $options['wrapper'] ) ) {
2623 $cmd[] = $options['wrapper'];
2624 }
2625 $cmd[] = $script;
2626 // Escape each parameter for shell
2627 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
2628 }
2629
2630 /**
2631 * wfMerge attempts to merge differences between three texts.
2632 * Returns true for a clean merge and false for failure or a conflict.
2633 *
2634 * @param $old String
2635 * @param $mine String
2636 * @param $yours String
2637 * @param $result String
2638 * @return Bool
2639 */
2640 function wfMerge( $old, $mine, $yours, &$result ) {
2641 global $wgDiff3;
2642
2643 # This check may also protect against code injection in
2644 # case of broken installations.
2645 wfSuppressWarnings();
2646 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2647 wfRestoreWarnings();
2648
2649 if( !$haveDiff3 ) {
2650 wfDebug( "diff3 not found\n" );
2651 return false;
2652 }
2653
2654 # Make temporary files
2655 $td = wfTempDir();
2656 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2657 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2658 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2659
2660 fwrite( $oldtextFile, $old );
2661 fclose( $oldtextFile );
2662 fwrite( $mytextFile, $mine );
2663 fclose( $mytextFile );
2664 fwrite( $yourtextFile, $yours );
2665 fclose( $yourtextFile );
2666
2667 # Check for a conflict
2668 $cmd = $wgDiff3 . ' -a --overlap-only ' .
2669 wfEscapeShellArg( $mytextName ) . ' ' .
2670 wfEscapeShellArg( $oldtextName ) . ' ' .
2671 wfEscapeShellArg( $yourtextName );
2672 $handle = popen( $cmd, 'r' );
2673
2674 if( fgets( $handle, 1024 ) ) {
2675 $conflict = true;
2676 } else {
2677 $conflict = false;
2678 }
2679 pclose( $handle );
2680
2681 # Merge differences
2682 $cmd = $wgDiff3 . ' -a -e --merge ' .
2683 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
2684 $handle = popen( $cmd, 'r' );
2685 $result = '';
2686 do {
2687 $data = fread( $handle, 8192 );
2688 if ( strlen( $data ) == 0 ) {
2689 break;
2690 }
2691 $result .= $data;
2692 } while ( true );
2693 pclose( $handle );
2694 unlink( $mytextName );
2695 unlink( $oldtextName );
2696 unlink( $yourtextName );
2697
2698 if ( $result === '' && $old !== '' && !$conflict ) {
2699 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
2700 $conflict = true;
2701 }
2702 return !$conflict;
2703 }
2704
2705 /**
2706 * Returns unified plain-text diff of two texts.
2707 * Useful for machine processing of diffs.
2708 *
2709 * @param $before String: the text before the changes.
2710 * @param $after String: the text after the changes.
2711 * @param $params String: command-line options for the diff command.
2712 * @return String: unified diff of $before and $after
2713 */
2714 function wfDiff( $before, $after, $params = '-u' ) {
2715 if ( $before == $after ) {
2716 return '';
2717 }
2718
2719 global $wgDiff;
2720 wfSuppressWarnings();
2721 $haveDiff = $wgDiff && file_exists( $wgDiff );
2722 wfRestoreWarnings();
2723
2724 # This check may also protect against code injection in
2725 # case of broken installations.
2726 if( !$haveDiff ) {
2727 wfDebug( "diff executable not found\n" );
2728 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2729 $format = new UnifiedDiffFormatter();
2730 return $format->format( $diffs );
2731 }
2732
2733 # Make temporary files
2734 $td = wfTempDir();
2735 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2736 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2737
2738 fwrite( $oldtextFile, $before );
2739 fclose( $oldtextFile );
2740 fwrite( $newtextFile, $after );
2741 fclose( $newtextFile );
2742
2743 // Get the diff of the two files
2744 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
2745
2746 $h = popen( $cmd, 'r' );
2747
2748 $diff = '';
2749
2750 do {
2751 $data = fread( $h, 8192 );
2752 if ( strlen( $data ) == 0 ) {
2753 break;
2754 }
2755 $diff .= $data;
2756 } while ( true );
2757
2758 // Clean up
2759 pclose( $h );
2760 unlink( $oldtextName );
2761 unlink( $newtextName );
2762
2763 // Kill the --- and +++ lines. They're not useful.
2764 $diff_lines = explode( "\n", $diff );
2765 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
2766 unset( $diff_lines[0] );
2767 }
2768 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
2769 unset( $diff_lines[1] );
2770 }
2771
2772 $diff = implode( "\n", $diff_lines );
2773
2774 return $diff;
2775 }
2776
2777 /**
2778 * This function works like "use VERSION" in Perl, the program will die with a
2779 * backtrace if the current version of PHP is less than the version provided
2780 *
2781 * This is useful for extensions which due to their nature are not kept in sync
2782 * with releases, and might depend on other versions of PHP than the main code
2783 *
2784 * Note: PHP might die due to parsing errors in some cases before it ever
2785 * manages to call this function, such is life
2786 *
2787 * @see perldoc -f use
2788 *
2789 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2790 * a float
2791 */
2792 function wfUsePHP( $req_ver ) {
2793 $php_ver = PHP_VERSION;
2794
2795 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2796 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2797 }
2798 }
2799
2800 /**
2801 * This function works like "use VERSION" in Perl except it checks the version
2802 * of MediaWiki, the program will die with a backtrace if the current version
2803 * of MediaWiki is less than the version provided.
2804 *
2805 * This is useful for extensions which due to their nature are not kept in sync
2806 * with releases
2807 *
2808 * @see perldoc -f use
2809 *
2810 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
2811 * a float
2812 */
2813 function wfUseMW( $req_ver ) {
2814 global $wgVersion;
2815
2816 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2817 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2818 }
2819 }
2820
2821 /**
2822 * Return the final portion of a pathname.
2823 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2824 * http://bugs.php.net/bug.php?id=33898
2825 *
2826 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2827 * We'll consider it so always, as we don't want \s in our Unix paths either.
2828 *
2829 * @param $path String
2830 * @param $suffix String: to remove if present
2831 * @return String
2832 */
2833 function wfBaseName( $path, $suffix = '' ) {
2834 $encSuffix = ( $suffix == '' )
2835 ? ''
2836 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2837 $matches = array();
2838 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2839 return $matches[1];
2840 } else {
2841 return '';
2842 }
2843 }
2844
2845 /**
2846 * Generate a relative path name to the given file.
2847 * May explode on non-matching case-insensitive paths,
2848 * funky symlinks, etc.
2849 *
2850 * @param $path String: absolute destination path including target filename
2851 * @param $from String: Absolute source path, directory only
2852 * @return String
2853 */
2854 function wfRelativePath( $path, $from ) {
2855 // Normalize mixed input on Windows...
2856 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2857 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2858
2859 // Trim trailing slashes -- fix for drive root
2860 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2861 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2862
2863 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2864 $against = explode( DIRECTORY_SEPARATOR, $from );
2865
2866 if( $pieces[0] !== $against[0] ) {
2867 // Non-matching Windows drive letters?
2868 // Return a full path.
2869 return $path;
2870 }
2871
2872 // Trim off common prefix
2873 while( count( $pieces ) && count( $against )
2874 && $pieces[0] == $against[0] ) {
2875 array_shift( $pieces );
2876 array_shift( $against );
2877 }
2878
2879 // relative dots to bump us to the parent
2880 while( count( $against ) ) {
2881 array_unshift( $pieces, '..' );
2882 array_shift( $against );
2883 }
2884
2885 array_push( $pieces, wfBaseName( $path ) );
2886
2887 return implode( DIRECTORY_SEPARATOR, $pieces );
2888 }
2889
2890 /**
2891 * Do any deferred updates and clear the list
2892 *
2893 * @deprecated since 1.19
2894 * @see DeferredUpdates::doUpdate()
2895 * @param $commit string
2896 */
2897 function wfDoUpdates( $commit = '' ) {
2898 DeferredUpdates::doUpdates( $commit );
2899 }
2900
2901 /**
2902 * Convert an arbitrarily-long digit string from one numeric base
2903 * to another, optionally zero-padding to a minimum column width.
2904 *
2905 * Supports base 2 through 36; digit values 10-36 are represented
2906 * as lowercase letters a-z. Input is case-insensitive.
2907 *
2908 * @param $input String: of digits
2909 * @param $sourceBase Integer: 2-36
2910 * @param $destBase Integer: 2-36
2911 * @param $pad Integer: 1 or greater
2912 * @param $lowercase Boolean
2913 * @return String or false on invalid input
2914 */
2915 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
2916 $input = strval( $input );
2917 if( $sourceBase < 2 ||
2918 $sourceBase > 36 ||
2919 $destBase < 2 ||
2920 $destBase > 36 ||
2921 $pad < 1 ||
2922 $sourceBase != intval( $sourceBase ) ||
2923 $destBase != intval( $destBase ) ||
2924 $pad != intval( $pad ) ||
2925 !is_string( $input ) ||
2926 $input == '' ) {
2927 return false;
2928 }
2929 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2930 $inDigits = array();
2931 $outChars = '';
2932
2933 // Decode and validate input string
2934 $input = strtolower( $input );
2935 for( $i = 0; $i < strlen( $input ); $i++ ) {
2936 $n = strpos( $digitChars, $input[$i] );
2937 if( $n === false || $n > $sourceBase ) {
2938 return false;
2939 }
2940 $inDigits[] = $n;
2941 }
2942
2943 // Iterate over the input, modulo-ing out an output digit
2944 // at a time until input is gone.
2945 while( count( $inDigits ) ) {
2946 $work = 0;
2947 $workDigits = array();
2948
2949 // Long division...
2950 foreach( $inDigits as $digit ) {
2951 $work *= $sourceBase;
2952 $work += $digit;
2953
2954 if( $work < $destBase ) {
2955 // Gonna need to pull another digit.
2956 if( count( $workDigits ) ) {
2957 // Avoid zero-padding; this lets us find
2958 // the end of the input very easily when
2959 // length drops to zero.
2960 $workDigits[] = 0;
2961 }
2962 } else {
2963 // Finally! Actual division!
2964 $workDigits[] = intval( $work / $destBase );
2965
2966 // Isn't it annoying that most programming languages
2967 // don't have a single divide-and-remainder operator,
2968 // even though the CPU implements it that way?
2969 $work = $work % $destBase;
2970 }
2971 }
2972
2973 // All that division leaves us with a remainder,
2974 // which is conveniently our next output digit.
2975 $outChars .= $digitChars[$work];
2976
2977 // And we continue!
2978 $inDigits = $workDigits;
2979 }
2980
2981 while( strlen( $outChars ) < $pad ) {
2982 $outChars .= '0';
2983 }
2984
2985 return strrev( $outChars );
2986 }
2987
2988 /**
2989 * Create an object with a given name and an array of construct parameters
2990 *
2991 * @param $name String
2992 * @param $p Array: parameters
2993 * @return object
2994 * @deprecated since 1.18, warnings in 1.18, removal in 1.20
2995 */
2996 function wfCreateObject( $name, $p ) {
2997 wfDeprecated( __FUNCTION__ );
2998 return MWFunction::newObj( $name, $p );
2999 }
3000
3001 /**
3002 * @return bool
3003 */
3004 function wfHttpOnlySafe() {
3005 global $wgHttpOnlyBlacklist;
3006
3007 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3008 foreach( $wgHttpOnlyBlacklist as $regex ) {
3009 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3010 return false;
3011 }
3012 }
3013 }
3014
3015 return true;
3016 }
3017
3018 /**
3019 * Initialise php session
3020 *
3021 * @param $sessionId Bool
3022 */
3023 function wfSetupSession( $sessionId = false ) {
3024 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
3025 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3026 if( $wgSessionsInMemcached ) {
3027 if ( !defined( 'MW_COMPILED' ) ) {
3028 global $IP;
3029 require_once( "$IP/includes/cache/MemcachedSessions.php" );
3030 }
3031 session_set_save_handler( 'memsess_open', 'memsess_close', 'memsess_read',
3032 'memsess_write', 'memsess_destroy', 'memsess_gc' );
3033
3034 // It's necessary to register a shutdown function to call session_write_close(),
3035 // because by the time the request shutdown function for the session module is
3036 // called, $wgMemc has already been destroyed. Shutdown functions registered
3037 // this way are called before object destruction.
3038 register_shutdown_function( 'memsess_write_close' );
3039 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3040 # Only set this if $wgSessionHandler isn't null and session.save_handler
3041 # hasn't already been set to the desired value (that causes errors)
3042 ini_set( 'session.save_handler', $wgSessionHandler );
3043 }
3044 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
3045 wfDebugLog( 'cookie',
3046 'session_set_cookie_params: "' . implode( '", "',
3047 array(
3048 0,
3049 $wgCookiePath,
3050 $wgCookieDomain,
3051 $wgCookieSecure,
3052 $httpOnlySafe ) ) . '"' );
3053 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
3054 session_cache_limiter( 'private, must-revalidate' );
3055 if ( $sessionId ) {
3056 session_id( $sessionId );
3057 }
3058 wfSuppressWarnings();
3059 session_start();
3060 wfRestoreWarnings();
3061 }
3062
3063 /**
3064 * Get an object from the precompiled serialized directory
3065 *
3066 * @param $name String
3067 * @return Mixed: the variable on success, false on failure
3068 */
3069 function wfGetPrecompiledData( $name ) {
3070 global $IP;
3071
3072 $file = "$IP/serialized/$name";
3073 if ( file_exists( $file ) ) {
3074 $blob = file_get_contents( $file );
3075 if ( $blob ) {
3076 return unserialize( $blob );
3077 }
3078 }
3079 return false;
3080 }
3081
3082 /**
3083 * Get a cache key
3084 *
3085 * @param varargs
3086 * @return String
3087 */
3088 function wfMemcKey( /*... */ ) {
3089 $args = func_get_args();
3090 $key = wfWikiID() . ':' . implode( ':', $args );
3091 $key = str_replace( ' ', '_', $key );
3092 return $key;
3093 }
3094
3095 /**
3096 * Get a cache key for a foreign DB
3097 *
3098 * @param $db String
3099 * @param $prefix String
3100 * @param varargs String
3101 * @return String
3102 */
3103 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3104 $args = array_slice( func_get_args(), 2 );
3105 if ( $prefix ) {
3106 $key = "$db-$prefix:" . implode( ':', $args );
3107 } else {
3108 $key = $db . ':' . implode( ':', $args );
3109 }
3110 return $key;
3111 }
3112
3113 /**
3114 * Get an ASCII string identifying this wiki
3115 * This is used as a prefix in memcached keys
3116 *
3117 * @return String
3118 */
3119 function wfWikiID() {
3120 global $wgDBprefix, $wgDBname, $wgWikiID;
3121 if ( $wgWikiID !== false ) {
3122 return $wgWikiID;
3123 } elseif ( $wgDBprefix ) {
3124 return "$wgDBname-$wgDBprefix";
3125 } else {
3126 return $wgDBname;
3127 }
3128 }
3129
3130 /**
3131 * Split a wiki ID into DB name and table prefix
3132 *
3133 * @param $wiki String
3134 *
3135 * @return array
3136 */
3137 function wfSplitWikiID( $wiki ) {
3138 $bits = explode( '-', $wiki, 2 );
3139 if ( count( $bits ) < 2 ) {
3140 $bits[] = '';
3141 }
3142 return $bits;
3143 }
3144
3145 /**
3146 * Get a Database object.
3147 *
3148 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3149 * master (for write queries), DB_SLAVE for potentially lagged read
3150 * queries, or an integer >= 0 for a particular server.
3151 *
3152 * @param $groups Mixed: query groups. An array of group names that this query
3153 * belongs to. May contain a single string if the query is only
3154 * in one group.
3155 *
3156 * @param $wiki String: the wiki ID, or false for the current wiki
3157 *
3158 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3159 * will always return the same object, unless the underlying connection or load
3160 * balancer is manually destroyed.
3161 *
3162 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3163 * updater to ensure that a proper database is being updated.
3164 *
3165 * @return DatabaseBase
3166 */
3167 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3168 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3169 }
3170
3171 /**
3172 * Get a load balancer object.
3173 *
3174 * @param $wiki String: wiki ID, or false for the current wiki
3175 * @return LoadBalancer
3176 */
3177 function wfGetLB( $wiki = false ) {
3178 return wfGetLBFactory()->getMainLB( $wiki );
3179 }
3180
3181 /**
3182 * Get the load balancer factory object
3183 *
3184 * @return LBFactory
3185 */
3186 function &wfGetLBFactory() {
3187 return LBFactory::singleton();
3188 }
3189
3190 /**
3191 * Find a file.
3192 * Shortcut for RepoGroup::singleton()->findFile()
3193 *
3194 * @param $title String or Title object
3195 * @param $options Associative array of options:
3196 * time: requested time for an archived image, or false for the
3197 * current version. An image object will be returned which was
3198 * created at the specified time.
3199 *
3200 * ignoreRedirect: If true, do not follow file redirects
3201 *
3202 * private: If true, return restricted (deleted) files if the current
3203 * user is allowed to view them. Otherwise, such files will not
3204 * be found.
3205 *
3206 * bypassCache: If true, do not use the process-local cache of File objects
3207 *
3208 * @return File, or false if the file does not exist
3209 */
3210 function wfFindFile( $title, $options = array() ) {
3211 return RepoGroup::singleton()->findFile( $title, $options );
3212 }
3213
3214 /**
3215 * Get an object referring to a locally registered file.
3216 * Returns a valid placeholder object if the file does not exist.
3217 *
3218 * @param $title Title or String
3219 * @return File, or null if passed an invalid Title
3220 */
3221 function wfLocalFile( $title ) {
3222 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3223 }
3224
3225 /**
3226 * Stream a file to the browser. Back-compat alias for StreamFile::stream()
3227 * @deprecated since 1.19
3228 */
3229 function wfStreamFile( $fname, $headers = array() ) {
3230 StreamFile::stream( $fname, $headers );
3231 }
3232
3233 /**
3234 * Should low-performance queries be disabled?
3235 *
3236 * @return Boolean
3237 * @codeCoverageIgnore
3238 */
3239 function wfQueriesMustScale() {
3240 global $wgMiserMode;
3241 return $wgMiserMode
3242 || ( SiteStats::pages() > 100000
3243 && SiteStats::edits() > 1000000
3244 && SiteStats::users() > 10000 );
3245 }
3246
3247 /**
3248 * Get the path to a specified script file, respecting file
3249 * extensions; this is a wrapper around $wgScriptExtension etc.
3250 *
3251 * @param $script String: script filename, sans extension
3252 * @return String
3253 */
3254 function wfScript( $script = 'index' ) {
3255 global $wgScriptPath, $wgScriptExtension;
3256 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3257 }
3258
3259 /**
3260 * Get the script URL.
3261 *
3262 * @return script URL
3263 */
3264 function wfGetScriptUrl() {
3265 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3266 #
3267 # as it was called, minus the query string.
3268 #
3269 # Some sites use Apache rewrite rules to handle subdomains,
3270 # and have PHP set up in a weird way that causes PHP_SELF
3271 # to contain the rewritten URL instead of the one that the
3272 # outside world sees.
3273 #
3274 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3275 # provides containing the "before" URL.
3276 return $_SERVER['SCRIPT_NAME'];
3277 } else {
3278 return $_SERVER['URL'];
3279 }
3280 }
3281
3282 /**
3283 * Convenience function converts boolean values into "true"
3284 * or "false" (string) values
3285 *
3286 * @param $value Boolean
3287 * @return String
3288 */
3289 function wfBoolToStr( $value ) {
3290 return $value ? 'true' : 'false';
3291 }
3292
3293 /**
3294 * Load an extension messages file
3295 *
3296 * @deprecated since 1.16, warnings in 1.18, remove in 1.20
3297 * @codeCoverageIgnore
3298 */
3299 function wfLoadExtensionMessages() {
3300 wfDeprecated( __FUNCTION__ );
3301 }
3302
3303 /**
3304 * Get a platform-independent path to the null file, e.g. /dev/null
3305 *
3306 * @return string
3307 */
3308 function wfGetNull() {
3309 return wfIsWindows()
3310 ? 'NUL'
3311 : '/dev/null';
3312 }
3313
3314 /**
3315 * Throws a warning that $function is deprecated
3316 *
3317 * @param $function String
3318 * @param $version String
3319 * @return null
3320 */
3321 function wfDeprecated( $function, $version = false ) {
3322 static $functionsWarned = array();
3323 if ( !isset( $functionsWarned[$function] ) ) {
3324 $functionsWarned[$function] = true;
3325 if ( $version ) {
3326 global $wgDeprecationReleaseLimit;
3327 if ( $wgDeprecationReleaseLimit ) {
3328 # Strip -* off the end of $version so that branches can use the
3329 # format #.##-branchname to avoid issues if the branch is merged into
3330 # a version of MediaWiki later than what it was branched from
3331 $comparableVersion = preg_replace( '/-.*$/', '', $version );
3332 # If the comparableVersion is larger than our release limit then
3333 # skip the warning message for the deprecation
3334 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
3335 return;
3336 }
3337 }
3338 wfWarn( "Use of $function was deprecated in $version.", 2 );
3339 } else {
3340 wfWarn( "Use of $function is deprecated.", 2 );
3341 }
3342 }
3343 }
3344
3345 /**
3346 * Send a warning either to the debug log or in a PHP error depending on
3347 * $wgDevelopmentWarnings
3348 *
3349 * @param $msg String: message to send
3350 * @param $callerOffset Integer: number of items to go back in the backtrace to
3351 * find the correct caller (1 = function calling wfWarn, ...)
3352 * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
3353 * is true
3354 */
3355 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
3356 global $wgDevelopmentWarnings;
3357
3358 $callers = wfDebugBacktrace();
3359 if ( isset( $callers[$callerOffset + 1] ) ) {
3360 $callerfunc = $callers[$callerOffset + 1];
3361 $callerfile = $callers[$callerOffset];
3362 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
3363 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
3364 } else {
3365 $file = '(internal function)';
3366 }
3367 $func = '';
3368 if ( isset( $callerfunc['class'] ) ) {
3369 $func .= $callerfunc['class'] . '::';
3370 }
3371 if ( isset( $callerfunc['function'] ) ) {
3372 $func .= $callerfunc['function'];
3373 }
3374 $msg .= " [Called from $func in $file]";
3375 }
3376
3377 if ( $wgDevelopmentWarnings ) {
3378 trigger_error( $msg, $level );
3379 } else {
3380 wfDebug( "$msg\n" );
3381 }
3382 }
3383
3384 /**
3385 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3386 * and waiting for it to go down, this waits for the slaves to catch up to the
3387 * master position. Use this when updating very large numbers of rows, as
3388 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3389 * a no-op if there are no slaves.
3390 *
3391 * @param $maxLag Integer (deprecated)
3392 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3393 */
3394 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
3395 $lb = wfGetLB( $wiki );
3396 // bug 27975 - Don't try to wait for slaves if there are none
3397 // Prevents permission error when getting master position
3398 if ( $lb->getServerCount() > 1 ) {
3399 $dbw = $lb->getConnection( DB_MASTER );
3400 $pos = $dbw->getMasterPos();
3401 $lb->waitForAll( $pos );
3402 }
3403 }
3404
3405 /**
3406 * Used to be used for outputting text in the installer/updater
3407 * @deprecated since 1.18, warnings in 1.18, remove in 1.20
3408 */
3409 function wfOut( $s ) {
3410 wfDeprecated( __METHOD__ );
3411 global $wgCommandLineMode;
3412 if ( $wgCommandLineMode ) {
3413 echo $s;
3414 } else {
3415 echo htmlspecialchars( $s );
3416 }
3417 flush();
3418 }
3419
3420 /**
3421 * Count down from $n to zero on the terminal, with a one-second pause
3422 * between showing each number. For use in command-line scripts.
3423 * @codeCoverageIgnore
3424 * @param $n int
3425 */
3426 function wfCountDown( $n ) {
3427 for ( $i = $n; $i >= 0; $i-- ) {
3428 if ( $i != $n ) {
3429 echo str_repeat( "\x08", strlen( $i + 1 ) );
3430 }
3431 echo $i;
3432 flush();
3433 if ( $i ) {
3434 sleep( 1 );
3435 }
3436 }
3437 echo "\n";
3438 }
3439
3440 /**
3441 * Generate a random 32-character hexadecimal token.
3442 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3443 * characters before hashing.
3444 * @return string
3445 * @codeCoverageIgnore
3446 */
3447 function wfGenerateToken( $salt = '' ) {
3448 $salt = serialize( $salt );
3449 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3450 }
3451
3452 /**
3453 * Replace all invalid characters with -
3454 *
3455 * @param $name Mixed: filename to process
3456 * @return String
3457 */
3458 function wfStripIllegalFilenameChars( $name ) {
3459 global $wgIllegalFileChars;
3460 $name = wfBaseName( $name );
3461 $name = preg_replace(
3462 "/[^" . Title::legalChars() . "]" .
3463 ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
3464 "/",
3465 '-',
3466 $name
3467 );
3468 return $name;
3469 }
3470
3471 /**
3472 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3473 *
3474 * @return Integer value memory was set to.
3475 */
3476 function wfMemoryLimit() {
3477 global $wgMemoryLimit;
3478 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3479 if( $memlimit != -1 ) {
3480 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3481 if( $conflimit == -1 ) {
3482 wfDebug( "Removing PHP's memory limit\n" );
3483 wfSuppressWarnings();
3484 ini_set( 'memory_limit', $conflimit );
3485 wfRestoreWarnings();
3486 return $conflimit;
3487 } elseif ( $conflimit > $memlimit ) {
3488 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3489 wfSuppressWarnings();
3490 ini_set( 'memory_limit', $conflimit );
3491 wfRestoreWarnings();
3492 return $conflimit;
3493 }
3494 }
3495 return $memlimit;
3496 }
3497
3498 /**
3499 * Converts shorthand byte notation to integer form
3500 *
3501 * @param $string String
3502 * @return Integer
3503 */
3504 function wfShorthandToInteger( $string = '' ) {
3505 $string = trim( $string );
3506 if( $string === '' ) {
3507 return -1;
3508 }
3509 $last = $string[strlen( $string ) - 1];
3510 $val = intval( $string );
3511 switch( $last ) {
3512 case 'g':
3513 case 'G':
3514 $val *= 1024;
3515 // break intentionally missing
3516 case 'm':
3517 case 'M':
3518 $val *= 1024;
3519 // break intentionally missing
3520 case 'k':
3521 case 'K':
3522 $val *= 1024;
3523 }
3524
3525 return $val;
3526 }
3527
3528 /**
3529 * Get the normalised IETF language tag
3530 * See unit test for examples.
3531 *
3532 * @param $code String: The language code.
3533 * @return String: The language code which complying with BCP 47 standards.
3534 */
3535 function wfBCP47( $code ) {
3536 $codeSegment = explode( '-', $code );
3537 $codeBCP = array();
3538 foreach ( $codeSegment as $segNo => $seg ) {
3539 if ( count( $codeSegment ) > 0 ) {
3540 // when previous segment is x, it is a private segment and should be lc
3541 if( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3542 $codeBCP[$segNo] = strtolower( $seg );
3543 // ISO 3166 country code
3544 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3545 $codeBCP[$segNo] = strtoupper( $seg );
3546 // ISO 15924 script code
3547 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3548 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3549 // Use lowercase for other cases
3550 } else {
3551 $codeBCP[$segNo] = strtolower( $seg );
3552 }
3553 } else {
3554 // Use lowercase for single segment
3555 $codeBCP[$segNo] = strtolower( $seg );
3556 }
3557 }
3558 $langCode = implode( '-', $codeBCP );
3559 return $langCode;
3560 }
3561
3562 /**
3563 * Get a cache object.
3564 *
3565 * @param $inputType integer Cache type, one the the CACHE_* constants.
3566 * @return BagOStuff
3567 */
3568 function wfGetCache( $inputType ) {
3569 return ObjectCache::getInstance( $inputType );
3570 }
3571
3572 /**
3573 * Get the main cache object
3574 *
3575 * @return BagOStuff
3576 */
3577 function wfGetMainCache() {
3578 global $wgMainCacheType;
3579 return ObjectCache::getInstance( $wgMainCacheType );
3580 }
3581
3582 /**
3583 * Get the cache object used by the message cache
3584 *
3585 * @return BagOStuff
3586 */
3587 function wfGetMessageCacheStorage() {
3588 global $wgMessageCacheType;
3589 return ObjectCache::getInstance( $wgMessageCacheType );
3590 }
3591
3592 /**
3593 * Get the cache object used by the parser cache
3594 *
3595 * @return BagOStuff
3596 */
3597 function wfGetParserCacheStorage() {
3598 global $wgParserCacheType;
3599 return ObjectCache::getInstance( $wgParserCacheType );
3600 }
3601
3602 /**
3603 * Call hook functions defined in $wgHooks
3604 *
3605 * @param $event String: event name
3606 * @param $args Array: parameters passed to hook functions
3607 * @return Boolean
3608 */
3609 function wfRunHooks( $event, $args = array() ) {
3610 return Hooks::run( $event, $args );
3611 }
3612
3613 /**
3614 * Wrapper around php's unpack.
3615 *
3616 * @param $format String: The format string (See php's docs)
3617 * @param $data: A binary string of binary data
3618 * @param $length integer or false: The minimun length of $data. This is to
3619 * prevent reading beyond the end of $data. false to disable the check.
3620 *
3621 * Also be careful when using this function to read unsigned 32 bit integer
3622 * because php might make it negative.
3623 *
3624 * @throws MWException if $data not long enough, or if unpack fails
3625 * @return Associative array of the extracted data
3626 */
3627 function wfUnpack( $format, $data, $length=false ) {
3628 if ( $length !== false ) {
3629 $realLen = strlen( $data );
3630 if ( $realLen < $length ) {
3631 throw new MWException( "Tried to use wfUnpack on a "
3632 . "string of length $realLen, but needed one "
3633 . "of at least length $length."
3634 );
3635 }
3636 }
3637
3638 wfSuppressWarnings();
3639 $result = unpack( $format, $data );
3640 wfRestoreWarnings();
3641
3642 if ( $result === false ) {
3643 // If it cannot extract the packed data.
3644 throw new MWException( "unpack could not unpack binary data" );
3645 }
3646 return $result;
3647 }