MediaWiki
master
|
00001 <?php 00023 if ( !defined( 'MEDIAWIKI' ) ) { 00024 die( "This file is part of MediaWiki, it is not a valid entry point" ); 00025 } 00026 00027 // Hide compatibility functions from Doxygen 00029 00038 if( !function_exists( 'iconv' ) ) { 00043 function iconv( $from, $to, $string ) { 00044 return Fallback::iconv( $from, $to, $string ); 00045 } 00046 } 00047 00048 if ( !function_exists( 'mb_substr' ) ) { 00053 function mb_substr( $str, $start, $count='end' ) { 00054 return Fallback::mb_substr( $str, $start, $count ); 00055 } 00056 00061 function mb_substr_split_unicode( $str, $splitPos ) { 00062 return Fallback::mb_substr_split_unicode( $str, $splitPos ); 00063 } 00064 } 00065 00066 if ( !function_exists( 'mb_strlen' ) ) { 00071 function mb_strlen( $str, $enc = '' ) { 00072 return Fallback::mb_strlen( $str, $enc ); 00073 } 00074 } 00075 00076 if( !function_exists( 'mb_strpos' ) ) { 00081 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) { 00082 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding ); 00083 } 00084 00085 } 00086 00087 if( !function_exists( 'mb_strrpos' ) ) { 00092 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) { 00093 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding ); 00094 } 00095 } 00096 00097 00098 // Support for Wietse Venema's taint feature 00099 if ( !function_exists( 'istainted' ) ) { 00104 function istainted( $var ) { 00105 return 0; 00106 } 00108 function taint( $var, $level = 0 ) {} 00110 function untaint( $var, $level = 0 ) {} 00111 define( 'TC_HTML', 1 ); 00112 define( 'TC_SHELL', 1 ); 00113 define( 'TC_MYSQL', 1 ); 00114 define( 'TC_PCRE', 1 ); 00115 define( 'TC_SELF', 1 ); 00116 } 00118 00125 function wfArrayDiff2( $a, $b ) { 00126 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' ); 00127 } 00128 00134 function wfArrayDiff2_cmp( $a, $b ) { 00135 if ( !is_array( $a ) ) { 00136 return strcmp( $a, $b ); 00137 } elseif ( count( $a ) !== count( $b ) ) { 00138 return count( $a ) < count( $b ) ? -1 : 1; 00139 } else { 00140 reset( $a ); 00141 reset( $b ); 00142 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) { 00143 $cmp = strcmp( $valueA, $valueB ); 00144 if ( $cmp !== 0 ) { 00145 return $cmp; 00146 } 00147 } 00148 return 0; 00149 } 00150 } 00151 00161 function wfArrayLookup( $a, $b ) { 00162 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) ); 00163 } 00164 00174 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) { 00175 if ( is_null( $changed ) ) { 00176 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' ); 00177 } 00178 if ( $default[$key] !== $value ) { 00179 $changed[$key] = $value; 00180 } 00181 } 00182 00191 function wfArrayMerge( $array1/* ... */ ) { 00192 $args = func_get_args(); 00193 $args = array_reverse( $args, true ); 00194 $out = array(); 00195 foreach ( $args as $arg ) { 00196 $out += $arg; 00197 } 00198 return $out; 00199 } 00200 00219 function wfMergeErrorArrays( /*...*/ ) { 00220 $args = func_get_args(); 00221 $out = array(); 00222 foreach ( $args as $errors ) { 00223 foreach ( $errors as $params ) { 00224 # @todo FIXME: Sometimes get nested arrays for $params, 00225 # which leads to E_NOTICEs 00226 $spec = implode( "\t", $params ); 00227 $out[$spec] = $params; 00228 } 00229 } 00230 return array_values( $out ); 00231 } 00232 00241 function wfArrayInsertAfter( array $array, array $insert, $after ) { 00242 // Find the offset of the element to insert after. 00243 $keys = array_keys( $array ); 00244 $offsetByKey = array_flip( $keys ); 00245 00246 $offset = $offsetByKey[$after]; 00247 00248 // Insert at the specified offset 00249 $before = array_slice( $array, 0, $offset + 1, true ); 00250 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true ); 00251 00252 $output = $before + $insert + $after; 00253 00254 return $output; 00255 } 00256 00264 function wfObjectToArray( $objOrArray, $recursive = true ) { 00265 $array = array(); 00266 if( is_object( $objOrArray ) ) { 00267 $objOrArray = get_object_vars( $objOrArray ); 00268 } 00269 foreach ( $objOrArray as $key => $value ) { 00270 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) { 00271 $value = wfObjectToArray( $value ); 00272 } 00273 00274 $array[$key] = $value; 00275 } 00276 00277 return $array; 00278 } 00279 00287 function wfArrayMap( $function, $input ) { 00288 $ret = array_map( $function, $input ); 00289 foreach ( $ret as $key => $value ) { 00290 $taint = istainted( $input[$key] ); 00291 if ( $taint ) { 00292 taint( $ret[$key], $taint ); 00293 } 00294 } 00295 return $ret; 00296 } 00297 00305 function wfRandom() { 00306 # The maximum random value is "only" 2^31-1, so get two random 00307 # values to reduce the chance of dupes 00308 $max = mt_getrandmax() + 1; 00309 $rand = number_format( ( mt_rand() * $max + mt_rand() ) 00310 / $max / $max, 12, '.', '' ); 00311 return $rand; 00312 } 00313 00324 function wfRandomString( $length = 32 ) { 00325 $str = ''; 00326 while ( strlen( $str ) < $length ) { 00327 $str .= dechex( mt_rand() ); 00328 } 00329 return substr( $str, 0, $length ); 00330 } 00331 00354 function wfUrlencode( $s ) { 00355 static $needle; 00356 if ( is_null( $s ) ) { 00357 $needle = null; 00358 return ''; 00359 } 00360 00361 if ( is_null( $needle ) ) { 00362 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' ); 00363 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) { 00364 $needle[] = '%3A'; 00365 } 00366 } 00367 00368 $s = urlencode( $s ); 00369 $s = str_ireplace( 00370 $needle, 00371 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ), 00372 $s 00373 ); 00374 00375 return $s; 00376 } 00377 00388 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) { 00389 if ( !is_null( $array2 ) ) { 00390 $array1 = $array1 + $array2; 00391 } 00392 00393 $cgi = ''; 00394 foreach ( $array1 as $key => $value ) { 00395 if ( !is_null($value) && $value !== false ) { 00396 if ( $cgi != '' ) { 00397 $cgi .= '&'; 00398 } 00399 if ( $prefix !== '' ) { 00400 $key = $prefix . "[$key]"; 00401 } 00402 if ( is_array( $value ) ) { 00403 $firstTime = true; 00404 foreach ( $value as $k => $v ) { 00405 $cgi .= $firstTime ? '' : '&'; 00406 if ( is_array( $v ) ) { 00407 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" ); 00408 } else { 00409 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v ); 00410 } 00411 $firstTime = false; 00412 } 00413 } else { 00414 if ( is_object( $value ) ) { 00415 $value = $value->__toString(); 00416 } 00417 $cgi .= urlencode( $key ) . '=' . urlencode( $value ); 00418 } 00419 } 00420 } 00421 return $cgi; 00422 } 00423 00433 function wfCgiToArray( $query ) { 00434 if ( isset( $query[0] ) && $query[0] == '?' ) { 00435 $query = substr( $query, 1 ); 00436 } 00437 $bits = explode( '&', $query ); 00438 $ret = array(); 00439 foreach ( $bits as $bit ) { 00440 if ( $bit === '' ) { 00441 continue; 00442 } 00443 if ( strpos( $bit, '=' ) === false ) { 00444 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does) 00445 $key = $bit; 00446 $value = ''; 00447 } else { 00448 list( $key, $value ) = explode( '=', $bit ); 00449 } 00450 $key = urldecode( $key ); 00451 $value = urldecode( $value ); 00452 if ( strpos( $key, '[' ) !== false ) { 00453 $keys = array_reverse( explode( '[', $key ) ); 00454 $key = array_pop( $keys ); 00455 $temp = $value; 00456 foreach ( $keys as $k ) { 00457 $k = substr( $k, 0, -1 ); 00458 $temp = array( $k => $temp ); 00459 } 00460 if ( isset( $ret[$key] ) ) { 00461 $ret[$key] = array_merge( $ret[$key], $temp ); 00462 } else { 00463 $ret[$key] = $temp; 00464 } 00465 } else { 00466 $ret[$key] = $value; 00467 } 00468 } 00469 return $ret; 00470 } 00471 00480 function wfAppendQuery( $url, $query ) { 00481 if ( is_array( $query ) ) { 00482 $query = wfArrayToCgi( $query ); 00483 } 00484 if( $query != '' ) { 00485 if( false === strpos( $url, '?' ) ) { 00486 $url .= '?'; 00487 } else { 00488 $url .= '&'; 00489 } 00490 $url .= $query; 00491 } 00492 return $url; 00493 } 00494 00517 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) { 00518 global $wgServer, $wgCanonicalServer, $wgInternalServer; 00519 $serverUrl = $wgServer; 00520 if ( $defaultProto === PROTO_CANONICAL ) { 00521 $serverUrl = $wgCanonicalServer; 00522 } 00523 // Make $wgInternalServer fall back to $wgServer if not set 00524 if ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) { 00525 $serverUrl = $wgInternalServer; 00526 } 00527 if ( $defaultProto === PROTO_CURRENT ) { 00528 $defaultProto = WebRequest::detectProtocol() . '://'; 00529 } 00530 00531 // Analyze $serverUrl to obtain its protocol 00532 $bits = wfParseUrl( $serverUrl ); 00533 $serverHasProto = $bits && $bits['scheme'] != ''; 00534 00535 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) { 00536 if ( $serverHasProto ) { 00537 $defaultProto = $bits['scheme'] . '://'; 00538 } else { 00539 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol. This really isn't supposed to happen 00540 // Fall back to HTTP in this ridiculous case 00541 $defaultProto = PROTO_HTTP; 00542 } 00543 } 00544 00545 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 ); 00546 00547 if ( substr( $url, 0, 2 ) == '//' ) { 00548 $url = $defaultProtoWithoutSlashes . $url; 00549 } elseif ( substr( $url, 0, 1 ) == '/' ) { 00550 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes, otherwise leave it alone 00551 $url = ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url; 00552 } 00553 00554 $bits = wfParseUrl( $url ); 00555 if ( $bits && isset( $bits['path'] ) ) { 00556 $bits['path'] = wfRemoveDotSegments( $bits['path'] ); 00557 return wfAssembleUrl( $bits ); 00558 } elseif ( $bits ) { 00559 # No path to expand 00560 return $url; 00561 } elseif ( substr( $url, 0, 1 ) != '/' ) { 00562 # URL is a relative path 00563 return wfRemoveDotSegments( $url ); 00564 } 00565 00566 # Expanded URL is not valid. 00567 return false; 00568 } 00569 00583 function wfAssembleUrl( $urlParts ) { 00584 $result = ''; 00585 00586 if ( isset( $urlParts['delimiter'] ) ) { 00587 if ( isset( $urlParts['scheme'] ) ) { 00588 $result .= $urlParts['scheme']; 00589 } 00590 00591 $result .= $urlParts['delimiter']; 00592 } 00593 00594 if ( isset( $urlParts['host'] ) ) { 00595 if ( isset( $urlParts['user'] ) ) { 00596 $result .= $urlParts['user']; 00597 if ( isset( $urlParts['pass'] ) ) { 00598 $result .= ':' . $urlParts['pass']; 00599 } 00600 $result .= '@'; 00601 } 00602 00603 $result .= $urlParts['host']; 00604 00605 if ( isset( $urlParts['port'] ) ) { 00606 $result .= ':' . $urlParts['port']; 00607 } 00608 } 00609 00610 if ( isset( $urlParts['path'] ) ) { 00611 $result .= $urlParts['path']; 00612 } 00613 00614 if ( isset( $urlParts['query'] ) ) { 00615 $result .= '?' . $urlParts['query']; 00616 } 00617 00618 if ( isset( $urlParts['fragment'] ) ) { 00619 $result .= '#' . $urlParts['fragment']; 00620 } 00621 00622 return $result; 00623 } 00624 00635 function wfRemoveDotSegments( $urlPath ) { 00636 $output = ''; 00637 $inputOffset = 0; 00638 $inputLength = strlen( $urlPath ); 00639 00640 while ( $inputOffset < $inputLength ) { 00641 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 ); 00642 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 ); 00643 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 ); 00644 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 ); 00645 $trimOutput = false; 00646 00647 if ( $prefixLengthTwo == './' ) { 00648 # Step A, remove leading "./" 00649 $inputOffset += 2; 00650 } elseif ( $prefixLengthThree == '../' ) { 00651 # Step A, remove leading "../" 00652 $inputOffset += 3; 00653 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) { 00654 # Step B, replace leading "/.$" with "/" 00655 $inputOffset += 1; 00656 $urlPath[$inputOffset] = '/'; 00657 } elseif ( $prefixLengthThree == '/./' ) { 00658 # Step B, replace leading "/./" with "/" 00659 $inputOffset += 2; 00660 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) { 00661 # Step C, replace leading "/..$" with "/" and 00662 # remove last path component in output 00663 $inputOffset += 2; 00664 $urlPath[$inputOffset] = '/'; 00665 $trimOutput = true; 00666 } elseif ( $prefixLengthFour == '/../' ) { 00667 # Step C, replace leading "/../" with "/" and 00668 # remove last path component in output 00669 $inputOffset += 3; 00670 $trimOutput = true; 00671 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) { 00672 # Step D, remove "^.$" 00673 $inputOffset += 1; 00674 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) { 00675 # Step D, remove "^..$" 00676 $inputOffset += 2; 00677 } else { 00678 # Step E, move leading path segment to output 00679 if ( $prefixLengthOne == '/' ) { 00680 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 ); 00681 } else { 00682 $slashPos = strpos( $urlPath, '/', $inputOffset ); 00683 } 00684 if ( $slashPos === false ) { 00685 $output .= substr( $urlPath, $inputOffset ); 00686 $inputOffset = $inputLength; 00687 } else { 00688 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset ); 00689 $inputOffset += $slashPos - $inputOffset; 00690 } 00691 } 00692 00693 if ( $trimOutput ) { 00694 $slashPos = strrpos( $output, '/' ); 00695 if ( $slashPos === false ) { 00696 $output = ''; 00697 } else { 00698 $output = substr( $output, 0, $slashPos ); 00699 } 00700 } 00701 } 00702 00703 return $output; 00704 } 00705 00713 function wfUrlProtocols( $includeProtocolRelative = true ) { 00714 global $wgUrlProtocols; 00715 00716 // Cache return values separately based on $includeProtocolRelative 00717 static $withProtRel = null, $withoutProtRel = null; 00718 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel; 00719 if ( !is_null( $cachedValue ) ) { 00720 return $cachedValue; 00721 } 00722 00723 // Support old-style $wgUrlProtocols strings, for backwards compatibility 00724 // with LocalSettings files from 1.5 00725 if ( is_array( $wgUrlProtocols ) ) { 00726 $protocols = array(); 00727 foreach ( $wgUrlProtocols as $protocol ) { 00728 // Filter out '//' if !$includeProtocolRelative 00729 if ( $includeProtocolRelative || $protocol !== '//' ) { 00730 $protocols[] = preg_quote( $protocol, '/' ); 00731 } 00732 } 00733 00734 $retval = implode( '|', $protocols ); 00735 } else { 00736 // Ignore $includeProtocolRelative in this case 00737 // This case exists for pre-1.6 compatibility, and we can safely assume 00738 // that '//' won't appear in a pre-1.6 config because protocol-relative 00739 // URLs weren't supported until 1.18 00740 $retval = $wgUrlProtocols; 00741 } 00742 00743 // Cache return value 00744 if ( $includeProtocolRelative ) { 00745 $withProtRel = $retval; 00746 } else { 00747 $withoutProtRel = $retval; 00748 } 00749 return $retval; 00750 } 00751 00758 function wfUrlProtocolsWithoutProtRel() { 00759 return wfUrlProtocols( false ); 00760 } 00761 00772 function wfParseUrl( $url ) { 00773 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php 00774 00775 // Protocol-relative URLs are handled really badly by parse_url(). It's so bad that the easiest 00776 // way to handle them is to just prepend 'http:' and strip the protocol out later 00777 $wasRelative = substr( $url, 0, 2 ) == '//'; 00778 if ( $wasRelative ) { 00779 $url = "http:$url"; 00780 } 00781 wfSuppressWarnings(); 00782 $bits = parse_url( $url ); 00783 wfRestoreWarnings(); 00784 // parse_url() returns an array without scheme for some invalid URLs, e.g. 00785 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' ) 00786 if ( !$bits || !isset( $bits['scheme'] ) ) { 00787 return false; 00788 } 00789 00790 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase. 00791 $bits['scheme'] = strtolower( $bits['scheme'] ); 00792 00793 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it 00794 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) { 00795 $bits['delimiter'] = '://'; 00796 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) { 00797 $bits['delimiter'] = ':'; 00798 // parse_url detects for news: and mailto: the host part of an url as path 00799 // We have to correct this wrong detection 00800 if ( isset( $bits['path'] ) ) { 00801 $bits['host'] = $bits['path']; 00802 $bits['path'] = ''; 00803 } 00804 } else { 00805 return false; 00806 } 00807 00808 /* Provide an empty host for eg. file:/// urls (see bug 28627) */ 00809 if ( !isset( $bits['host'] ) ) { 00810 $bits['host'] = ''; 00811 00812 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */ 00813 if ( substr( $bits['path'], 0, 1 ) !== '/' ) { 00814 $bits['path'] = '/' . $bits['path']; 00815 } 00816 } 00817 00818 // If the URL was protocol-relative, fix scheme and delimiter 00819 if ( $wasRelative ) { 00820 $bits['scheme'] = ''; 00821 $bits['delimiter'] = '//'; 00822 } 00823 return $bits; 00824 } 00825 00836 function wfExpandIRI( $url ) { 00837 return preg_replace_callback( '/((?:%[89A-F][0-9A-F])+)/i', 'wfExpandIRI_callback', wfExpandUrl( $url ) ); 00838 } 00839 00845 function wfExpandIRI_callback( $matches ) { 00846 return urldecode( $matches[1] ); 00847 } 00848 00849 00850 00857 function wfMakeUrlIndexes( $url ) { 00858 $bits = wfParseUrl( $url ); 00859 00860 // Reverse the labels in the hostname, convert to lower case 00861 // For emails reverse domainpart only 00862 if ( $bits['scheme'] == 'mailto' ) { 00863 $mailparts = explode( '@', $bits['host'], 2 ); 00864 if ( count( $mailparts ) === 2 ) { 00865 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) ); 00866 } else { 00867 // No domain specified, don't mangle it 00868 $domainpart = ''; 00869 } 00870 $reversedHost = $domainpart . '@' . $mailparts[0]; 00871 } else { 00872 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) ); 00873 } 00874 // Add an extra dot to the end 00875 // Why? Is it in wrong place in mailto links? 00876 if ( substr( $reversedHost, -1, 1 ) !== '.' ) { 00877 $reversedHost .= '.'; 00878 } 00879 // Reconstruct the pseudo-URL 00880 $prot = $bits['scheme']; 00881 $index = $prot . $bits['delimiter'] . $reversedHost; 00882 // Leave out user and password. Add the port, path, query and fragment 00883 if ( isset( $bits['port'] ) ) { 00884 $index .= ':' . $bits['port']; 00885 } 00886 if ( isset( $bits['path'] ) ) { 00887 $index .= $bits['path']; 00888 } else { 00889 $index .= '/'; 00890 } 00891 if ( isset( $bits['query'] ) ) { 00892 $index .= '?' . $bits['query']; 00893 } 00894 if ( isset( $bits['fragment'] ) ) { 00895 $index .= '#' . $bits['fragment']; 00896 } 00897 00898 if ( $prot == '' ) { 00899 return array( "http:$index", "https:$index" ); 00900 } else { 00901 return array( $index ); 00902 } 00903 } 00904 00911 function wfMatchesDomainList( $url, $domains ) { 00912 $bits = wfParseUrl( $url ); 00913 if ( is_array( $bits ) && isset( $bits['host'] ) ) { 00914 foreach ( (array)$domains as $domain ) { 00915 // FIXME: This gives false positives. http://nds-nl.wikipedia.org will match nl.wikipedia.org 00916 // We should use something that interprets dots instead 00917 if ( substr( $bits['host'], -strlen( $domain ) ) === $domain ) { 00918 return true; 00919 } 00920 } 00921 } 00922 return false; 00923 } 00924 00938 function wfDebug( $text, $logonly = false ) { 00939 global $wgDebugLogFile, $wgProfileOnly, $wgDebugRawPage, $wgDebugLogPrefix; 00940 00941 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) { 00942 return; 00943 } 00944 00945 $timer = wfDebugTimer(); 00946 if ( $timer !== '' ) { 00947 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 ); 00948 } 00949 00950 if ( !$logonly ) { 00951 MWDebug::debugMsg( $text ); 00952 } 00953 00954 if ( wfRunHooks( 'Debug', array( $text, null /* no log group */ ) ) ) { 00955 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) { 00956 # Strip unprintables; they can switch terminal modes when binary data 00957 # gets dumped, which is pretty annoying. 00958 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text ); 00959 $text = $wgDebugLogPrefix . $text; 00960 wfErrorLog( $text, $wgDebugLogFile ); 00961 } 00962 } 00963 } 00964 00969 function wfIsDebugRawPage() { 00970 static $cache; 00971 if ( $cache !== null ) { 00972 return $cache; 00973 } 00974 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet 00975 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' ) 00976 || ( 00977 isset( $_SERVER['SCRIPT_NAME'] ) 00978 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php' 00979 ) ) 00980 { 00981 $cache = true; 00982 } else { 00983 $cache = false; 00984 } 00985 return $cache; 00986 } 00987 00993 function wfDebugTimer() { 00994 global $wgDebugTimestamps, $wgRequestTime; 00995 00996 if ( !$wgDebugTimestamps ) { 00997 return ''; 00998 } 00999 01000 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime ); 01001 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) ); 01002 return "$prefix $mem "; 01003 } 01004 01010 function wfDebugMem( $exact = false ) { 01011 $mem = memory_get_usage(); 01012 if( !$exact ) { 01013 $mem = floor( $mem / 1024 ) . ' kilobytes'; 01014 } else { 01015 $mem .= ' bytes'; 01016 } 01017 wfDebug( "Memory usage: $mem\n" ); 01018 } 01019 01029 function wfDebugLog( $logGroup, $text, $public = true ) { 01030 global $wgDebugLogGroups; 01031 $text = trim( $text ) . "\n"; 01032 if( isset( $wgDebugLogGroups[$logGroup] ) ) { 01033 $time = wfTimestamp( TS_DB ); 01034 $wiki = wfWikiID(); 01035 $host = wfHostname(); 01036 if ( wfRunHooks( 'Debug', array( $text, $logGroup ) ) ) { 01037 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] ); 01038 } 01039 } elseif ( $public === true ) { 01040 wfDebug( "[$logGroup] $text", true ); 01041 } 01042 } 01043 01049 function wfLogDBError( $text ) { 01050 global $wgDBerrorLog, $wgDBerrorLogTZ; 01051 static $logDBErrorTimeZoneObject = null; 01052 01053 if ( $wgDBerrorLog ) { 01054 $host = wfHostname(); 01055 $wiki = wfWikiID(); 01056 01057 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) { 01058 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ ); 01059 } 01060 01061 // Workaround for https://bugs.php.net/bug.php?id=52063 01062 // Can be removed when min PHP > 5.3.2 01063 if ( $logDBErrorTimeZoneObject === null ) { 01064 $d = date_create( "now" ); 01065 } else { 01066 $d = date_create( "now", $logDBErrorTimeZoneObject ); 01067 } 01068 01069 $date = $d->format( 'D M j G:i:s T Y' ); 01070 01071 $text = "$date\t$host\t$wiki\t$text"; 01072 wfErrorLog( $text, $wgDBerrorLog ); 01073 } 01074 } 01075 01088 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) { 01089 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 ); 01090 } 01091 01102 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) { 01103 MWDebug::warning( $msg, $callerOffset + 1, $level ); 01104 } 01105 01116 function wfErrorLog( $text, $file ) { 01117 if ( substr( $file, 0, 4 ) == 'udp:' ) { 01118 # Needs the sockets extension 01119 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) { 01120 // IPv6 bracketed host 01121 $host = $m[2]; 01122 $port = intval( $m[3] ); 01123 $prefix = isset( $m[4] ) ? $m[4] : false; 01124 $domain = AF_INET6; 01125 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) { 01126 $host = $m[2]; 01127 if ( !IP::isIPv4( $host ) ) { 01128 $host = gethostbyname( $host ); 01129 } 01130 $port = intval( $m[3] ); 01131 $prefix = isset( $m[4] ) ? $m[4] : false; 01132 $domain = AF_INET; 01133 } else { 01134 throw new MWException( __METHOD__ . ': Invalid UDP specification' ); 01135 } 01136 01137 // Clean it up for the multiplexer 01138 if ( strval( $prefix ) !== '' ) { 01139 $text = preg_replace( '/^/m', $prefix . ' ', $text ); 01140 01141 // Limit to 64KB 01142 if ( strlen( $text ) > 65506 ) { 01143 $text = substr( $text, 0, 65506 ); 01144 } 01145 01146 if ( substr( $text, -1 ) != "\n" ) { 01147 $text .= "\n"; 01148 } 01149 } elseif ( strlen( $text ) > 65507 ) { 01150 $text = substr( $text, 0, 65507 ); 01151 } 01152 01153 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP ); 01154 if ( !$sock ) { 01155 return; 01156 } 01157 01158 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port ); 01159 socket_close( $sock ); 01160 } else { 01161 wfSuppressWarnings(); 01162 $exists = file_exists( $file ); 01163 $size = $exists ? filesize( $file ) : false; 01164 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) { 01165 file_put_contents( $file, $text, FILE_APPEND ); 01166 } 01167 wfRestoreWarnings(); 01168 } 01169 } 01170 01174 function wfLogProfilingData() { 01175 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest; 01176 global $wgProfileLimit, $wgUser; 01177 01178 $profiler = Profiler::instance(); 01179 01180 # Profiling must actually be enabled... 01181 if ( $profiler->isStub() ) { 01182 return; 01183 } 01184 01185 // Get total page request time and only show pages that longer than 01186 // $wgProfileLimit time (default is 0) 01187 $elapsed = microtime( true ) - $wgRequestTime; 01188 if ( $elapsed <= $wgProfileLimit ) { 01189 return; 01190 } 01191 01192 $profiler->logData(); 01193 01194 // Check whether this should be logged in the debug file. 01195 if ( $wgDebugLogFile == '' || ( !$wgDebugRawPage && wfIsDebugRawPage() ) ) { 01196 return; 01197 } 01198 01199 $forward = ''; 01200 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { 01201 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR']; 01202 } 01203 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { 01204 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP']; 01205 } 01206 if ( !empty( $_SERVER['HTTP_FROM'] ) ) { 01207 $forward .= ' from ' . $_SERVER['HTTP_FROM']; 01208 } 01209 if ( $forward ) { 01210 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})"; 01211 } 01212 // Don't load $wgUser at this late stage just for statistics purposes 01213 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId() 01214 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) { 01215 $forward .= ' anon'; 01216 } 01217 01218 // Command line script uses a FauxRequest object which does not have 01219 // any knowledge about an URL and throw an exception instead. 01220 try { 01221 $requestUrl = $wgRequest->getRequestURL(); 01222 } catch ( MWException $e ) { 01223 $requestUrl = 'n/a'; 01224 } 01225 01226 $log = sprintf( "%s\t%04.3f\t%s\n", 01227 gmdate( 'YmdHis' ), $elapsed, 01228 urldecode( $requestUrl . $forward ) ); 01229 01230 wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile ); 01231 } 01232 01239 function wfIncrStats( $key, $count = 1 ) { 01240 global $wgStatsMethod; 01241 01242 $count = intval( $count ); 01243 01244 if( $wgStatsMethod == 'udp' ) { 01245 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID; 01246 static $socket; 01247 01248 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname; 01249 01250 if ( !$socket ) { 01251 $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP ); 01252 $statline = "stats/{$id} - 1 1 1 1 1 -total\n"; 01253 socket_sendto( 01254 $socket, 01255 $statline, 01256 strlen( $statline ), 01257 0, 01258 $wgUDPProfilerHost, 01259 $wgUDPProfilerPort 01260 ); 01261 } 01262 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n"; 01263 wfSuppressWarnings(); 01264 socket_sendto( 01265 $socket, 01266 $statline, 01267 strlen( $statline ), 01268 0, 01269 $wgUDPProfilerHost, 01270 $wgUDPProfilerPort 01271 ); 01272 wfRestoreWarnings(); 01273 } elseif( $wgStatsMethod == 'cache' ) { 01274 global $wgMemc; 01275 $key = wfMemcKey( 'stats', $key ); 01276 if ( is_null( $wgMemc->incr( $key, $count ) ) ) { 01277 $wgMemc->add( $key, $count ); 01278 } 01279 } else { 01280 // Disabled 01281 } 01282 } 01283 01291 function wfReadOnly() { 01292 global $wgReadOnlyFile, $wgReadOnly; 01293 01294 if ( !is_null( $wgReadOnly ) ) { 01295 return (bool)$wgReadOnly; 01296 } 01297 if ( $wgReadOnlyFile == '' ) { 01298 return false; 01299 } 01300 // Set $wgReadOnly for faster access next time 01301 if ( is_file( $wgReadOnlyFile ) ) { 01302 $wgReadOnly = file_get_contents( $wgReadOnlyFile ); 01303 } else { 01304 $wgReadOnly = false; 01305 } 01306 return (bool)$wgReadOnly; 01307 } 01308 01312 function wfReadOnlyReason() { 01313 global $wgReadOnly; 01314 wfReadOnly(); 01315 return $wgReadOnly; 01316 } 01317 01333 function wfGetLangObj( $langcode = false ) { 01334 # Identify which language to get or create a language object for. 01335 # Using is_object here due to Stub objects. 01336 if( is_object( $langcode ) ) { 01337 # Great, we already have the object (hopefully)! 01338 return $langcode; 01339 } 01340 01341 global $wgContLang, $wgLanguageCode; 01342 if( $langcode === true || $langcode === $wgLanguageCode ) { 01343 # $langcode is the language code of the wikis content language object. 01344 # or it is a boolean and value is true 01345 return $wgContLang; 01346 } 01347 01348 global $wgLang; 01349 if( $langcode === false || $langcode === $wgLang->getCode() ) { 01350 # $langcode is the language code of user language object. 01351 # or it was a boolean and value is false 01352 return $wgLang; 01353 } 01354 01355 $validCodes = array_keys( Language::fetchLanguageNames() ); 01356 if( in_array( $langcode, $validCodes ) ) { 01357 # $langcode corresponds to a valid language. 01358 return Language::factory( $langcode ); 01359 } 01360 01361 # $langcode is a string, but not a valid language code; use content language. 01362 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" ); 01363 return $wgContLang; 01364 } 01365 01373 function wfUILang() { 01374 wfDeprecated( __METHOD__, '1.18' ); 01375 global $wgLang; 01376 return $wgLang; 01377 } 01378 01388 function wfMessage( $key /*...*/) { 01389 $params = func_get_args(); 01390 array_shift( $params ); 01391 if ( isset( $params[0] ) && is_array( $params[0] ) ) { 01392 $params = $params[0]; 01393 } 01394 return new Message( $key, $params ); 01395 } 01396 01405 function wfMessageFallback( /*...*/ ) { 01406 $args = func_get_args(); 01407 return MWFunction::callArray( 'Message::newFallbackSequence', $args ); 01408 } 01409 01429 function wfMsg( $key ) { 01430 wfDeprecated( __METHOD__, '1.21' ); 01431 01432 $args = func_get_args(); 01433 array_shift( $args ); 01434 return wfMsgReal( $key, $args ); 01435 } 01436 01445 function wfMsgNoTrans( $key ) { 01446 wfDeprecated( __METHOD__, '1.21' ); 01447 01448 $args = func_get_args(); 01449 array_shift( $args ); 01450 return wfMsgReal( $key, $args, true, false, false ); 01451 } 01452 01478 function wfMsgForContent( $key ) { 01479 wfDeprecated( __METHOD__, '1.21' ); 01480 01481 global $wgForceUIMsgAsContentMsg; 01482 $args = func_get_args(); 01483 array_shift( $args ); 01484 $forcontent = true; 01485 if( is_array( $wgForceUIMsgAsContentMsg ) && 01486 in_array( $key, $wgForceUIMsgAsContentMsg ) ) 01487 { 01488 $forcontent = false; 01489 } 01490 return wfMsgReal( $key, $args, true, $forcontent ); 01491 } 01492 01501 function wfMsgForContentNoTrans( $key ) { 01502 wfDeprecated( __METHOD__, '1.21' ); 01503 01504 global $wgForceUIMsgAsContentMsg; 01505 $args = func_get_args(); 01506 array_shift( $args ); 01507 $forcontent = true; 01508 if( is_array( $wgForceUIMsgAsContentMsg ) && 01509 in_array( $key, $wgForceUIMsgAsContentMsg ) ) 01510 { 01511 $forcontent = false; 01512 } 01513 return wfMsgReal( $key, $args, true, $forcontent, false ); 01514 } 01515 01528 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) { 01529 wfDeprecated( __METHOD__, '1.21' ); 01530 01531 wfProfileIn( __METHOD__ ); 01532 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform ); 01533 $message = wfMsgReplaceArgs( $message, $args ); 01534 wfProfileOut( __METHOD__ ); 01535 return $message; 01536 } 01537 01550 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) { 01551 wfDeprecated( __METHOD__, '1.21' ); 01552 01553 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) ); 01554 01555 $cache = MessageCache::singleton(); 01556 $message = $cache->get( $key, $useDB, $langCode ); 01557 if( $message === false ) { 01558 $message = '<' . htmlspecialchars( $key ) . '>'; 01559 } elseif ( $transform ) { 01560 $message = $cache->transform( $message ); 01561 } 01562 return $message; 01563 } 01564 01573 function wfMsgReplaceArgs( $message, $args ) { 01574 # Fix windows line-endings 01575 # Some messages are split with explode("\n", $msg) 01576 $message = str_replace( "\r", '', $message ); 01577 01578 // Replace arguments 01579 if ( count( $args ) ) { 01580 if ( is_array( $args[0] ) ) { 01581 $args = array_values( $args[0] ); 01582 } 01583 $replacementKeys = array(); 01584 foreach( $args as $n => $param ) { 01585 $replacementKeys['$' . ( $n + 1 )] = $param; 01586 } 01587 $message = strtr( $message, $replacementKeys ); 01588 } 01589 01590 return $message; 01591 } 01592 01606 function wfMsgHtml( $key ) { 01607 wfDeprecated( __METHOD__, '1.21' ); 01608 01609 $args = func_get_args(); 01610 array_shift( $args ); 01611 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args ); 01612 } 01613 01627 function wfMsgWikiHtml( $key ) { 01628 wfDeprecated( __METHOD__, '1.21' ); 01629 01630 $args = func_get_args(); 01631 array_shift( $args ); 01632 return wfMsgReplaceArgs( 01633 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null, 01634 /* can't be set to false */ true, /* interface */ true )->getText(), 01635 $args ); 01636 } 01637 01660 function wfMsgExt( $key, $options ) { 01661 wfDeprecated( __METHOD__, '1.21' ); 01662 01663 $args = func_get_args(); 01664 array_shift( $args ); 01665 array_shift( $args ); 01666 $options = (array)$options; 01667 01668 foreach( $options as $arrayKey => $option ) { 01669 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) { 01670 # An unknown index, neither numeric nor "language" 01671 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING ); 01672 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option, 01673 array( 'parse', 'parseinline', 'escape', 'escapenoentities', 01674 'replaceafter', 'parsemag', 'content' ) ) ) { 01675 # A numeric index with unknown value 01676 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING ); 01677 } 01678 } 01679 01680 if( in_array( 'content', $options, true ) ) { 01681 $forContent = true; 01682 $langCode = true; 01683 $langCodeObj = null; 01684 } elseif( array_key_exists( 'language', $options ) ) { 01685 $forContent = false; 01686 $langCode = wfGetLangObj( $options['language'] ); 01687 $langCodeObj = $langCode; 01688 } else { 01689 $forContent = false; 01690 $langCode = false; 01691 $langCodeObj = null; 01692 } 01693 01694 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false ); 01695 01696 if( !in_array( 'replaceafter', $options, true ) ) { 01697 $string = wfMsgReplaceArgs( $string, $args ); 01698 } 01699 01700 $messageCache = MessageCache::singleton(); 01701 $parseInline = in_array( 'parseinline', $options, true ); 01702 if( in_array( 'parse', $options, true ) || $parseInline ) { 01703 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj ); 01704 if ( $string instanceof ParserOutput ) { 01705 $string = $string->getText(); 01706 } 01707 01708 if ( $parseInline ) { 01709 $m = array(); 01710 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) { 01711 $string = $m[1]; 01712 } 01713 } 01714 } elseif ( in_array( 'parsemag', $options, true ) ) { 01715 $string = $messageCache->transform( $string, 01716 !$forContent, $langCodeObj ); 01717 } 01718 01719 if ( in_array( 'escape', $options, true ) ) { 01720 $string = htmlspecialchars ( $string ); 01721 } elseif ( in_array( 'escapenoentities', $options, true ) ) { 01722 $string = Sanitizer::escapeHtmlAllowEntities( $string ); 01723 } 01724 01725 if( in_array( 'replaceafter', $options, true ) ) { 01726 $string = wfMsgReplaceArgs( $string, $args ); 01727 } 01728 01729 return $string; 01730 } 01731 01742 function wfEmptyMsg( $key ) { 01743 wfDeprecated( __METHOD__, '1.21' ); 01744 01745 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false; 01746 } 01747 01755 function wfDebugDieBacktrace( $msg = '' ) { 01756 throw new MWException( $msg ); 01757 } 01758 01766 function wfHostname() { 01767 static $host; 01768 if ( is_null( $host ) ) { 01769 01770 # Hostname overriding 01771 global $wgOverrideHostname; 01772 if( $wgOverrideHostname !== false ) { 01773 # Set static and skip any detection 01774 $host = $wgOverrideHostname; 01775 return $host; 01776 } 01777 01778 if ( function_exists( 'posix_uname' ) ) { 01779 // This function not present on Windows 01780 $uname = posix_uname(); 01781 } else { 01782 $uname = false; 01783 } 01784 if( is_array( $uname ) && isset( $uname['nodename'] ) ) { 01785 $host = $uname['nodename']; 01786 } elseif ( getenv( 'COMPUTERNAME' ) ) { 01787 # Windows computer name 01788 $host = getenv( 'COMPUTERNAME' ); 01789 } else { 01790 # This may be a virtual server. 01791 $host = $_SERVER['SERVER_NAME']; 01792 } 01793 } 01794 return $host; 01795 } 01796 01803 function wfReportTime() { 01804 global $wgRequestTime, $wgShowHostnames; 01805 01806 $elapsed = microtime( true ) - $wgRequestTime; 01807 01808 return $wgShowHostnames 01809 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed ) 01810 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed ); 01811 } 01812 01828 function wfDebugBacktrace( $limit = 0 ) { 01829 static $disabled = null; 01830 01831 if( extension_loaded( 'Zend Optimizer' ) ) { 01832 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" ); 01833 return array(); 01834 } 01835 01836 if ( is_null( $disabled ) ) { 01837 $disabled = false; 01838 $functions = explode( ',', ini_get( 'disable_functions' ) ); 01839 $functions = array_map( 'trim', $functions ); 01840 $functions = array_map( 'strtolower', $functions ); 01841 if ( in_array( 'debug_backtrace', $functions ) ) { 01842 wfDebug( "debug_backtrace is in disabled_functions\n" ); 01843 $disabled = true; 01844 } 01845 } 01846 if ( $disabled ) { 01847 return array(); 01848 } 01849 01850 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) { 01851 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 ); 01852 } else { 01853 return array_slice( debug_backtrace(), 1 ); 01854 } 01855 } 01856 01862 function wfBacktrace() { 01863 global $wgCommandLineMode; 01864 01865 if ( $wgCommandLineMode ) { 01866 $msg = ''; 01867 } else { 01868 $msg = "<ul>\n"; 01869 } 01870 $backtrace = wfDebugBacktrace(); 01871 foreach( $backtrace as $call ) { 01872 if( isset( $call['file'] ) ) { 01873 $f = explode( DIRECTORY_SEPARATOR, $call['file'] ); 01874 $file = $f[count( $f ) - 1]; 01875 } else { 01876 $file = '-'; 01877 } 01878 if( isset( $call['line'] ) ) { 01879 $line = $call['line']; 01880 } else { 01881 $line = '-'; 01882 } 01883 if ( $wgCommandLineMode ) { 01884 $msg .= "$file line $line calls "; 01885 } else { 01886 $msg .= '<li>' . $file . ' line ' . $line . ' calls '; 01887 } 01888 if( !empty( $call['class'] ) ) { 01889 $msg .= $call['class'] . $call['type']; 01890 } 01891 $msg .= $call['function'] . '()'; 01892 01893 if ( $wgCommandLineMode ) { 01894 $msg .= "\n"; 01895 } else { 01896 $msg .= "</li>\n"; 01897 } 01898 } 01899 if ( $wgCommandLineMode ) { 01900 $msg .= "\n"; 01901 } else { 01902 $msg .= "</ul>\n"; 01903 } 01904 01905 return $msg; 01906 } 01907 01917 function wfGetCaller( $level = 2 ) { 01918 $backtrace = wfDebugBacktrace( $level + 1 ); 01919 if ( isset( $backtrace[$level] ) ) { 01920 return wfFormatStackFrame( $backtrace[$level] ); 01921 } else { 01922 return 'unknown'; 01923 } 01924 } 01925 01934 function wfGetAllCallers( $limit = 3 ) { 01935 $trace = array_reverse( wfDebugBacktrace() ); 01936 if ( !$limit || $limit > count( $trace ) - 1 ) { 01937 $limit = count( $trace ) - 1; 01938 } 01939 $trace = array_slice( $trace, -$limit - 1, $limit ); 01940 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) ); 01941 } 01942 01949 function wfFormatStackFrame( $frame ) { 01950 return isset( $frame['class'] ) ? 01951 $frame['class'] . '::' . $frame['function'] : 01952 $frame['function']; 01953 } 01954 01955 01956 /* Some generic result counters, pulled out of SearchEngine */ 01957 01958 01966 function wfShowingResults( $offset, $limit ) { 01967 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse(); 01968 } 01969 01981 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) { 01982 wfDeprecated( __METHOD__, '1.19' ); 01983 01984 global $wgLang; 01985 01986 $query = wfCgiToArray( $query ); 01987 01988 if( is_object( $link ) ) { 01989 $title = $link; 01990 } else { 01991 $title = Title::newFromText( $link ); 01992 if( is_null( $title ) ) { 01993 return false; 01994 } 01995 } 01996 01997 return $wgLang->viewPrevNext( $title, $offset, $limit, $query, $atend ); 01998 } 01999 02010 function wfSpecialList( $page, $details, $oppositedm = true ) { 02011 wfDeprecated( __METHOD__, '1.19' ); 02012 02013 global $wgLang; 02014 return $wgLang->specialList( $page, $details, $oppositedm ); 02015 } 02016 02024 function wfClientAcceptsGzip( $force = false ) { 02025 static $result = null; 02026 if ( $result === null || $force ) { 02027 $result = false; 02028 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) { 02029 # @todo FIXME: We may want to blacklist some broken browsers 02030 $m = array(); 02031 if( preg_match( 02032 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/', 02033 $_SERVER['HTTP_ACCEPT_ENCODING'], 02034 $m ) 02035 ) 02036 { 02037 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) { 02038 $result = false; 02039 return $result; 02040 } 02041 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" ); 02042 $result = true; 02043 } 02044 } 02045 } 02046 return $result; 02047 } 02048 02058 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) { 02059 global $wgRequest; 02060 return $wgRequest->getLimitOffset( $deflimit, $optionname ); 02061 } 02062 02072 function wfEscapeWikiText( $text ) { 02073 $text = strtr( "\n$text", array( 02074 '"' => '"', '&' => '&', "'" => ''', '<' => '<', 02075 '=' => '=', '>' => '>', '[' => '[', ']' => ']', 02076 '{' => '{', '|' => '|', '}' => '}', 02077 "\n#" => "\n#", "\n*" => "\n*", 02078 "\n:" => "\n:", "\n;" => "\n;", 02079 '://' => '://', 'ISBN ' => 'ISBN ', 'RFC ' => 'RFC ', 02080 ) ); 02081 return substr( $text, 1 ); 02082 } 02083 02088 function wfTime() { 02089 return microtime( true ); 02090 } 02091 02102 function wfSetVar( &$dest, $source, $force = false ) { 02103 $temp = $dest; 02104 if ( !is_null( $source ) || $force ) { 02105 $dest = $source; 02106 } 02107 return $temp; 02108 } 02109 02119 function wfSetBit( &$dest, $bit, $state = true ) { 02120 $temp = (bool)( $dest & $bit ); 02121 if ( !is_null( $state ) ) { 02122 if ( $state ) { 02123 $dest |= $bit; 02124 } else { 02125 $dest &= ~$bit; 02126 } 02127 } 02128 return $temp; 02129 } 02130 02137 function wfVarDump( $var ) { 02138 global $wgOut; 02139 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" ); 02140 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) { 02141 print $s; 02142 } else { 02143 $wgOut->addHTML( $s ); 02144 } 02145 } 02146 02154 function wfHttpError( $code, $label, $desc ) { 02155 global $wgOut; 02156 $wgOut->disable(); 02157 header( "HTTP/1.0 $code $label" ); 02158 header( "Status: $code $label" ); 02159 $wgOut->sendCacheControl(); 02160 02161 header( 'Content-type: text/html; charset=utf-8' ); 02162 print "<!doctype html>" . 02163 '<html><head><title>' . 02164 htmlspecialchars( $label ) . 02165 '</title></head><body><h1>' . 02166 htmlspecialchars( $label ) . 02167 '</h1><p>' . 02168 nl2br( htmlspecialchars( $desc ) ) . 02169 "</p></body></html>\n"; 02170 } 02171 02189 function wfResetOutputBuffers( $resetGzipEncoding = true ) { 02190 if( $resetGzipEncoding ) { 02191 // Suppress Content-Encoding and Content-Length 02192 // headers from 1.10+s wfOutputHandler 02193 global $wgDisableOutputCompression; 02194 $wgDisableOutputCompression = true; 02195 } 02196 while( $status = ob_get_status() ) { 02197 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) { 02198 // Probably from zlib.output_compression or other 02199 // PHP-internal setting which can't be removed. 02200 // 02201 // Give up, and hope the result doesn't break 02202 // output behavior. 02203 break; 02204 } 02205 if( !ob_end_clean() ) { 02206 // Could not remove output buffer handler; abort now 02207 // to avoid getting in some kind of infinite loop. 02208 break; 02209 } 02210 if( $resetGzipEncoding ) { 02211 if( $status['name'] == 'ob_gzhandler' ) { 02212 // Reset the 'Content-Encoding' field set by this handler 02213 // so we can start fresh. 02214 header_remove( 'Content-Encoding' ); 02215 break; 02216 } 02217 } 02218 } 02219 } 02220 02233 function wfClearOutputBuffers() { 02234 wfResetOutputBuffers( false ); 02235 } 02236 02245 function wfAcceptToPrefs( $accept, $def = '*/*' ) { 02246 # No arg means accept anything (per HTTP spec) 02247 if( !$accept ) { 02248 return array( $def => 1.0 ); 02249 } 02250 02251 $prefs = array(); 02252 02253 $parts = explode( ',', $accept ); 02254 02255 foreach( $parts as $part ) { 02256 # @todo FIXME: Doesn't deal with params like 'text/html; level=1' 02257 $values = explode( ';', trim( $part ) ); 02258 $match = array(); 02259 if ( count( $values ) == 1 ) { 02260 $prefs[$values[0]] = 1.0; 02261 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) { 02262 $prefs[$values[0]] = floatval( $match[1] ); 02263 } 02264 } 02265 02266 return $prefs; 02267 } 02268 02281 function mimeTypeMatch( $type, $avail ) { 02282 if( array_key_exists( $type, $avail ) ) { 02283 return $type; 02284 } else { 02285 $parts = explode( '/', $type ); 02286 if( array_key_exists( $parts[0] . '/*', $avail ) ) { 02287 return $parts[0] . '/*'; 02288 } elseif( array_key_exists( '*/*', $avail ) ) { 02289 return '*/*'; 02290 } else { 02291 return null; 02292 } 02293 } 02294 } 02295 02309 function wfNegotiateType( $cprefs, $sprefs ) { 02310 $combine = array(); 02311 02312 foreach( array_keys( $sprefs ) as $type ) { 02313 $parts = explode( '/', $type ); 02314 if( $parts[1] != '*' ) { 02315 $ckey = mimeTypeMatch( $type, $cprefs ); 02316 if( $ckey ) { 02317 $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; 02318 } 02319 } 02320 } 02321 02322 foreach( array_keys( $cprefs ) as $type ) { 02323 $parts = explode( '/', $type ); 02324 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) { 02325 $skey = mimeTypeMatch( $type, $sprefs ); 02326 if( $skey ) { 02327 $combine[$type] = $sprefs[$skey] * $cprefs[$type]; 02328 } 02329 } 02330 } 02331 02332 $bestq = 0; 02333 $besttype = null; 02334 02335 foreach( array_keys( $combine ) as $type ) { 02336 if( $combine[$type] > $bestq ) { 02337 $besttype = $type; 02338 $bestq = $combine[$type]; 02339 } 02340 } 02341 02342 return $besttype; 02343 } 02344 02350 function wfSuppressWarnings( $end = false ) { 02351 static $suppressCount = 0; 02352 static $originalLevel = false; 02353 02354 if ( $end ) { 02355 if ( $suppressCount ) { 02356 --$suppressCount; 02357 if ( !$suppressCount ) { 02358 error_reporting( $originalLevel ); 02359 } 02360 } 02361 } else { 02362 if ( !$suppressCount ) { 02363 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED ) ); 02364 } 02365 ++$suppressCount; 02366 } 02367 } 02368 02372 function wfRestoreWarnings() { 02373 wfSuppressWarnings( true ); 02374 } 02375 02376 # Autodetect, convert and provide timestamps of various types 02377 02381 define( 'TS_UNIX', 0 ); 02382 02386 define( 'TS_MW', 1 ); 02387 02391 define( 'TS_DB', 2 ); 02392 02396 define( 'TS_RFC2822', 3 ); 02397 02403 define( 'TS_ISO_8601', 4 ); 02404 02412 define( 'TS_EXIF', 5 ); 02413 02417 define( 'TS_ORACLE', 6 ); 02418 02422 define( 'TS_POSTGRES', 7 ); 02423 02427 define( 'TS_DB2', 8 ); 02428 02432 define( 'TS_ISO_8601_BASIC', 9 ); 02433 02443 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) { 02444 try { 02445 $timestamp = new MWTimestamp( $ts ); 02446 return $timestamp->getTimestamp( $outputtype ); 02447 } catch( TimestampException $e ) { 02448 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n"); 02449 return false; 02450 } 02451 } 02452 02461 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) { 02462 if( is_null( $ts ) ) { 02463 return null; 02464 } else { 02465 return wfTimestamp( $outputtype, $ts ); 02466 } 02467 } 02468 02474 function wfTimestampNow() { 02475 # return NOW 02476 return wfTimestamp( TS_MW, time() ); 02477 } 02478 02484 function wfIsWindows() { 02485 static $isWindows = null; 02486 if ( $isWindows === null ) { 02487 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows'; 02488 } 02489 return $isWindows; 02490 } 02491 02497 function wfIsHipHop() { 02498 return function_exists( 'hphp_thread_set_warmup_enabled' ); 02499 } 02500 02507 function swap( &$x, &$y ) { 02508 $z = $x; 02509 $x = $y; 02510 $y = $z; 02511 } 02512 02524 function wfTempDir() { 02525 global $wgTmpDirectory; 02526 02527 if ( $wgTmpDirectory !== false ) { 02528 return $wgTmpDirectory; 02529 } 02530 02531 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) ); 02532 02533 foreach( $tmpDir as $tmp ) { 02534 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) { 02535 return $tmp; 02536 } 02537 } 02538 return sys_get_temp_dir(); 02539 } 02540 02550 function wfMkdirParents( $dir, $mode = null, $caller = null ) { 02551 global $wgDirectoryMode; 02552 02553 if ( FileBackend::isStoragePath( $dir ) ) { // sanity 02554 throw new MWException( __FUNCTION__ . " given storage path '$dir'." ); 02555 } 02556 02557 if ( !is_null( $caller ) ) { 02558 wfDebug( "$caller: called wfMkdirParents($dir)\n" ); 02559 } 02560 02561 if( strval( $dir ) === '' || file_exists( $dir ) ) { 02562 return true; 02563 } 02564 02565 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir ); 02566 02567 if ( is_null( $mode ) ) { 02568 $mode = $wgDirectoryMode; 02569 } 02570 02571 // Turn off the normal warning, we're doing our own below 02572 wfSuppressWarnings(); 02573 $ok = mkdir( $dir, $mode, true ); // PHP5 <3 02574 wfRestoreWarnings(); 02575 02576 if( !$ok ) { 02577 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis. 02578 trigger_error( sprintf( "%s: failed to mkdir \"%s\" mode 0%o", __FUNCTION__, $dir, $mode ), 02579 E_USER_WARNING ); 02580 } 02581 return $ok; 02582 } 02583 02588 function wfRecursiveRemoveDir( $dir ) { 02589 wfDebug( __FUNCTION__ . "( $dir )\n" ); 02590 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622 02591 if ( is_dir( $dir ) ) { 02592 $objects = scandir( $dir ); 02593 foreach ( $objects as $object ) { 02594 if ( $object != "." && $object != ".." ) { 02595 if ( filetype( $dir . '/' . $object ) == "dir" ) { 02596 wfRecursiveRemoveDir( $dir . '/' . $object ); 02597 } else { 02598 unlink( $dir . '/' . $object ); 02599 } 02600 } 02601 } 02602 reset( $objects ); 02603 rmdir( $dir ); 02604 } 02605 } 02606 02613 function wfPercent( $nr, $acc = 2, $round = true ) { 02614 $ret = sprintf( "%.${acc}f", $nr ); 02615 return $round ? round( $ret, $acc ) . '%' : "$ret%"; 02616 } 02617 02626 function in_string( $needle, $str, $insensitive = false ) { 02627 $func = 'strpos'; 02628 if( $insensitive ) $func = 'stripos'; 02629 02630 return $func( $str, $needle ) !== false; 02631 } 02632 02656 function wfIniGetBool( $setting ) { 02657 $val = ini_get( $setting ); 02658 // 'on' and 'true' can't have whitespace around them, but '1' can. 02659 return strtolower( $val ) == 'on' 02660 || strtolower( $val ) == 'true' 02661 || strtolower( $val ) == 'yes' 02662 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function 02663 } 02664 02674 function wfDl( $extension, $fileName = null ) { 02675 if( extension_loaded( $extension ) ) { 02676 return true; 02677 } 02678 02679 $canDl = false; 02680 $sapi = php_sapi_name(); 02681 if( $sapi == 'cli' || $sapi == 'cgi' || $sapi == 'embed' ) { 02682 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' ) 02683 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) ); 02684 } 02685 02686 if( $canDl ) { 02687 $fileName = $fileName ? $fileName : $extension; 02688 if( wfIsWindows() ) { 02689 $fileName = 'php_' . $fileName; 02690 } 02691 wfSuppressWarnings(); 02692 dl( $fileName . '.' . PHP_SHLIB_SUFFIX ); 02693 wfRestoreWarnings(); 02694 } 02695 return extension_loaded( $extension ); 02696 } 02697 02709 function wfEscapeShellArg( ) { 02710 wfInitShellLocale(); 02711 02712 $args = func_get_args(); 02713 $first = true; 02714 $retVal = ''; 02715 foreach ( $args as $arg ) { 02716 if ( !$first ) { 02717 $retVal .= ' '; 02718 } else { 02719 $first = false; 02720 } 02721 02722 if ( wfIsWindows() ) { 02723 // Escaping for an MSVC-style command line parser and CMD.EXE 02724 // Refs: 02725 // * https://waybackassets.bk21.net/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html 02726 // * http://technet.microsoft.com/en-us/library/cc723564.aspx 02727 // * Bug #13518 02728 // * CR r63214 02729 // Double the backslashes before any double quotes. Escape the double quotes. 02730 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE ); 02731 $arg = ''; 02732 $iteration = 0; 02733 foreach ( $tokens as $token ) { 02734 if ( $iteration % 2 == 1 ) { 02735 // Delimiter, a double quote preceded by zero or more slashes 02736 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"'; 02737 } elseif ( $iteration % 4 == 2 ) { 02738 // ^ in $token will be outside quotes, need to be escaped 02739 $arg .= str_replace( '^', '^^', $token ); 02740 } else { // $iteration % 4 == 0 02741 // ^ in $token will appear inside double quotes, so leave as is 02742 $arg .= $token; 02743 } 02744 $iteration++; 02745 } 02746 // Double the backslashes before the end of the string, because 02747 // we will soon add a quote 02748 $m = array(); 02749 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) { 02750 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] ); 02751 } 02752 02753 // Add surrounding quotes 02754 $retVal .= '"' . $arg . '"'; 02755 } else { 02756 $retVal .= escapeshellarg( $arg ); 02757 } 02758 } 02759 return $retVal; 02760 } 02761 02774 function wfShellExec( $cmd, &$retval = null, $environ = array(), $limits = array() ) { 02775 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime; 02776 02777 static $disabled; 02778 if ( is_null( $disabled ) ) { 02779 $disabled = false; 02780 if( wfIniGetBool( 'safe_mode' ) ) { 02781 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" ); 02782 $disabled = 'safemode'; 02783 } else { 02784 $functions = explode( ',', ini_get( 'disable_functions' ) ); 02785 $functions = array_map( 'trim', $functions ); 02786 $functions = array_map( 'strtolower', $functions ); 02787 if ( in_array( 'passthru', $functions ) ) { 02788 wfDebug( "passthru is in disabled_functions\n" ); 02789 $disabled = 'passthru'; 02790 } 02791 } 02792 } 02793 if ( $disabled ) { 02794 $retval = 1; 02795 return $disabled == 'safemode' ? 02796 'Unable to run external programs in safe mode.' : 02797 'Unable to run external programs, passthru() is disabled.'; 02798 } 02799 02800 wfInitShellLocale(); 02801 02802 $envcmd = ''; 02803 foreach( $environ as $k => $v ) { 02804 if ( wfIsWindows() ) { 02805 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves 02806 * appear in the environment variable, so we must use carat escaping as documented in 02807 * http://technet.microsoft.com/en-us/library/cc723564.aspx 02808 * Note however that the quote isn't listed there, but is needed, and the parentheses 02809 * are listed there but doesn't appear to need it. 02810 */ 02811 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& '; 02812 } else { 02813 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command 02814 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01 02815 */ 02816 $envcmd .= "$k=" . escapeshellarg( $v ) . ' '; 02817 } 02818 } 02819 $cmd = $envcmd . $cmd; 02820 02821 if ( php_uname( 's' ) == 'Linux' ) { 02822 $time = intval ( isset($limits['time']) ? $limits['time'] : $wgMaxShellTime ); 02823 $mem = intval ( isset($limits['memory']) ? $limits['memory'] : $wgMaxShellMemory ); 02824 $filesize = intval ( isset($limits['filesize']) ? $limits['filesize'] : $wgMaxShellFileSize ); 02825 02826 if ( $time > 0 && $mem > 0 ) { 02827 $script = "$IP/bin/ulimit4.sh"; 02828 if ( is_executable( $script ) ) { 02829 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd ); 02830 } 02831 } 02832 } 02833 wfDebug( "wfShellExec: $cmd\n" ); 02834 02835 $retval = 1; // error by default? 02836 ob_start(); 02837 passthru( $cmd, $retval ); 02838 $output = ob_get_contents(); 02839 ob_end_clean(); 02840 02841 if ( $retval == 127 ) { 02842 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" ); 02843 } 02844 return $output; 02845 } 02846 02851 function wfInitShellLocale() { 02852 static $done = false; 02853 if ( $done ) { 02854 return; 02855 } 02856 $done = true; 02857 global $wgShellLocale; 02858 if ( !wfIniGetBool( 'safe_mode' ) ) { 02859 putenv( "LC_CTYPE=$wgShellLocale" ); 02860 setlocale( LC_CTYPE, $wgShellLocale ); 02861 } 02862 } 02863 02868 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) { 02869 return wfShellWikiCmd( $script, $parameters, $options ); 02870 } 02871 02883 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) { 02884 global $wgPhpCli; 02885 // Give site config file a chance to run the script in a wrapper. 02886 // The caller may likely want to call wfBasename() on $script. 02887 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) ); 02888 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli ); 02889 if ( isset( $options['wrapper'] ) ) { 02890 $cmd[] = $options['wrapper']; 02891 } 02892 $cmd[] = $script; 02893 // Escape each parameter for shell 02894 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) ); 02895 } 02896 02907 function wfMerge( $old, $mine, $yours, &$result ) { 02908 global $wgDiff3; 02909 02910 # This check may also protect against code injection in 02911 # case of broken installations. 02912 wfSuppressWarnings(); 02913 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 ); 02914 wfRestoreWarnings(); 02915 02916 if( !$haveDiff3 ) { 02917 wfDebug( "diff3 not found\n" ); 02918 return false; 02919 } 02920 02921 # Make temporary files 02922 $td = wfTempDir(); 02923 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' ); 02924 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' ); 02925 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' ); 02926 02927 # NOTE: diff3 issues a warning to stderr if any of the files does not end with 02928 # a newline character. To avoid this, we normalize the trailing whitespace before 02929 # creating the diff. 02930 02931 fwrite( $oldtextFile, rtrim( $old ) . "\n" ); 02932 fclose( $oldtextFile ); 02933 fwrite( $mytextFile, rtrim( $mine ) . "\n" ); 02934 fclose( $mytextFile ); 02935 fwrite( $yourtextFile, rtrim( $yours ) . "\n" ); 02936 fclose( $yourtextFile ); 02937 02938 # Check for a conflict 02939 $cmd = $wgDiff3 . ' -a --overlap-only ' . 02940 wfEscapeShellArg( $mytextName ) . ' ' . 02941 wfEscapeShellArg( $oldtextName ) . ' ' . 02942 wfEscapeShellArg( $yourtextName ); 02943 $handle = popen( $cmd, 'r' ); 02944 02945 if( fgets( $handle, 1024 ) ) { 02946 $conflict = true; 02947 } else { 02948 $conflict = false; 02949 } 02950 pclose( $handle ); 02951 02952 # Merge differences 02953 $cmd = $wgDiff3 . ' -a -e --merge ' . 02954 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName ); 02955 $handle = popen( $cmd, 'r' ); 02956 $result = ''; 02957 do { 02958 $data = fread( $handle, 8192 ); 02959 if ( strlen( $data ) == 0 ) { 02960 break; 02961 } 02962 $result .= $data; 02963 } while ( true ); 02964 pclose( $handle ); 02965 unlink( $mytextName ); 02966 unlink( $oldtextName ); 02967 unlink( $yourtextName ); 02968 02969 if ( $result === '' && $old !== '' && !$conflict ) { 02970 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" ); 02971 $conflict = true; 02972 } 02973 return !$conflict; 02974 } 02975 02985 function wfDiff( $before, $after, $params = '-u' ) { 02986 if ( $before == $after ) { 02987 return ''; 02988 } 02989 02990 global $wgDiff; 02991 wfSuppressWarnings(); 02992 $haveDiff = $wgDiff && file_exists( $wgDiff ); 02993 wfRestoreWarnings(); 02994 02995 # This check may also protect against code injection in 02996 # case of broken installations. 02997 if( !$haveDiff ) { 02998 wfDebug( "diff executable not found\n" ); 02999 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) ); 03000 $format = new UnifiedDiffFormatter(); 03001 return $format->format( $diffs ); 03002 } 03003 03004 # Make temporary files 03005 $td = wfTempDir(); 03006 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' ); 03007 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' ); 03008 03009 fwrite( $oldtextFile, $before ); 03010 fclose( $oldtextFile ); 03011 fwrite( $newtextFile, $after ); 03012 fclose( $newtextFile ); 03013 03014 // Get the diff of the two files 03015 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName ); 03016 03017 $h = popen( $cmd, 'r' ); 03018 03019 $diff = ''; 03020 03021 do { 03022 $data = fread( $h, 8192 ); 03023 if ( strlen( $data ) == 0 ) { 03024 break; 03025 } 03026 $diff .= $data; 03027 } while ( true ); 03028 03029 // Clean up 03030 pclose( $h ); 03031 unlink( $oldtextName ); 03032 unlink( $newtextName ); 03033 03034 // Kill the --- and +++ lines. They're not useful. 03035 $diff_lines = explode( "\n", $diff ); 03036 if ( strpos( $diff_lines[0], '---' ) === 0 ) { 03037 unset( $diff_lines[0] ); 03038 } 03039 if ( strpos( $diff_lines[1], '+++' ) === 0 ) { 03040 unset( $diff_lines[1] ); 03041 } 03042 03043 $diff = implode( "\n", $diff_lines ); 03044 03045 return $diff; 03046 } 03047 03064 function wfUsePHP( $req_ver ) { 03065 $php_ver = PHP_VERSION; 03066 03067 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) { 03068 throw new MWException( "PHP $req_ver required--this is only $php_ver" ); 03069 } 03070 } 03071 03086 function wfUseMW( $req_ver ) { 03087 global $wgVersion; 03088 03089 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) { 03090 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" ); 03091 } 03092 } 03093 03106 function wfBaseName( $path, $suffix = '' ) { 03107 $encSuffix = ( $suffix == '' ) 03108 ? '' 03109 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' ); 03110 $matches = array(); 03111 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) { 03112 return $matches[1]; 03113 } else { 03114 return ''; 03115 } 03116 } 03117 03127 function wfRelativePath( $path, $from ) { 03128 // Normalize mixed input on Windows... 03129 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path ); 03130 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from ); 03131 03132 // Trim trailing slashes -- fix for drive root 03133 $path = rtrim( $path, DIRECTORY_SEPARATOR ); 03134 $from = rtrim( $from, DIRECTORY_SEPARATOR ); 03135 03136 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) ); 03137 $against = explode( DIRECTORY_SEPARATOR, $from ); 03138 03139 if( $pieces[0] !== $against[0] ) { 03140 // Non-matching Windows drive letters? 03141 // Return a full path. 03142 return $path; 03143 } 03144 03145 // Trim off common prefix 03146 while( count( $pieces ) && count( $against ) 03147 && $pieces[0] == $against[0] ) { 03148 array_shift( $pieces ); 03149 array_shift( $against ); 03150 } 03151 03152 // relative dots to bump us to the parent 03153 while( count( $against ) ) { 03154 array_unshift( $pieces, '..' ); 03155 array_shift( $against ); 03156 } 03157 03158 array_push( $pieces, wfBaseName( $path ) ); 03159 03160 return implode( DIRECTORY_SEPARATOR, $pieces ); 03161 } 03162 03170 function wfDoUpdates( $commit = '' ) { 03171 wfDeprecated( __METHOD__, '1.19' ); 03172 DeferredUpdates::doUpdates( $commit ); 03173 } 03174 03189 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) { 03190 $input = strval( $input ); 03191 if( $sourceBase < 2 || 03192 $sourceBase > 36 || 03193 $destBase < 2 || 03194 $destBase > 36 || 03195 $pad < 1 || 03196 $sourceBase != intval( $sourceBase ) || 03197 $destBase != intval( $destBase ) || 03198 $pad != intval( $pad ) || 03199 !is_string( $input ) || 03200 $input == '' ) { 03201 return false; 03202 } 03203 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 03204 $inDigits = array(); 03205 $outChars = ''; 03206 03207 // Decode and validate input string 03208 $input = strtolower( $input ); 03209 for( $i = 0; $i < strlen( $input ); $i++ ) { 03210 $n = strpos( $digitChars, $input[$i] ); 03211 if( $n === false || $n > $sourceBase ) { 03212 return false; 03213 } 03214 $inDigits[] = $n; 03215 } 03216 03217 // Iterate over the input, modulo-ing out an output digit 03218 // at a time until input is gone. 03219 while( count( $inDigits ) ) { 03220 $work = 0; 03221 $workDigits = array(); 03222 03223 // Long division... 03224 foreach( $inDigits as $digit ) { 03225 $work *= $sourceBase; 03226 $work += $digit; 03227 03228 if( $work < $destBase ) { 03229 // Gonna need to pull another digit. 03230 if( count( $workDigits ) ) { 03231 // Avoid zero-padding; this lets us find 03232 // the end of the input very easily when 03233 // length drops to zero. 03234 $workDigits[] = 0; 03235 } 03236 } else { 03237 // Finally! Actual division! 03238 $workDigits[] = intval( $work / $destBase ); 03239 03240 // Isn't it annoying that most programming languages 03241 // don't have a single divide-and-remainder operator, 03242 // even though the CPU implements it that way? 03243 $work = $work % $destBase; 03244 } 03245 } 03246 03247 // All that division leaves us with a remainder, 03248 // which is conveniently our next output digit. 03249 $outChars .= $digitChars[$work]; 03250 03251 // And we continue! 03252 $inDigits = $workDigits; 03253 } 03254 03255 while( strlen( $outChars ) < $pad ) { 03256 $outChars .= '0'; 03257 } 03258 03259 return strrev( $outChars ); 03260 } 03261 03270 function wfCreateObject( $name, $p ) { 03271 wfDeprecated( __FUNCTION__, '1.18' ); 03272 return MWFunction::newObj( $name, $p ); 03273 } 03274 03278 function wfHttpOnlySafe() { 03279 global $wgHttpOnlyBlacklist; 03280 03281 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { 03282 foreach( $wgHttpOnlyBlacklist as $regex ) { 03283 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) { 03284 return false; 03285 } 03286 } 03287 } 03288 03289 return true; 03290 } 03291 03296 function wfCheckEntropy() { 03297 return ( 03298 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) ) 03299 || ini_get( 'session.entropy_file' ) 03300 ) 03301 && intval( ini_get( 'session.entropy_length' ) ) >= 32; 03302 } 03303 03308 function wfFixSessionID() { 03309 // If the cookie or session id is already set we already have a session and should abort 03310 if ( isset( $_COOKIE[ session_name() ] ) || session_id() ) { 03311 return; 03312 } 03313 03314 // PHP's built-in session entropy is enabled if: 03315 // - entropy_file is set or you're on Windows with php 5.3.3+ 03316 // - AND entropy_length is > 0 03317 // We treat it as disabled if it doesn't have an entropy length of at least 32 03318 $entropyEnabled = wfCheckEntropy(); 03319 03320 // If built-in entropy is not enabled or not sufficient override php's built in session id generation code 03321 if ( !$entropyEnabled ) { 03322 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, overriding session id generation using our cryptrand source.\n" ); 03323 session_id( MWCryptRand::generateHex( 32 ) ); 03324 } 03325 } 03326 03332 function wfSetupSession( $sessionId = false ) { 03333 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain, 03334 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler; 03335 if( $wgSessionsInObjectCache || $wgSessionsInMemcached ) { 03336 ObjectCacheSessionHandler::install(); 03337 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) { 03338 # Only set this if $wgSessionHandler isn't null and session.save_handler 03339 # hasn't already been set to the desired value (that causes errors) 03340 ini_set( 'session.save_handler', $wgSessionHandler ); 03341 } 03342 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly; 03343 wfDebugLog( 'cookie', 03344 'session_set_cookie_params: "' . implode( '", "', 03345 array( 03346 0, 03347 $wgCookiePath, 03348 $wgCookieDomain, 03349 $wgCookieSecure, 03350 $httpOnlySafe ) ) . '"' ); 03351 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe ); 03352 session_cache_limiter( 'private, must-revalidate' ); 03353 if ( $sessionId ) { 03354 session_id( $sessionId ); 03355 } else { 03356 wfFixSessionID(); 03357 } 03358 wfSuppressWarnings(); 03359 session_start(); 03360 wfRestoreWarnings(); 03361 } 03362 03369 function wfGetPrecompiledData( $name ) { 03370 global $IP; 03371 03372 $file = "$IP/serialized/$name"; 03373 if ( file_exists( $file ) ) { 03374 $blob = file_get_contents( $file ); 03375 if ( $blob ) { 03376 return unserialize( $blob ); 03377 } 03378 } 03379 return false; 03380 } 03381 03388 function wfMemcKey( /*... */ ) { 03389 global $wgCachePrefix; 03390 $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix; 03391 $args = func_get_args(); 03392 $key = $prefix . ':' . implode( ':', $args ); 03393 $key = str_replace( ' ', '_', $key ); 03394 return $key; 03395 } 03396 03405 function wfForeignMemcKey( $db, $prefix /*, ... */ ) { 03406 $args = array_slice( func_get_args(), 2 ); 03407 if ( $prefix ) { 03408 $key = "$db-$prefix:" . implode( ':', $args ); 03409 } else { 03410 $key = $db . ':' . implode( ':', $args ); 03411 } 03412 return $key; 03413 } 03414 03421 function wfWikiID() { 03422 global $wgDBprefix, $wgDBname; 03423 if ( $wgDBprefix ) { 03424 return "$wgDBname-$wgDBprefix"; 03425 } else { 03426 return $wgDBname; 03427 } 03428 } 03429 03437 function wfSplitWikiID( $wiki ) { 03438 $bits = explode( '-', $wiki, 2 ); 03439 if ( count( $bits ) < 2 ) { 03440 $bits[] = ''; 03441 } 03442 return $bits; 03443 } 03444 03467 function &wfGetDB( $db, $groups = array(), $wiki = false ) { 03468 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki ); 03469 } 03470 03477 function wfGetLB( $wiki = false ) { 03478 return wfGetLBFactory()->getMainLB( $wiki ); 03479 } 03480 03486 function &wfGetLBFactory() { 03487 return LBFactory::singleton(); 03488 } 03489 03510 function wfFindFile( $title, $options = array() ) { 03511 return RepoGroup::singleton()->findFile( $title, $options ); 03512 } 03513 03521 function wfLocalFile( $title ) { 03522 return RepoGroup::singleton()->getLocalRepo()->newFile( $title ); 03523 } 03524 03529 function wfStreamFile( $fname, $headers = array() ) { 03530 wfDeprecated( __FUNCTION__, '1.19' ); 03531 StreamFile::stream( $fname, $headers ); 03532 } 03533 03540 function wfQueriesMustScale() { 03541 global $wgMiserMode; 03542 return $wgMiserMode 03543 || ( SiteStats::pages() > 100000 03544 && SiteStats::edits() > 1000000 03545 && SiteStats::users() > 10000 ); 03546 } 03547 03556 function wfScript( $script = 'index' ) { 03557 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript; 03558 if ( $script === 'index' ) { 03559 return $wgScript; 03560 } else if ( $script === 'load' ) { 03561 return $wgLoadScript; 03562 } else { 03563 return "{$wgScriptPath}/{$script}{$wgScriptExtension}"; 03564 } 03565 } 03566 03572 function wfGetScriptUrl() { 03573 if( isset( $_SERVER['SCRIPT_NAME'] ) ) { 03574 # 03575 # as it was called, minus the query string. 03576 # 03577 # Some sites use Apache rewrite rules to handle subdomains, 03578 # and have PHP set up in a weird way that causes PHP_SELF 03579 # to contain the rewritten URL instead of the one that the 03580 # outside world sees. 03581 # 03582 # If in this mode, use SCRIPT_URL instead, which mod_rewrite 03583 # provides containing the "before" URL. 03584 return $_SERVER['SCRIPT_NAME']; 03585 } else { 03586 return $_SERVER['URL']; 03587 } 03588 } 03589 03597 function wfBoolToStr( $value ) { 03598 return $value ? 'true' : 'false'; 03599 } 03600 03606 function wfGetNull() { 03607 return wfIsWindows() 03608 ? 'NUL' 03609 : '/dev/null'; 03610 } 03611 03622 function wfWaitForSlaves( $maxLag = false, $wiki = false ) { 03623 $lb = wfGetLB( $wiki ); 03624 // bug 27975 - Don't try to wait for slaves if there are none 03625 // Prevents permission error when getting master position 03626 if ( $lb->getServerCount() > 1 ) { 03627 $dbw = $lb->getConnection( DB_MASTER ); 03628 $pos = $dbw->getMasterPos(); 03629 $lb->waitForAll( $pos ); 03630 } 03631 } 03632 03637 function wfOut( $s ) { 03638 wfDeprecated( __FUNCTION__, '1.18' ); 03639 global $wgCommandLineMode; 03640 if ( $wgCommandLineMode ) { 03641 echo $s; 03642 } else { 03643 echo htmlspecialchars( $s ); 03644 } 03645 flush(); 03646 } 03647 03654 function wfCountDown( $n ) { 03655 for ( $i = $n; $i >= 0; $i-- ) { 03656 if ( $i != $n ) { 03657 echo str_repeat( "\x08", strlen( $i + 1 ) ); 03658 } 03659 echo $i; 03660 flush(); 03661 if ( $i ) { 03662 sleep( 1 ); 03663 } 03664 } 03665 echo "\n"; 03666 } 03667 03677 function wfGenerateToken( $salt = '' ) { 03678 wfDeprecated( __METHOD__, '1.20' ); 03679 $salt = serialize( $salt ); 03680 return md5( mt_rand( 0, 0x7fffffff ) . $salt ); 03681 } 03682 03691 function wfStripIllegalFilenameChars( $name ) { 03692 global $wgIllegalFileChars; 03693 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : ''; 03694 $name = wfBaseName( $name ); 03695 $name = preg_replace( 03696 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/", 03697 '-', 03698 $name 03699 ); 03700 return $name; 03701 } 03702 03708 function wfMemoryLimit() { 03709 global $wgMemoryLimit; 03710 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) ); 03711 if( $memlimit != -1 ) { 03712 $conflimit = wfShorthandToInteger( $wgMemoryLimit ); 03713 if( $conflimit == -1 ) { 03714 wfDebug( "Removing PHP's memory limit\n" ); 03715 wfSuppressWarnings(); 03716 ini_set( 'memory_limit', $conflimit ); 03717 wfRestoreWarnings(); 03718 return $conflimit; 03719 } elseif ( $conflimit > $memlimit ) { 03720 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" ); 03721 wfSuppressWarnings(); 03722 ini_set( 'memory_limit', $conflimit ); 03723 wfRestoreWarnings(); 03724 return $conflimit; 03725 } 03726 } 03727 return $memlimit; 03728 } 03729 03736 function wfShorthandToInteger( $string = '' ) { 03737 $string = trim( $string ); 03738 if( $string === '' ) { 03739 return -1; 03740 } 03741 $last = $string[strlen( $string ) - 1]; 03742 $val = intval( $string ); 03743 switch( $last ) { 03744 case 'g': 03745 case 'G': 03746 $val *= 1024; 03747 // break intentionally missing 03748 case 'm': 03749 case 'M': 03750 $val *= 1024; 03751 // break intentionally missing 03752 case 'k': 03753 case 'K': 03754 $val *= 1024; 03755 } 03756 03757 return $val; 03758 } 03759 03767 function wfBCP47( $code ) { 03768 $codeSegment = explode( '-', $code ); 03769 $codeBCP = array(); 03770 foreach ( $codeSegment as $segNo => $seg ) { 03771 if ( count( $codeSegment ) > 0 ) { 03772 // when previous segment is x, it is a private segment and should be lc 03773 if( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) { 03774 $codeBCP[$segNo] = strtolower( $seg ); 03775 // ISO 3166 country code 03776 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) { 03777 $codeBCP[$segNo] = strtoupper( $seg ); 03778 // ISO 15924 script code 03779 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) { 03780 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) ); 03781 // Use lowercase for other cases 03782 } else { 03783 $codeBCP[$segNo] = strtolower( $seg ); 03784 } 03785 } else { 03786 // Use lowercase for single segment 03787 $codeBCP[$segNo] = strtolower( $seg ); 03788 } 03789 } 03790 $langCode = implode( '-', $codeBCP ); 03791 return $langCode; 03792 } 03793 03800 function wfGetCache( $inputType ) { 03801 return ObjectCache::getInstance( $inputType ); 03802 } 03803 03809 function wfGetMainCache() { 03810 global $wgMainCacheType; 03811 return ObjectCache::getInstance( $wgMainCacheType ); 03812 } 03813 03819 function wfGetMessageCacheStorage() { 03820 global $wgMessageCacheType; 03821 return ObjectCache::getInstance( $wgMessageCacheType ); 03822 } 03823 03829 function wfGetParserCacheStorage() { 03830 global $wgParserCacheType; 03831 return ObjectCache::getInstance( $wgParserCacheType ); 03832 } 03833 03839 function wfGetLangConverterCacheStorage() { 03840 global $wgLanguageConverterCacheType; 03841 return ObjectCache::getInstance( $wgLanguageConverterCacheType ); 03842 } 03843 03851 function wfRunHooks( $event, $args = array() ) { 03852 return Hooks::run( $event, $args ); 03853 } 03854 03869 function wfUnpack( $format, $data, $length=false ) { 03870 if ( $length !== false ) { 03871 $realLen = strlen( $data ); 03872 if ( $realLen < $length ) { 03873 throw new MWException( "Tried to use wfUnpack on a " 03874 . "string of length $realLen, but needed one " 03875 . "of at least length $length." 03876 ); 03877 } 03878 } 03879 03880 wfSuppressWarnings(); 03881 $result = unpack( $format, $data ); 03882 wfRestoreWarnings(); 03883 03884 if ( $result === false ) { 03885 // If it cannot extract the packed data. 03886 throw new MWException( "unpack could not unpack binary data" ); 03887 } 03888 return $result; 03889 } 03890 03905 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) { 03906 static $badImageCache = null; // based on bad_image_list msg 03907 wfProfileIn( __METHOD__ ); 03908 03909 # Handle redirects 03910 $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) ); 03911 if( $redirectTitle ) { 03912 $name = $redirectTitle->getDbKey(); 03913 } 03914 03915 # Run the extension hook 03916 $bad = false; 03917 if( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) { 03918 wfProfileOut( __METHOD__ ); 03919 return $bad; 03920 } 03921 03922 $cacheable = ( $blacklist === null ); 03923 if( $cacheable && $badImageCache !== null ) { 03924 $badImages = $badImageCache; 03925 } else { // cache miss 03926 if ( $blacklist === null ) { 03927 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list 03928 } 03929 # Build the list now 03930 $badImages = array(); 03931 $lines = explode( "\n", $blacklist ); 03932 foreach( $lines as $line ) { 03933 # List items only 03934 if ( substr( $line, 0, 1 ) !== '*' ) { 03935 continue; 03936 } 03937 03938 # Find all links 03939 $m = array(); 03940 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) { 03941 continue; 03942 } 03943 03944 $exceptions = array(); 03945 $imageDBkey = false; 03946 foreach ( $m[1] as $i => $titleText ) { 03947 $title = Title::newFromText( $titleText ); 03948 if ( !is_null( $title ) ) { 03949 if ( $i == 0 ) { 03950 $imageDBkey = $title->getDBkey(); 03951 } else { 03952 $exceptions[$title->getPrefixedDBkey()] = true; 03953 } 03954 } 03955 } 03956 03957 if ( $imageDBkey !== false ) { 03958 $badImages[$imageDBkey] = $exceptions; 03959 } 03960 } 03961 if ( $cacheable ) { 03962 $badImageCache = $badImages; 03963 } 03964 } 03965 03966 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false; 03967 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] ); 03968 wfProfileOut( __METHOD__ ); 03969 return $bad; 03970 }