MediaWiki  REL1_20
GlobalFunctions.php
Go to the documentation of this file.
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 
00173 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
00174         if ( is_null( $changed ) ) {
00175                 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
00176         }
00177         if ( $default[$key] !== $value ) {
00178                 $changed[$key] = $value;
00179         }
00180 }
00181 
00190 function wfArrayMerge( $array1/* ... */ ) {
00191         $args = func_get_args();
00192         $args = array_reverse( $args, true );
00193         $out = array();
00194         foreach ( $args as $arg ) {
00195                 $out += $arg;
00196         }
00197         return $out;
00198 }
00199 
00218 function wfMergeErrorArrays( /*...*/ ) {
00219         $args = func_get_args();
00220         $out = array();
00221         foreach ( $args as $errors ) {
00222                 foreach ( $errors as $params ) {
00223                         # @todo FIXME: Sometimes get nested arrays for $params,
00224                         # which leads to E_NOTICEs
00225                         $spec = implode( "\t", $params );
00226                         $out[$spec] = $params;
00227                 }
00228         }
00229         return array_values( $out );
00230 }
00231 
00240 function wfArrayInsertAfter( array $array, array $insert, $after ) {
00241         // Find the offset of the element to insert after.
00242         $keys = array_keys( $array );
00243         $offsetByKey = array_flip( $keys );
00244 
00245         $offset = $offsetByKey[$after];
00246 
00247         // Insert at the specified offset
00248         $before = array_slice( $array, 0, $offset + 1, true );
00249         $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
00250 
00251         $output = $before + $insert + $after;
00252 
00253         return $output;
00254 }
00255 
00263 function wfObjectToArray( $objOrArray, $recursive = true ) {
00264         $array = array();
00265         if( is_object( $objOrArray ) ) {
00266                 $objOrArray = get_object_vars( $objOrArray );
00267         }
00268         foreach ( $objOrArray as $key => $value ) {
00269                 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
00270                         $value = wfObjectToArray( $value );
00271                 }
00272 
00273                 $array[$key] = $value;
00274         }
00275 
00276         return $array;
00277 }
00278 
00286 function wfArrayMap( $function, $input ) {
00287         $ret = array_map( $function, $input );
00288         foreach ( $ret as $key => $value ) {
00289                 $taint = istainted( $input[$key] );
00290                 if ( $taint ) {
00291                         taint( $ret[$key], $taint );
00292                 }
00293         }
00294         return $ret;
00295 }
00296 
00304 function wfRandom() {
00305         # The maximum random value is "only" 2^31-1, so get two random
00306         # values to reduce the chance of dupes
00307         $max = mt_getrandmax() + 1;
00308         $rand = number_format( ( mt_rand() * $max + mt_rand() )
00309                 / $max / $max, 12, '.', '' );
00310         return $rand;
00311 }
00312 
00323 function wfRandomString( $length = 32 ) {
00324         $str = '';
00325         while ( strlen( $str ) < $length ) {
00326                 $str .= dechex( mt_rand() );
00327         }
00328         return substr( $str, 0, $length );
00329 }
00330 
00353 function wfUrlencode( $s ) {
00354         static $needle;
00355         if ( is_null( $s ) ) {
00356                 $needle = null;
00357                 return '';
00358         }
00359 
00360         if ( is_null( $needle ) ) {
00361                 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
00362                 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
00363                         $needle[] = '%3A';
00364                 }
00365         }
00366 
00367         $s = urlencode( $s );
00368         $s = str_ireplace(
00369                 $needle,
00370                 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
00371                 $s
00372         );
00373 
00374         return $s;
00375 }
00376 
00387 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
00388         if ( !is_null( $array2 ) ) {
00389                 $array1 = $array1 + $array2;
00390         }
00391 
00392         $cgi = '';
00393         foreach ( $array1 as $key => $value ) {
00394                 if ( !is_null($value) && $value !== false ) {
00395                         if ( $cgi != '' ) {
00396                                 $cgi .= '&';
00397                         }
00398                         if ( $prefix !== '' ) {
00399                                 $key = $prefix . "[$key]";
00400                         }
00401                         if ( is_array( $value ) ) {
00402                                 $firstTime = true;
00403                                 foreach ( $value as $k => $v ) {
00404                                         $cgi .= $firstTime ? '' : '&';
00405                                         if ( is_array( $v ) ) {
00406                                                 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
00407                                         } else {
00408                                                 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
00409                                         }
00410                                         $firstTime = false;
00411                                 }
00412                         } else {
00413                                 if ( is_object( $value ) ) {
00414                                         $value = $value->__toString();
00415                                 }
00416                                 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
00417                         }
00418                 }
00419         }
00420         return $cgi;
00421 }
00422 
00432 function wfCgiToArray( $query ) {
00433         if ( isset( $query[0] ) && $query[0] == '?' ) {
00434                 $query = substr( $query, 1 );
00435         }
00436         $bits = explode( '&', $query );
00437         $ret = array();
00438         foreach ( $bits as $bit ) {
00439                 if ( $bit === '' ) {
00440                         continue;
00441                 }
00442                 if ( strpos( $bit, '=' ) === false ) {
00443                         // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
00444                         $key = $bit;
00445                         $value = '';
00446                 } else {
00447                         list( $key, $value ) = explode( '=', $bit );
00448                 }
00449                 $key = urldecode( $key );
00450                 $value = urldecode( $value );
00451                 if ( strpos( $key, '[' ) !== false ) {
00452                         $keys = array_reverse( explode( '[', $key ) );
00453                         $key = array_pop( $keys );
00454                         $temp = $value;
00455                         foreach ( $keys as $k ) {
00456                                 $k = substr( $k, 0, -1 );
00457                                 $temp = array( $k => $temp );
00458                         }
00459                         if ( isset( $ret[$key] ) ) {
00460                                 $ret[$key] = array_merge( $ret[$key], $temp );
00461                         } else {
00462                                 $ret[$key] = $temp;
00463                         }
00464                 } else {
00465                         $ret[$key] = $value;
00466                 }
00467         }
00468         return $ret;
00469 }
00470 
00479 function wfAppendQuery( $url, $query ) {
00480         if ( is_array( $query ) ) {
00481                 $query = wfArrayToCgi( $query );
00482         }
00483         if( $query != '' ) {
00484                 if( false === strpos( $url, '?' ) ) {
00485                         $url .= '?';
00486                 } else {
00487                         $url .= '&';
00488                 }
00489                 $url .= $query;
00490         }
00491         return $url;
00492 }
00493 
00516 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
00517         global $wgServer, $wgCanonicalServer, $wgInternalServer;
00518         $serverUrl = $wgServer;
00519         if ( $defaultProto === PROTO_CANONICAL ) {
00520                 $serverUrl = $wgCanonicalServer;
00521         }
00522         // Make $wgInternalServer fall back to $wgServer if not set
00523         if ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
00524                 $serverUrl = $wgInternalServer;
00525         }
00526         if ( $defaultProto === PROTO_CURRENT ) {
00527                 $defaultProto = WebRequest::detectProtocol() . '://';
00528         }
00529 
00530         // Analyze $serverUrl to obtain its protocol
00531         $bits = wfParseUrl( $serverUrl );
00532         $serverHasProto = $bits && $bits['scheme'] != '';
00533 
00534         if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
00535                 if ( $serverHasProto ) {
00536                         $defaultProto = $bits['scheme'] . '://';
00537                 } else {
00538                         // $wgCanonicalServer or $wgInternalServer doesn't have a protocol. This really isn't supposed to happen
00539                         // Fall back to HTTP in this ridiculous case
00540                         $defaultProto = PROTO_HTTP;
00541                 }
00542         }
00543 
00544         $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
00545 
00546         if ( substr( $url, 0, 2 ) == '//' ) {
00547                 $url = $defaultProtoWithoutSlashes . $url;
00548         } elseif ( substr( $url, 0, 1 ) == '/' ) {
00549                 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes, otherwise leave it alone
00550                 $url = ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
00551         }
00552 
00553         $bits = wfParseUrl( $url );
00554         if ( $bits && isset( $bits['path'] ) ) {
00555                 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
00556                 return wfAssembleUrl( $bits );
00557         } elseif ( $bits ) {
00558                 # No path to expand
00559                 return $url;
00560         } elseif ( substr( $url, 0, 1 ) != '/' ) {
00561                 # URL is a relative path
00562                 return wfRemoveDotSegments( $url );
00563         }
00564 
00565         # Expanded URL is not valid.
00566         return false;
00567 }
00568 
00582 function wfAssembleUrl( $urlParts ) {
00583         $result = '';
00584 
00585         if ( isset( $urlParts['delimiter'] ) ) {
00586                 if ( isset( $urlParts['scheme'] ) ) {
00587                         $result .= $urlParts['scheme'];
00588                 }
00589 
00590                 $result .= $urlParts['delimiter'];
00591         }
00592 
00593         if ( isset( $urlParts['host'] ) ) {
00594                 if ( isset( $urlParts['user'] ) ) {
00595                         $result .= $urlParts['user'];
00596                         if ( isset( $urlParts['pass'] ) ) {
00597                                 $result .= ':' . $urlParts['pass'];
00598                         }
00599                         $result .= '@';
00600                 }
00601 
00602                 $result .= $urlParts['host'];
00603 
00604                 if ( isset( $urlParts['port'] ) ) {
00605                         $result .= ':' . $urlParts['port'];
00606                 }
00607         }
00608 
00609         if ( isset( $urlParts['path'] ) ) {
00610                 $result .= $urlParts['path'];
00611         }
00612 
00613         if ( isset( $urlParts['query'] ) ) {
00614                 $result .= '?' . $urlParts['query'];
00615         }
00616 
00617         if ( isset( $urlParts['fragment'] ) ) {
00618                 $result .= '#' . $urlParts['fragment'];
00619         }
00620 
00621         return $result;
00622 }
00623 
00634 function wfRemoveDotSegments( $urlPath ) {
00635         $output = '';
00636         $inputOffset = 0;
00637         $inputLength = strlen( $urlPath );
00638 
00639         while ( $inputOffset < $inputLength ) {
00640                 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
00641                 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
00642                 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
00643                 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
00644                 $trimOutput = false;
00645 
00646                 if ( $prefixLengthTwo == './' ) {
00647                         # Step A, remove leading "./"
00648                         $inputOffset += 2;
00649                 } elseif ( $prefixLengthThree == '../' ) {
00650                         # Step A, remove leading "../"
00651                         $inputOffset += 3;
00652                 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
00653                         # Step B, replace leading "/.$" with "/"
00654                         $inputOffset += 1;
00655                         $urlPath[$inputOffset] = '/';
00656                 } elseif ( $prefixLengthThree == '/./' ) {
00657                         # Step B, replace leading "/./" with "/"
00658                         $inputOffset += 2;
00659                 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
00660                         # Step C, replace leading "/..$" with "/" and
00661                         # remove last path component in output
00662                         $inputOffset += 2;
00663                         $urlPath[$inputOffset] = '/';
00664                         $trimOutput = true;
00665                 } elseif ( $prefixLengthFour == '/../' ) {
00666                         # Step C, replace leading "/../" with "/" and
00667                         # remove last path component in output
00668                         $inputOffset += 3;
00669                         $trimOutput = true;
00670                 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
00671                         # Step D, remove "^.$"
00672                         $inputOffset += 1;
00673                 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
00674                         # Step D, remove "^..$"
00675                         $inputOffset += 2;
00676                 } else {
00677                         # Step E, move leading path segment to output
00678                         if ( $prefixLengthOne == '/' ) {
00679                                 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
00680                         } else {
00681                                 $slashPos = strpos( $urlPath, '/', $inputOffset );
00682                         }
00683                         if ( $slashPos === false ) {
00684                                 $output .= substr( $urlPath, $inputOffset );
00685                                 $inputOffset = $inputLength;
00686                         } else {
00687                                 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
00688                                 $inputOffset += $slashPos - $inputOffset;
00689                         }
00690                 }
00691 
00692                 if ( $trimOutput ) {
00693                         $slashPos = strrpos( $output, '/' );
00694                         if ( $slashPos === false ) {
00695                                 $output = '';
00696                         } else {
00697                                 $output = substr( $output, 0, $slashPos );
00698                         }
00699                 }
00700         }
00701 
00702         return $output;
00703 }
00704 
00712 function wfUrlProtocols( $includeProtocolRelative = true ) {
00713         global $wgUrlProtocols;
00714 
00715         // Cache return values separately based on $includeProtocolRelative
00716         static $withProtRel = null, $withoutProtRel = null;
00717         $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
00718         if ( !is_null( $cachedValue ) ) {
00719                 return $cachedValue;
00720         }
00721 
00722         // Support old-style $wgUrlProtocols strings, for backwards compatibility
00723         // with LocalSettings files from 1.5
00724         if ( is_array( $wgUrlProtocols ) ) {
00725                 $protocols = array();
00726                 foreach ( $wgUrlProtocols as $protocol ) {
00727                         // Filter out '//' if !$includeProtocolRelative
00728                         if ( $includeProtocolRelative || $protocol !== '//' ) {
00729                                 $protocols[] = preg_quote( $protocol, '/' );
00730                         }
00731                 }
00732 
00733                 $retval = implode( '|', $protocols );
00734         } else {
00735                 // Ignore $includeProtocolRelative in this case
00736                 // This case exists for pre-1.6 compatibility, and we can safely assume
00737                 // that '//' won't appear in a pre-1.6 config because protocol-relative
00738                 // URLs weren't supported until 1.18
00739                 $retval = $wgUrlProtocols;
00740         }
00741 
00742         // Cache return value
00743         if ( $includeProtocolRelative ) {
00744                 $withProtRel = $retval;
00745         } else {
00746                 $withoutProtRel = $retval;
00747         }
00748         return $retval;
00749 }
00750 
00757 function wfUrlProtocolsWithoutProtRel() {
00758         return wfUrlProtocols( false );
00759 }
00760 
00771 function wfParseUrl( $url ) {
00772         global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
00773 
00774         // Protocol-relative URLs are handled really badly by parse_url(). It's so bad that the easiest
00775         // way to handle them is to just prepend 'http:' and strip the protocol out later
00776         $wasRelative = substr( $url, 0, 2 ) == '//';
00777         if ( $wasRelative ) {
00778                 $url = "http:$url";
00779         }
00780         wfSuppressWarnings();
00781         $bits = parse_url( $url );
00782         wfRestoreWarnings();
00783         // parse_url() returns an array without scheme for some invalid URLs, e.g.
00784         // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
00785         if ( !$bits || !isset( $bits['scheme'] ) ) {
00786                 return false;
00787         }
00788 
00789         // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
00790         $bits['scheme'] = strtolower( $bits['scheme'] );
00791 
00792         // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
00793         if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
00794                 $bits['delimiter'] = '://';
00795         } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
00796                 $bits['delimiter'] = ':';
00797                 // parse_url detects for news: and mailto: the host part of an url as path
00798                 // We have to correct this wrong detection
00799                 if ( isset( $bits['path'] ) ) {
00800                         $bits['host'] = $bits['path'];
00801                         $bits['path'] = '';
00802                 }
00803         } else {
00804                 return false;
00805         }
00806 
00807         /* Provide an empty host for eg. file:/// urls (see bug 28627) */
00808         if ( !isset( $bits['host'] ) ) {
00809                 $bits['host'] = '';
00810 
00811                 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
00812                 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
00813                         $bits['path'] = '/' . $bits['path'];
00814                 }
00815         }
00816 
00817         // If the URL was protocol-relative, fix scheme and delimiter
00818         if ( $wasRelative ) {
00819                 $bits['scheme'] = '';
00820                 $bits['delimiter'] = '//';
00821         }
00822         return $bits;
00823 }
00824 
00835 function wfExpandIRI( $url ) {
00836         return preg_replace_callback( '/((?:%[89A-F][0-9A-F])+)/i', 'wfExpandIRI_callback', wfExpandUrl( $url ) );
00837 }
00838 
00844 function wfExpandIRI_callback( $matches ) {
00845         return urldecode( $matches[1] );
00846 }
00847 
00848 
00849 
00856 function wfMakeUrlIndexes( $url ) {
00857         $bits = wfParseUrl( $url );
00858 
00859         // Reverse the labels in the hostname, convert to lower case
00860         // For emails reverse domainpart only
00861         if ( $bits['scheme'] == 'mailto' ) {
00862                 $mailparts = explode( '@', $bits['host'], 2 );
00863                 if ( count( $mailparts ) === 2 ) {
00864                         $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
00865                 } else {
00866                         // No domain specified, don't mangle it
00867                         $domainpart = '';
00868                 }
00869                 $reversedHost = $domainpart . '@' . $mailparts[0];
00870         } else {
00871                 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
00872         }
00873         // Add an extra dot to the end
00874         // Why? Is it in wrong place in mailto links?
00875         if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
00876                 $reversedHost .= '.';
00877         }
00878         // Reconstruct the pseudo-URL
00879         $prot = $bits['scheme'];
00880         $index = $prot . $bits['delimiter'] . $reversedHost;
00881         // Leave out user and password. Add the port, path, query and fragment
00882         if ( isset( $bits['port'] ) ) {
00883                 $index .= ':' . $bits['port'];
00884         }
00885         if ( isset( $bits['path'] ) ) {
00886                 $index .= $bits['path'];
00887         } else {
00888                 $index .= '/';
00889         }
00890         if ( isset( $bits['query'] ) ) {
00891                 $index .= '?' . $bits['query'];
00892         }
00893         if ( isset( $bits['fragment'] ) ) {
00894                 $index .= '#' . $bits['fragment'];
00895         }
00896 
00897         if ( $prot == '' ) {
00898                 return array( "http:$index", "https:$index" );
00899         } else {
00900                 return array( $index );
00901         }
00902 }
00903 
00910 function wfMatchesDomainList( $url, $domains ) {
00911         $bits = wfParseUrl( $url );
00912         if ( is_array( $bits ) && isset( $bits['host'] ) ) {
00913                 foreach ( (array)$domains as $domain ) {
00914                         // FIXME: This gives false positives. http://nds-nl.wikipedia.org will match nl.wikipedia.org
00915                         // We should use something that interprets dots instead
00916                         if ( substr( $bits['host'], -strlen( $domain ) ) === $domain ) {
00917                                 return true;
00918                         }
00919                 }
00920         }
00921         return false;
00922 }
00923 
00937 function wfDebug( $text, $logonly = false ) {
00938         global $wgDebugLogFile, $wgProfileOnly, $wgDebugRawPage, $wgDebugLogPrefix;
00939 
00940         if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
00941                 return;
00942         }
00943 
00944         $timer = wfDebugTimer();
00945         if ( $timer !== '' ) {
00946                 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
00947         }
00948 
00949         if ( !$logonly ) {
00950                 MWDebug::debugMsg( $text );
00951         }
00952 
00953         if ( wfRunHooks( 'Debug', array( $text, null /* no log group */ ) ) ) {
00954                 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
00955                         # Strip unprintables; they can switch terminal modes when binary data
00956                         # gets dumped, which is pretty annoying.
00957                         $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
00958                         $text = $wgDebugLogPrefix . $text;
00959                         wfErrorLog( $text, $wgDebugLogFile );
00960                 }
00961         }
00962 }
00963 
00968 function wfIsDebugRawPage() {
00969         static $cache;
00970         if ( $cache !== null ) {
00971                 return $cache;
00972         }
00973         # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
00974         if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
00975                 || (
00976                         isset( $_SERVER['SCRIPT_NAME'] )
00977                         && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
00978                 ) )
00979         {
00980                 $cache = true;
00981         } else {
00982                 $cache = false;
00983         }
00984         return $cache;
00985 }
00986 
00992 function wfDebugTimer() {
00993         global $wgDebugTimestamps, $wgRequestTime;
00994 
00995         if ( !$wgDebugTimestamps ) {
00996                 return '';
00997         }
00998 
00999         $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
01000         $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
01001         return "$prefix $mem  ";
01002 }
01003 
01009 function wfDebugMem( $exact = false ) {
01010         $mem = memory_get_usage();
01011         if( !$exact ) {
01012                 $mem = floor( $mem / 1024 ) . ' kilobytes';
01013         } else {
01014                 $mem .= ' bytes';
01015         }
01016         wfDebug( "Memory usage: $mem\n" );
01017 }
01018 
01028 function wfDebugLog( $logGroup, $text, $public = true ) {
01029         global $wgDebugLogGroups;
01030         $text = trim( $text ) . "\n";
01031         if( isset( $wgDebugLogGroups[$logGroup] ) ) {
01032                 $time = wfTimestamp( TS_DB );
01033                 $wiki = wfWikiID();
01034                 $host = wfHostname();
01035                 if ( wfRunHooks( 'Debug', array( $text, $logGroup ) ) ) {
01036                         wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
01037                 }
01038         } elseif ( $public === true ) {
01039                 wfDebug( $text, true );
01040         }
01041 }
01042 
01048 function wfLogDBError( $text ) {
01049         global $wgDBerrorLog, $wgDBerrorLogTZ;
01050         static $logDBErrorTimeZoneObject = null;
01051 
01052         if ( $wgDBerrorLog ) {
01053                 $host = wfHostname();
01054                 $wiki = wfWikiID();
01055 
01056                 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
01057                         $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
01058                 }
01059 
01060                 // Workaround for https://bugs.php.net/bug.php?id=52063
01061                 // Can be removed when min PHP > 5.3.2
01062                 if ( $logDBErrorTimeZoneObject === null ) {
01063                         $d = date_create( "now" );
01064                 } else {
01065                         $d = date_create( "now", $logDBErrorTimeZoneObject );
01066                 }
01067 
01068                 $date = $d->format( 'D M j G:i:s T Y' );
01069 
01070                 $text = "$date\t$host\t$wiki\t$text";
01071                 wfErrorLog( $text, $wgDBerrorLog );
01072         }
01073 }
01074 
01087 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
01088         MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
01089 }
01090 
01101 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
01102         MWDebug::warning( $msg, $callerOffset + 1, $level );
01103 }
01104 
01114 function wfErrorLog( $text, $file ) {
01115         if ( substr( $file, 0, 4 ) == 'udp:' ) {
01116                 # Needs the sockets extension
01117                 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
01118                         // IPv6 bracketed host
01119                         $host = $m[2];
01120                         $port = intval( $m[3] );
01121                         $prefix = isset( $m[4] ) ? $m[4] : false;
01122                         $domain = AF_INET6;
01123                 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
01124                         $host = $m[2];
01125                         if ( !IP::isIPv4( $host ) ) {
01126                                 $host = gethostbyname( $host );
01127                         }
01128                         $port = intval( $m[3] );
01129                         $prefix = isset( $m[4] ) ? $m[4] : false;
01130                         $domain = AF_INET;
01131                 } else {
01132                         throw new MWException( __METHOD__ . ': Invalid UDP specification' );
01133                 }
01134 
01135                 // Clean it up for the multiplexer
01136                 if ( strval( $prefix ) !== '' ) {
01137                         $text = preg_replace( '/^/m', $prefix . ' ', $text );
01138 
01139                         // Limit to 64KB
01140                         if ( strlen( $text ) > 65506 ) {
01141                                 $text = substr( $text, 0, 65506 );
01142                         }
01143 
01144                         if ( substr( $text, -1 ) != "\n" ) {
01145                                 $text .= "\n";
01146                         }
01147                 } elseif ( strlen( $text ) > 65507 ) {
01148                         $text = substr( $text, 0, 65507 );
01149                 }
01150 
01151                 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
01152                 if ( !$sock ) {
01153                         return;
01154                 }
01155 
01156                 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
01157                 socket_close( $sock );
01158         } else {
01159                 wfSuppressWarnings();
01160                 $exists = file_exists( $file );
01161                 $size = $exists ? filesize( $file ) : false;
01162                 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
01163                         file_put_contents( $file, $text, FILE_APPEND );
01164                 }
01165                 wfRestoreWarnings();
01166         }
01167 }
01168 
01172 function wfLogProfilingData() {
01173         global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
01174         global $wgProfileLimit, $wgUser;
01175 
01176         $profiler = Profiler::instance();
01177 
01178         # Profiling must actually be enabled...
01179         if ( $profiler->isStub() ) {
01180                 return;
01181         }
01182 
01183         // Get total page request time and only show pages that longer than
01184         // $wgProfileLimit time (default is 0)
01185         $elapsed = microtime( true ) - $wgRequestTime;
01186         if ( $elapsed <= $wgProfileLimit ) {
01187                 return;
01188         }
01189 
01190         $profiler->logData();
01191 
01192         // Check whether this should be logged in the debug file.
01193         if ( $wgDebugLogFile == '' || ( !$wgDebugRawPage && wfIsDebugRawPage() ) ) {
01194                 return;
01195         }
01196 
01197         $forward = '';
01198         if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
01199                 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
01200         }
01201         if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
01202                 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
01203         }
01204         if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
01205                 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
01206         }
01207         if ( $forward ) {
01208                 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
01209         }
01210         // Don't load $wgUser at this late stage just for statistics purposes
01211         // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
01212         if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
01213                 $forward .= ' anon';
01214         }
01215         $log = sprintf( "%s\t%04.3f\t%s\n",
01216                 gmdate( 'YmdHis' ), $elapsed,
01217                 urldecode( $wgRequest->getRequestURL() . $forward ) );
01218 
01219         wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
01220 }
01221 
01228 function wfIncrStats( $key, $count = 1 ) {
01229         global $wgStatsMethod;
01230 
01231         $count = intval( $count );
01232 
01233         if( $wgStatsMethod == 'udp' ) {
01234                 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname, $wgAggregateStatsID;
01235                 static $socket;
01236 
01237                 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname;
01238 
01239                 if ( !$socket ) {
01240                         $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
01241                         $statline = "stats/{$id} - 1 1 1 1 1 -total\n";
01242                         socket_sendto(
01243                                 $socket,
01244                                 $statline,
01245                                 strlen( $statline ),
01246                                 0,
01247                                 $wgUDPProfilerHost,
01248                                 $wgUDPProfilerPort
01249                         );
01250                 }
01251                 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
01252                 wfSuppressWarnings();
01253                 socket_sendto(
01254                         $socket,
01255                         $statline,
01256                         strlen( $statline ),
01257                         0,
01258                         $wgUDPProfilerHost,
01259                         $wgUDPProfilerPort
01260                 );
01261                 wfRestoreWarnings();
01262         } elseif( $wgStatsMethod == 'cache' ) {
01263                 global $wgMemc;
01264                 $key = wfMemcKey( 'stats', $key );
01265                 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
01266                         $wgMemc->add( $key, $count );
01267                 }
01268         } else {
01269                 // Disabled
01270         }
01271 }
01272 
01280 function wfReadOnly() {
01281         global $wgReadOnlyFile, $wgReadOnly;
01282 
01283         if ( !is_null( $wgReadOnly ) ) {
01284                 return (bool)$wgReadOnly;
01285         }
01286         if ( $wgReadOnlyFile == '' ) {
01287                 return false;
01288         }
01289         // Set $wgReadOnly for faster access next time
01290         if ( is_file( $wgReadOnlyFile ) ) {
01291                 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
01292         } else {
01293                 $wgReadOnly = false;
01294         }
01295         return (bool)$wgReadOnly;
01296 }
01297 
01301 function wfReadOnlyReason() {
01302         global $wgReadOnly;
01303         wfReadOnly();
01304         return $wgReadOnly;
01305 }
01306 
01322 function wfGetLangObj( $langcode = false ) {
01323         # Identify which language to get or create a language object for.
01324         # Using is_object here due to Stub objects.
01325         if( is_object( $langcode ) ) {
01326                 # Great, we already have the object (hopefully)!
01327                 return $langcode;
01328         }
01329 
01330         global $wgContLang, $wgLanguageCode;
01331         if( $langcode === true || $langcode === $wgLanguageCode ) {
01332                 # $langcode is the language code of the wikis content language object.
01333                 # or it is a boolean and value is true
01334                 return $wgContLang;
01335         }
01336 
01337         global $wgLang;
01338         if( $langcode === false || $langcode === $wgLang->getCode() ) {
01339                 # $langcode is the language code of user language object.
01340                 # or it was a boolean and value is false
01341                 return $wgLang;
01342         }
01343 
01344         $validCodes = array_keys( Language::fetchLanguageNames() );
01345         if( in_array( $langcode, $validCodes ) ) {
01346                 # $langcode corresponds to a valid language.
01347                 return Language::factory( $langcode );
01348         }
01349 
01350         # $langcode is a string, but not a valid language code; use content language.
01351         wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
01352         return $wgContLang;
01353 }
01354 
01362 function wfUILang() {
01363         wfDeprecated( __METHOD__, '1.18' );
01364         global $wgLang;
01365         return $wgLang;
01366 }
01367 
01377 function wfMessage( $key /*...*/) {
01378         $params = func_get_args();
01379         array_shift( $params );
01380         if ( isset( $params[0] ) && is_array( $params[0] ) ) {
01381                 $params = $params[0];
01382         }
01383         return new Message( $key, $params );
01384 }
01385 
01394 function wfMessageFallback( /*...*/ ) {
01395         $args = func_get_args();
01396         return MWFunction::callArray( 'Message::newFallbackSequence', $args );
01397 }
01398 
01418 function wfMsg( $key ) {
01419         $args = func_get_args();
01420         array_shift( $args );
01421         return wfMsgReal( $key, $args );
01422 }
01423 
01432 function wfMsgNoTrans( $key ) {
01433         $args = func_get_args();
01434         array_shift( $args );
01435         return wfMsgReal( $key, $args, true, false, false );
01436 }
01437 
01463 function wfMsgForContent( $key ) {
01464         global $wgForceUIMsgAsContentMsg;
01465         $args = func_get_args();
01466         array_shift( $args );
01467         $forcontent = true;
01468         if( is_array( $wgForceUIMsgAsContentMsg ) &&
01469                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
01470         {
01471                 $forcontent = false;
01472         }
01473         return wfMsgReal( $key, $args, true, $forcontent );
01474 }
01475 
01484 function wfMsgForContentNoTrans( $key ) {
01485         global $wgForceUIMsgAsContentMsg;
01486         $args = func_get_args();
01487         array_shift( $args );
01488         $forcontent = true;
01489         if( is_array( $wgForceUIMsgAsContentMsg ) &&
01490                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
01491         {
01492                 $forcontent = false;
01493         }
01494         return wfMsgReal( $key, $args, true, $forcontent, false );
01495 }
01496 
01509 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
01510         wfProfileIn( __METHOD__ );
01511         $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
01512         $message = wfMsgReplaceArgs( $message, $args );
01513         wfProfileOut( __METHOD__ );
01514         return $message;
01515 }
01516 
01529 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
01530         wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
01531 
01532         $cache = MessageCache::singleton();
01533         $message = $cache->get( $key, $useDB, $langCode );
01534         if( $message === false ) {
01535                 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
01536         } elseif ( $transform ) {
01537                 $message = $cache->transform( $message );
01538         }
01539         return $message;
01540 }
01541 
01550 function wfMsgReplaceArgs( $message, $args ) {
01551         # Fix windows line-endings
01552         # Some messages are split with explode("\n", $msg)
01553         $message = str_replace( "\r", '', $message );
01554 
01555         // Replace arguments
01556         if ( count( $args ) ) {
01557                 if ( is_array( $args[0] ) ) {
01558                         $args = array_values( $args[0] );
01559                 }
01560                 $replacementKeys = array();
01561                 foreach( $args as $n => $param ) {
01562                         $replacementKeys['$' . ( $n + 1 )] = $param;
01563                 }
01564                 $message = strtr( $message, $replacementKeys );
01565         }
01566 
01567         return $message;
01568 }
01569 
01583 function wfMsgHtml( $key ) {
01584         $args = func_get_args();
01585         array_shift( $args );
01586         return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
01587 }
01588 
01602 function wfMsgWikiHtml( $key ) {
01603         $args = func_get_args();
01604         array_shift( $args );
01605         return wfMsgReplaceArgs(
01606                 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
01607                 /* can't be set to false */ true, /* interface */ true )->getText(),
01608                 $args );
01609 }
01610 
01633 function wfMsgExt( $key, $options ) {
01634         $args = func_get_args();
01635         array_shift( $args );
01636         array_shift( $args );
01637         $options = (array)$options;
01638 
01639         foreach( $options as $arrayKey => $option ) {
01640                 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
01641                         # An unknown index, neither numeric nor "language"
01642                         wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
01643                 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
01644                 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
01645                 'replaceafter', 'parsemag', 'content' ) ) ) {
01646                         # A numeric index with unknown value
01647                         wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
01648                 }
01649         }
01650 
01651         if( in_array( 'content', $options, true ) ) {
01652                 $forContent = true;
01653                 $langCode = true;
01654                 $langCodeObj = null;
01655         } elseif( array_key_exists( 'language', $options ) ) {
01656                 $forContent = false;
01657                 $langCode = wfGetLangObj( $options['language'] );
01658                 $langCodeObj = $langCode;
01659         } else {
01660                 $forContent = false;
01661                 $langCode = false;
01662                 $langCodeObj = null;
01663         }
01664 
01665         $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
01666 
01667         if( !in_array( 'replaceafter', $options, true ) ) {
01668                 $string = wfMsgReplaceArgs( $string, $args );
01669         }
01670 
01671         $messageCache = MessageCache::singleton();
01672         $parseInline = in_array( 'parseinline', $options, true );
01673         if( in_array( 'parse', $options, true ) || $parseInline ) {
01674                 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
01675                 if ( $string instanceof ParserOutput ) {
01676                         $string = $string->getText();
01677                 }
01678 
01679                 if ( $parseInline ) {
01680                         $m = array();
01681                         if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
01682                                 $string = $m[1];
01683                         }
01684                 }
01685         } elseif ( in_array( 'parsemag', $options, true ) ) {
01686                 $string = $messageCache->transform( $string,
01687                                 !$forContent, $langCodeObj );
01688         }
01689 
01690         if ( in_array( 'escape', $options, true ) ) {
01691                 $string = htmlspecialchars ( $string );
01692         } elseif ( in_array( 'escapenoentities', $options, true ) ) {
01693                 $string = Sanitizer::escapeHtmlAllowEntities( $string );
01694         }
01695 
01696         if( in_array( 'replaceafter', $options, true ) ) {
01697                 $string = wfMsgReplaceArgs( $string, $args );
01698         }
01699 
01700         return $string;
01701 }
01702 
01713 function wfEmptyMsg( $key ) {
01714         return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
01715 }
01716 
01723 function wfDebugDieBacktrace( $msg = '' ) {
01724         throw new MWException( $msg );
01725 }
01726 
01734 function wfHostname() {
01735         static $host;
01736         if ( is_null( $host ) ) {
01737 
01738                 # Hostname overriding
01739                 global $wgOverrideHostname;
01740                 if( $wgOverrideHostname !== false ) {
01741                         # Set static and skip any detection
01742                         $host = $wgOverrideHostname;
01743                         return $host;
01744                 }
01745 
01746                 if ( function_exists( 'posix_uname' ) ) {
01747                         // This function not present on Windows
01748                         $uname = posix_uname();
01749                 } else {
01750                         $uname = false;
01751                 }
01752                 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
01753                         $host = $uname['nodename'];
01754                 } elseif ( getenv( 'COMPUTERNAME' ) ) {
01755                         # Windows computer name
01756                         $host = getenv( 'COMPUTERNAME' );
01757                 } else {
01758                         # This may be a virtual server.
01759                         $host = $_SERVER['SERVER_NAME'];
01760                 }
01761         }
01762         return $host;
01763 }
01764 
01771 function wfReportTime() {
01772         global $wgRequestTime, $wgShowHostnames;
01773 
01774         $elapsed = microtime( true ) - $wgRequestTime;
01775 
01776         return $wgShowHostnames
01777                 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
01778                 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
01779 }
01780 
01796 function wfDebugBacktrace( $limit = 0 ) {
01797         static $disabled = null;
01798 
01799         if( extension_loaded( 'Zend Optimizer' ) ) {
01800                 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
01801                 return array();
01802         }
01803 
01804         if ( is_null( $disabled ) ) {
01805                 $disabled = false;
01806                 $functions = explode( ',', ini_get( 'disable_functions' ) );
01807                 $functions = array_map( 'trim', $functions );
01808                 $functions = array_map( 'strtolower', $functions );
01809                 if ( in_array( 'debug_backtrace', $functions ) ) {
01810                         wfDebug( "debug_backtrace is in disabled_functions\n" );
01811                         $disabled = true;
01812                 }
01813         }
01814         if ( $disabled ) {
01815                 return array();
01816         }
01817 
01818         if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
01819                 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
01820         } else {
01821                 return array_slice( debug_backtrace(), 1 );
01822         }
01823 }
01824 
01830 function wfBacktrace() {
01831         global $wgCommandLineMode;
01832 
01833         if ( $wgCommandLineMode ) {
01834                 $msg = '';
01835         } else {
01836                 $msg = "<ul>\n";
01837         }
01838         $backtrace = wfDebugBacktrace();
01839         foreach( $backtrace as $call ) {
01840                 if( isset( $call['file'] ) ) {
01841                         $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
01842                         $file = $f[count( $f ) - 1];
01843                 } else {
01844                         $file = '-';
01845                 }
01846                 if( isset( $call['line'] ) ) {
01847                         $line = $call['line'];
01848                 } else {
01849                         $line = '-';
01850                 }
01851                 if ( $wgCommandLineMode ) {
01852                         $msg .= "$file line $line calls ";
01853                 } else {
01854                         $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
01855                 }
01856                 if( !empty( $call['class'] ) ) {
01857                         $msg .= $call['class'] . $call['type'];
01858                 }
01859                 $msg .= $call['function'] . '()';
01860 
01861                 if ( $wgCommandLineMode ) {
01862                         $msg .= "\n";
01863                 } else {
01864                         $msg .= "</li>\n";
01865                 }
01866         }
01867         if ( $wgCommandLineMode ) {
01868                 $msg .= "\n";
01869         } else {
01870                 $msg .= "</ul>\n";
01871         }
01872 
01873         return $msg;
01874 }
01875 
01885 function wfGetCaller( $level = 2 ) {
01886         $backtrace = wfDebugBacktrace( $level + 1 );
01887         if ( isset( $backtrace[$level] ) ) {
01888                 return wfFormatStackFrame( $backtrace[$level] );
01889         } else {
01890                 return 'unknown';
01891         }
01892 }
01893 
01902 function wfGetAllCallers( $limit = 3 ) {
01903         $trace = array_reverse( wfDebugBacktrace() );
01904         if ( !$limit || $limit > count( $trace ) - 1 ) {
01905                 $limit = count( $trace ) - 1;
01906         }
01907         $trace = array_slice( $trace, -$limit - 1, $limit );
01908         return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
01909 }
01910 
01917 function wfFormatStackFrame( $frame ) {
01918         return isset( $frame['class'] ) ?
01919                 $frame['class'] . '::' . $frame['function'] :
01920                 $frame['function'];
01921 }
01922 
01923 
01924 /* Some generic result counters, pulled out of SearchEngine */
01925 
01926 
01934 function wfShowingResults( $offset, $limit ) {
01935         return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
01936 }
01937 
01949 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
01950         wfDeprecated( __METHOD__, '1.19' );
01951 
01952         global $wgLang;
01953 
01954         $query = wfCgiToArray( $query );
01955 
01956         if( is_object( $link ) ) {
01957                 $title = $link;
01958         } else {
01959                 $title = Title::newFromText( $link );
01960                 if( is_null( $title ) ) {
01961                         return false;
01962                 }
01963         }
01964 
01965         return $wgLang->viewPrevNext( $title, $offset, $limit, $query, $atend );
01966 }
01967 
01978 function wfSpecialList( $page, $details, $oppositedm = true ) {
01979         wfDeprecated( __METHOD__, '1.19' );
01980 
01981         global $wgLang;
01982         return $wgLang->specialList( $page, $details, $oppositedm );
01983 }
01984 
01992 function wfClientAcceptsGzip( $force = false ) {
01993         static $result = null;
01994         if ( $result === null || $force ) {
01995                 $result = false;
01996                 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
01997                         # @todo FIXME: We may want to blacklist some broken browsers
01998                         $m = array();
01999                         if( preg_match(
02000                                 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
02001                                 $_SERVER['HTTP_ACCEPT_ENCODING'],
02002                                 $m )
02003                         )
02004                         {
02005                                 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
02006                                         $result = false;
02007                                         return $result;
02008                                 }
02009                                 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
02010                                 $result = true;
02011                         }
02012                 }
02013         }
02014         return $result;
02015 }
02016 
02026 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
02027         global $wgRequest;
02028         return $wgRequest->getLimitOffset( $deflimit, $optionname );
02029 }
02030 
02040 function wfEscapeWikiText( $text ) {
02041         $text = strtr( "\n$text", array(
02042                 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
02043                 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
02044                 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
02045                 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
02046                 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
02047                 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
02048         ) );
02049         return substr( $text, 1 );
02050 }
02051 
02056 function wfTime() {
02057         return microtime( true );
02058 }
02059 
02070 function wfSetVar( &$dest, $source, $force = false ) {
02071         $temp = $dest;
02072         if ( !is_null( $source ) || $force ) {
02073                 $dest = $source;
02074         }
02075         return $temp;
02076 }
02077 
02087 function wfSetBit( &$dest, $bit, $state = true ) {
02088         $temp = (bool)( $dest & $bit );
02089         if ( !is_null( $state ) ) {
02090                 if ( $state ) {
02091                         $dest |= $bit;
02092                 } else {
02093                         $dest &= ~$bit;
02094                 }
02095         }
02096         return $temp;
02097 }
02098 
02105 function wfVarDump( $var ) {
02106         global $wgOut;
02107         $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
02108         if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
02109                 print $s;
02110         } else {
02111                 $wgOut->addHTML( $s );
02112         }
02113 }
02114 
02122 function wfHttpError( $code, $label, $desc ) {
02123         global $wgOut;
02124         $wgOut->disable();
02125         header( "HTTP/1.0 $code $label" );
02126         header( "Status: $code $label" );
02127         $wgOut->sendCacheControl();
02128 
02129         header( 'Content-type: text/html; charset=utf-8' );
02130         print "<!doctype html>" .
02131                 '<html><head><title>' .
02132                 htmlspecialchars( $label ) .
02133                 '</title></head><body><h1>' .
02134                 htmlspecialchars( $label ) .
02135                 '</h1><p>' .
02136                 nl2br( htmlspecialchars( $desc ) ) .
02137                 "</p></body></html>\n";
02138 }
02139 
02157 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
02158         if( $resetGzipEncoding ) {
02159                 // Suppress Content-Encoding and Content-Length
02160                 // headers from 1.10+s wfOutputHandler
02161                 global $wgDisableOutputCompression;
02162                 $wgDisableOutputCompression = true;
02163         }
02164         while( $status = ob_get_status() ) {
02165                 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
02166                         // Probably from zlib.output_compression or other
02167                         // PHP-internal setting which can't be removed.
02168                         //
02169                         // Give up, and hope the result doesn't break
02170                         // output behavior.
02171                         break;
02172                 }
02173                 if( !ob_end_clean() ) {
02174                         // Could not remove output buffer handler; abort now
02175                         // to avoid getting in some kind of infinite loop.
02176                         break;
02177                 }
02178                 if( $resetGzipEncoding ) {
02179                         if( $status['name'] == 'ob_gzhandler' ) {
02180                                 // Reset the 'Content-Encoding' field set by this handler
02181                                 // so we can start fresh.
02182                                 header_remove( 'Content-Encoding' );
02183                                 break;
02184                         }
02185                 }
02186         }
02187 }
02188 
02201 function wfClearOutputBuffers() {
02202         wfResetOutputBuffers( false );
02203 }
02204 
02213 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
02214         # No arg means accept anything (per HTTP spec)
02215         if( !$accept ) {
02216                 return array( $def => 1.0 );
02217         }
02218 
02219         $prefs = array();
02220 
02221         $parts = explode( ',', $accept );
02222 
02223         foreach( $parts as $part ) {
02224                 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
02225                 $values = explode( ';', trim( $part ) );
02226                 $match = array();
02227                 if ( count( $values ) == 1 ) {
02228                         $prefs[$values[0]] = 1.0;
02229                 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
02230                         $prefs[$values[0]] = floatval( $match[1] );
02231                 }
02232         }
02233 
02234         return $prefs;
02235 }
02236 
02249 function mimeTypeMatch( $type, $avail ) {
02250         if( array_key_exists( $type, $avail ) ) {
02251                 return $type;
02252         } else {
02253                 $parts = explode( '/', $type );
02254                 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
02255                         return $parts[0] . '/*';
02256                 } elseif( array_key_exists( '*/*', $avail ) ) {
02257                         return '*/*';
02258                 } else {
02259                         return null;
02260                 }
02261         }
02262 }
02263 
02277 function wfNegotiateType( $cprefs, $sprefs ) {
02278         $combine = array();
02279 
02280         foreach( array_keys( $sprefs ) as $type ) {
02281                 $parts = explode( '/', $type );
02282                 if( $parts[1] != '*' ) {
02283                         $ckey = mimeTypeMatch( $type, $cprefs );
02284                         if( $ckey ) {
02285                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
02286                         }
02287                 }
02288         }
02289 
02290         foreach( array_keys( $cprefs ) as $type ) {
02291                 $parts = explode( '/', $type );
02292                 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
02293                         $skey = mimeTypeMatch( $type, $sprefs );
02294                         if( $skey ) {
02295                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
02296                         }
02297                 }
02298         }
02299 
02300         $bestq = 0;
02301         $besttype = null;
02302 
02303         foreach( array_keys( $combine ) as $type ) {
02304                 if( $combine[$type] > $bestq ) {
02305                         $besttype = $type;
02306                         $bestq = $combine[$type];
02307                 }
02308         }
02309 
02310         return $besttype;
02311 }
02312 
02318 function wfSuppressWarnings( $end = false ) {
02319         static $suppressCount = 0;
02320         static $originalLevel = false;
02321 
02322         if ( $end ) {
02323                 if ( $suppressCount ) {
02324                         --$suppressCount;
02325                         if ( !$suppressCount ) {
02326                                 error_reporting( $originalLevel );
02327                         }
02328                 }
02329         } else {
02330                 if ( !$suppressCount ) {
02331                         $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT ) );
02332                 }
02333                 ++$suppressCount;
02334         }
02335 }
02336 
02340 function wfRestoreWarnings() {
02341         wfSuppressWarnings( true );
02342 }
02343 
02344 # Autodetect, convert and provide timestamps of various types
02345 
02349 define( 'TS_UNIX', 0 );
02350 
02354 define( 'TS_MW', 1 );
02355 
02359 define( 'TS_DB', 2 );
02360 
02364 define( 'TS_RFC2822', 3 );
02365 
02371 define( 'TS_ISO_8601', 4 );
02372 
02380 define( 'TS_EXIF', 5 );
02381 
02385 define( 'TS_ORACLE', 6 );
02386 
02390 define( 'TS_POSTGRES', 7 );
02391 
02395 define( 'TS_DB2', 8 );
02396 
02400 define( 'TS_ISO_8601_BASIC', 9 );
02401 
02411 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
02412         try {
02413                 $timestamp = new MWTimestamp( $ts );
02414                 return $timestamp->getTimestamp( $outputtype );
02415         } catch( TimestampException $e ) {
02416                 wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n");
02417                 return false;
02418         }
02419 }
02420 
02429 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
02430         if( is_null( $ts ) ) {
02431                 return null;
02432         } else {
02433                 return wfTimestamp( $outputtype, $ts );
02434         }
02435 }
02436 
02442 function wfTimestampNow() {
02443         # return NOW
02444         return wfTimestamp( TS_MW, time() );
02445 }
02446 
02452 function wfIsWindows() {
02453         static $isWindows = null;
02454         if ( $isWindows === null ) {
02455                 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
02456         }
02457         return $isWindows;
02458 }
02459 
02465 function wfIsHipHop() {
02466         return function_exists( 'hphp_thread_set_warmup_enabled' );
02467 }
02468 
02475 function swap( &$x, &$y ) {
02476         $z = $x;
02477         $x = $y;
02478         $y = $z;
02479 }
02480 
02492 function wfTempDir() {
02493         global $wgTmpDirectory;
02494 
02495         if ( $wgTmpDirectory !== false ) {
02496                 return $wgTmpDirectory;
02497         }
02498 
02499         $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
02500 
02501         foreach( $tmpDir as $tmp ) {
02502                 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
02503                         return $tmp;
02504                 }
02505         }
02506         return sys_get_temp_dir();
02507 }
02508 
02517 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
02518         global $wgDirectoryMode;
02519 
02520         if ( FileBackend::isStoragePath( $dir ) ) { // sanity
02521                 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
02522         }
02523 
02524         if ( !is_null( $caller ) ) {
02525                 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
02526         }
02527 
02528         if( strval( $dir ) === '' || file_exists( $dir ) ) {
02529                 return true;
02530         }
02531 
02532         $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
02533 
02534         if ( is_null( $mode ) ) {
02535                 $mode = $wgDirectoryMode;
02536         }
02537 
02538         // Turn off the normal warning, we're doing our own below
02539         wfSuppressWarnings();
02540         $ok = mkdir( $dir, $mode, true ); // PHP5 <3
02541         wfRestoreWarnings();
02542 
02543         if( !$ok ) {
02544                 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
02545                 trigger_error( sprintf( "%s: failed to mkdir \"%s\" mode 0%o", __FUNCTION__, $dir, $mode ),
02546                         E_USER_WARNING );
02547         }
02548         return $ok;
02549 }
02550 
02555 function wfRecursiveRemoveDir( $dir ) {
02556         wfDebug( __FUNCTION__ . "( $dir )\n" );
02557         // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
02558         if ( is_dir( $dir ) ) {
02559                 $objects = scandir( $dir );
02560                 foreach ( $objects as $object ) {
02561                         if ( $object != "." && $object != ".." ) {
02562                                 if ( filetype( $dir . '/' . $object ) == "dir" ) {
02563                                         wfRecursiveRemoveDir( $dir . '/' . $object );
02564                                 } else {
02565                                         unlink( $dir . '/' . $object );
02566                                 }
02567                         }
02568                 }
02569                 reset( $objects );
02570                 rmdir( $dir );
02571         }
02572 }
02573 
02580 function wfPercent( $nr, $acc = 2, $round = true ) {
02581         $ret = sprintf( "%.${acc}f", $nr );
02582         return $round ? round( $ret, $acc ) . '%' : "$ret%";
02583 }
02584 
02593 function in_string( $needle, $str, $insensitive = false ) {
02594         $func = 'strpos';
02595         if( $insensitive ) $func = 'stripos';
02596 
02597         return $func( $str, $needle ) !== false;
02598 }
02599 
02623 function wfIniGetBool( $setting ) {
02624         $val = ini_get( $setting );
02625         // 'on' and 'true' can't have whitespace around them, but '1' can.
02626         return strtolower( $val ) == 'on'
02627                 || strtolower( $val ) == 'true'
02628                 || strtolower( $val ) == 'yes'
02629                 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
02630 }
02631 
02641 function wfDl( $extension, $fileName = null ) {
02642         if( extension_loaded( $extension ) ) {
02643                 return true;
02644         }
02645 
02646         $canDl = false;
02647         $sapi = php_sapi_name();
02648         if( $sapi == 'cli' || $sapi == 'cgi' || $sapi == 'embed' ) {
02649                 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
02650                 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
02651         }
02652 
02653         if( $canDl ) {
02654                 $fileName = $fileName ? $fileName : $extension;
02655                 if( wfIsWindows() ) {
02656                         $fileName = 'php_' . $fileName;
02657                 }
02658                 wfSuppressWarnings();
02659                 dl( $fileName . '.' . PHP_SHLIB_SUFFIX );
02660                 wfRestoreWarnings();
02661         }
02662         return extension_loaded( $extension );
02663 }
02664 
02676 function wfEscapeShellArg( ) {
02677         wfInitShellLocale();
02678 
02679         $args = func_get_args();
02680         $first = true;
02681         $retVal = '';
02682         foreach ( $args as $arg ) {
02683                 if ( !$first ) {
02684                         $retVal .= ' ';
02685                 } else {
02686                         $first = false;
02687                 }
02688 
02689                 if ( wfIsWindows() ) {
02690                         // Escaping for an MSVC-style command line parser and CMD.EXE
02691                         // Refs:
02692                         //  * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
02693                         //  * http://technet.microsoft.com/en-us/library/cc723564.aspx
02694                         //  * Bug #13518
02695                         //  * CR r63214
02696                         // Double the backslashes before any double quotes. Escape the double quotes.
02697                         $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
02698                         $arg = '';
02699                         $iteration = 0;
02700                         foreach ( $tokens as $token ) {
02701                                 if ( $iteration % 2 == 1 ) {
02702                                         // Delimiter, a double quote preceded by zero or more slashes
02703                                         $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
02704                                 } elseif ( $iteration % 4 == 2 ) {
02705                                         // ^ in $token will be outside quotes, need to be escaped
02706                                         $arg .= str_replace( '^', '^^', $token );
02707                                 } else { // $iteration % 4 == 0
02708                                         // ^ in $token will appear inside double quotes, so leave as is
02709                                         $arg .= $token;
02710                                 }
02711                                 $iteration++;
02712                         }
02713                         // Double the backslashes before the end of the string, because
02714                         // we will soon add a quote
02715                         $m = array();
02716                         if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
02717                                 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
02718                         }
02719 
02720                         // Add surrounding quotes
02721                         $retVal .= '"' . $arg . '"';
02722                 } else {
02723                         $retVal .= escapeshellarg( $arg );
02724                 }
02725         }
02726         return $retVal;
02727 }
02728 
02741 function wfShellExec( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
02742         global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
02743 
02744         static $disabled;
02745         if ( is_null( $disabled ) ) {
02746                 $disabled = false;
02747                 if( wfIniGetBool( 'safe_mode' ) ) {
02748                         wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
02749                         $disabled = 'safemode';
02750                 } else {
02751                         $functions = explode( ',', ini_get( 'disable_functions' ) );
02752                         $functions = array_map( 'trim', $functions );
02753                         $functions = array_map( 'strtolower', $functions );
02754                         if ( in_array( 'passthru', $functions ) ) {
02755                                 wfDebug( "passthru is in disabled_functions\n" );
02756                                 $disabled = 'passthru';
02757                         }
02758                 }
02759         }
02760         if ( $disabled ) {
02761                 $retval = 1;
02762                 return $disabled == 'safemode' ?
02763                         'Unable to run external programs in safe mode.' :
02764                         'Unable to run external programs, passthru() is disabled.';
02765         }
02766 
02767         wfInitShellLocale();
02768 
02769         $envcmd = '';
02770         foreach( $environ as $k => $v ) {
02771                 if ( wfIsWindows() ) {
02772                         /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
02773                          * appear in the environment variable, so we must use carat escaping as documented in
02774                          * http://technet.microsoft.com/en-us/library/cc723564.aspx
02775                          * Note however that the quote isn't listed there, but is needed, and the parentheses
02776                          * are listed there but doesn't appear to need it.
02777                          */
02778                         $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
02779                 } else {
02780                         /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
02781                          * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
02782                          */
02783                         $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
02784                 }
02785         }
02786         $cmd = $envcmd . $cmd;
02787 
02788         if ( php_uname( 's' ) == 'Linux' ) {
02789                 $time = intval ( isset($limits['time']) ? $limits['time'] : $wgMaxShellTime );
02790                 $mem = intval ( isset($limits['memory']) ? $limits['memory'] : $wgMaxShellMemory );
02791                 $filesize = intval ( isset($limits['filesize']) ? $limits['filesize'] : $wgMaxShellFileSize );
02792 
02793                 if ( $time > 0 && $mem > 0 ) {
02794                         $script = "$IP/bin/ulimit4.sh";
02795                         if ( is_executable( $script ) ) {
02796                                 $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
02797                         }
02798                 }
02799         }
02800         wfDebug( "wfShellExec: $cmd\n" );
02801 
02802         $retval = 1; // error by default?
02803         ob_start();
02804         passthru( $cmd, $retval );
02805         $output = ob_get_contents();
02806         ob_end_clean();
02807 
02808         if ( $retval == 127 ) {
02809                 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
02810         }
02811         return $output;
02812 }
02813 
02818 function wfInitShellLocale() {
02819         static $done = false;
02820         if ( $done ) {
02821                 return;
02822         }
02823         $done = true;
02824         global $wgShellLocale;
02825         if ( !wfIniGetBool( 'safe_mode' ) ) {
02826                 putenv( "LC_CTYPE=$wgShellLocale" );
02827                 setlocale( LC_CTYPE, $wgShellLocale );
02828         }
02829 }
02830 
02835 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
02836         return wfShellWikiCmd( $script, $parameters, $options );
02837 }
02838 
02850 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
02851         global $wgPhpCli;
02852         // Give site config file a chance to run the script in a wrapper.
02853         // The caller may likely want to call wfBasename() on $script.
02854         wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
02855         $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
02856         if ( isset( $options['wrapper'] ) ) {
02857                 $cmd[] = $options['wrapper'];
02858         }
02859         $cmd[] = $script;
02860         // Escape each parameter for shell
02861         return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
02862 }
02863 
02874 function wfMerge( $old, $mine, $yours, &$result ) {
02875         global $wgDiff3;
02876 
02877         # This check may also protect against code injection in
02878         # case of broken installations.
02879         wfSuppressWarnings();
02880         $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
02881         wfRestoreWarnings();
02882 
02883         if( !$haveDiff3 ) {
02884                 wfDebug( "diff3 not found\n" );
02885                 return false;
02886         }
02887 
02888         # Make temporary files
02889         $td = wfTempDir();
02890         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
02891         $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
02892         $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
02893 
02894         fwrite( $oldtextFile, $old );
02895         fclose( $oldtextFile );
02896         fwrite( $mytextFile, $mine );
02897         fclose( $mytextFile );
02898         fwrite( $yourtextFile, $yours );
02899         fclose( $yourtextFile );
02900 
02901         # Check for a conflict
02902         $cmd = $wgDiff3 . ' -a --overlap-only ' .
02903                 wfEscapeShellArg( $mytextName ) . ' ' .
02904                 wfEscapeShellArg( $oldtextName ) . ' ' .
02905                 wfEscapeShellArg( $yourtextName );
02906         $handle = popen( $cmd, 'r' );
02907 
02908         if( fgets( $handle, 1024 ) ) {
02909                 $conflict = true;
02910         } else {
02911                 $conflict = false;
02912         }
02913         pclose( $handle );
02914 
02915         # Merge differences
02916         $cmd = $wgDiff3 . ' -a -e --merge ' .
02917                 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
02918         $handle = popen( $cmd, 'r' );
02919         $result = '';
02920         do {
02921                 $data = fread( $handle, 8192 );
02922                 if ( strlen( $data ) == 0 ) {
02923                         break;
02924                 }
02925                 $result .= $data;
02926         } while ( true );
02927         pclose( $handle );
02928         unlink( $mytextName );
02929         unlink( $oldtextName );
02930         unlink( $yourtextName );
02931 
02932         if ( $result === '' && $old !== '' && !$conflict ) {
02933                 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
02934                 $conflict = true;
02935         }
02936         return !$conflict;
02937 }
02938 
02948 function wfDiff( $before, $after, $params = '-u' ) {
02949         if ( $before == $after ) {
02950                 return '';
02951         }
02952 
02953         global $wgDiff;
02954         wfSuppressWarnings();
02955         $haveDiff = $wgDiff && file_exists( $wgDiff );
02956         wfRestoreWarnings();
02957 
02958         # This check may also protect against code injection in
02959         # case of broken installations.
02960         if( !$haveDiff ) {
02961                 wfDebug( "diff executable not found\n" );
02962                 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
02963                 $format = new UnifiedDiffFormatter();
02964                 return $format->format( $diffs );
02965         }
02966 
02967         # Make temporary files
02968         $td = wfTempDir();
02969         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
02970         $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
02971 
02972         fwrite( $oldtextFile, $before );
02973         fclose( $oldtextFile );
02974         fwrite( $newtextFile, $after );
02975         fclose( $newtextFile );
02976 
02977         // Get the diff of the two files
02978         $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
02979 
02980         $h = popen( $cmd, 'r' );
02981 
02982         $diff = '';
02983 
02984         do {
02985                 $data = fread( $h, 8192 );
02986                 if ( strlen( $data ) == 0 ) {
02987                         break;
02988                 }
02989                 $diff .= $data;
02990         } while ( true );
02991 
02992         // Clean up
02993         pclose( $h );
02994         unlink( $oldtextName );
02995         unlink( $newtextName );
02996 
02997         // Kill the --- and +++ lines. They're not useful.
02998         $diff_lines = explode( "\n", $diff );
02999         if ( strpos( $diff_lines[0], '---' ) === 0 ) {
03000                 unset( $diff_lines[0] );
03001         }
03002         if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
03003                 unset( $diff_lines[1] );
03004         }
03005 
03006         $diff = implode( "\n", $diff_lines );
03007 
03008         return $diff;
03009 }
03010 
03026 function wfUsePHP( $req_ver ) {
03027         $php_ver = PHP_VERSION;
03028 
03029         if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
03030                 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
03031         }
03032 }
03033 
03047 function wfUseMW( $req_ver ) {
03048         global $wgVersion;
03049 
03050         if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
03051                 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
03052         }
03053 }
03054 
03067 function wfBaseName( $path, $suffix = '' ) {
03068         $encSuffix = ( $suffix == '' )
03069                 ? ''
03070                 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
03071         $matches = array();
03072         if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
03073                 return $matches[1];
03074         } else {
03075                 return '';
03076         }
03077 }
03078 
03088 function wfRelativePath( $path, $from ) {
03089         // Normalize mixed input on Windows...
03090         $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
03091         $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
03092 
03093         // Trim trailing slashes -- fix for drive root
03094         $path = rtrim( $path, DIRECTORY_SEPARATOR );
03095         $from = rtrim( $from, DIRECTORY_SEPARATOR );
03096 
03097         $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
03098         $against = explode( DIRECTORY_SEPARATOR, $from );
03099 
03100         if( $pieces[0] !== $against[0] ) {
03101                 // Non-matching Windows drive letters?
03102                 // Return a full path.
03103                 return $path;
03104         }
03105 
03106         // Trim off common prefix
03107         while( count( $pieces ) && count( $against )
03108                 && $pieces[0] == $against[0] ) {
03109                 array_shift( $pieces );
03110                 array_shift( $against );
03111         }
03112 
03113         // relative dots to bump us to the parent
03114         while( count( $against ) ) {
03115                 array_unshift( $pieces, '..' );
03116                 array_shift( $against );
03117         }
03118 
03119         array_push( $pieces, wfBaseName( $path ) );
03120 
03121         return implode( DIRECTORY_SEPARATOR, $pieces );
03122 }
03123 
03131 function wfDoUpdates( $commit = '' ) {
03132         wfDeprecated( __METHOD__, '1.19' );
03133         DeferredUpdates::doUpdates( $commit );
03134 }
03135 
03150 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
03151         $input = strval( $input );
03152         if( $sourceBase < 2 ||
03153                 $sourceBase > 36 ||
03154                 $destBase < 2 ||
03155                 $destBase > 36 ||
03156                 $pad < 1 ||
03157                 $sourceBase != intval( $sourceBase ) ||
03158                 $destBase != intval( $destBase ) ||
03159                 $pad != intval( $pad ) ||
03160                 !is_string( $input ) ||
03161                 $input == '' ) {
03162                 return false;
03163         }
03164         $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
03165         $inDigits = array();
03166         $outChars = '';
03167 
03168         // Decode and validate input string
03169         $input = strtolower( $input );
03170         for( $i = 0; $i < strlen( $input ); $i++ ) {
03171                 $n = strpos( $digitChars, $input[$i] );
03172                 if( $n === false || $n > $sourceBase ) {
03173                         return false;
03174                 }
03175                 $inDigits[] = $n;
03176         }
03177 
03178         // Iterate over the input, modulo-ing out an output digit
03179         // at a time until input is gone.
03180         while( count( $inDigits ) ) {
03181                 $work = 0;
03182                 $workDigits = array();
03183 
03184                 // Long division...
03185                 foreach( $inDigits as $digit ) {
03186                         $work *= $sourceBase;
03187                         $work += $digit;
03188 
03189                         if( $work < $destBase ) {
03190                                 // Gonna need to pull another digit.
03191                                 if( count( $workDigits ) ) {
03192                                         // Avoid zero-padding; this lets us find
03193                                         // the end of the input very easily when
03194                                         // length drops to zero.
03195                                         $workDigits[] = 0;
03196                                 }
03197                         } else {
03198                                 // Finally! Actual division!
03199                                 $workDigits[] = intval( $work / $destBase );
03200 
03201                                 // Isn't it annoying that most programming languages
03202                                 // don't have a single divide-and-remainder operator,
03203                                 // even though the CPU implements it that way?
03204                                 $work = $work % $destBase;
03205                         }
03206                 }
03207 
03208                 // All that division leaves us with a remainder,
03209                 // which is conveniently our next output digit.
03210                 $outChars .= $digitChars[$work];
03211 
03212                 // And we continue!
03213                 $inDigits = $workDigits;
03214         }
03215 
03216         while( strlen( $outChars ) < $pad ) {
03217                 $outChars .= '0';
03218         }
03219 
03220         return strrev( $outChars );
03221 }
03222 
03231 function wfCreateObject( $name, $p ) {
03232         wfDeprecated( __FUNCTION__, '1.18' );
03233         return MWFunction::newObj( $name, $p );
03234 }
03235 
03239 function wfHttpOnlySafe() {
03240         global $wgHttpOnlyBlacklist;
03241 
03242         if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
03243                 foreach( $wgHttpOnlyBlacklist as $regex ) {
03244                         if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
03245                                 return false;
03246                         }
03247                 }
03248         }
03249 
03250         return true;
03251 }
03252 
03257 function wfCheckEntropy() {
03258         return (
03259                         ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
03260                         || ini_get( 'session.entropy_file' )
03261                 )
03262                 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
03263 }
03264 
03269 function wfFixSessionID() {
03270         // If the cookie or session id is already set we already have a session and should abort
03271         if ( isset( $_COOKIE[ session_name() ] ) || session_id() ) {
03272                 return;
03273         }
03274 
03275         // PHP's built-in session entropy is enabled if:
03276         // - entropy_file is set or you're on Windows with php 5.3.3+
03277         // - AND entropy_length is > 0
03278         // We treat it as disabled if it doesn't have an entropy length of at least 32
03279         $entropyEnabled = wfCheckEntropy();
03280 
03281         // If built-in entropy is not enabled or not sufficient override php's built in session id generation code
03282         if ( !$entropyEnabled ) {
03283                 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, overriding session id generation using our cryptrand source.\n" );
03284                 session_id( MWCryptRand::generateHex( 32 ) );
03285         }
03286 }
03287 
03293 function wfSetupSession( $sessionId = false ) {
03294         global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
03295                         $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
03296         if( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
03297                 ObjectCacheSessionHandler::install();
03298         } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
03299                 # Only set this if $wgSessionHandler isn't null and session.save_handler
03300                 # hasn't already been set to the desired value (that causes errors)
03301                 ini_set( 'session.save_handler', $wgSessionHandler );
03302         }
03303         $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
03304         wfDebugLog( 'cookie',
03305                 'session_set_cookie_params: "' . implode( '", "',
03306                         array(
03307                                 0,
03308                                 $wgCookiePath,
03309                                 $wgCookieDomain,
03310                                 $wgCookieSecure,
03311                                 $httpOnlySafe ) ) . '"' );
03312         session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
03313         session_cache_limiter( 'private, must-revalidate' );
03314         if ( $sessionId ) {
03315                 session_id( $sessionId );
03316         } else {
03317                 wfFixSessionID();
03318         }
03319         wfSuppressWarnings();
03320         session_start();
03321         wfRestoreWarnings();
03322 }
03323 
03330 function wfGetPrecompiledData( $name ) {
03331         global $IP;
03332 
03333         $file = "$IP/serialized/$name";
03334         if ( file_exists( $file ) ) {
03335                 $blob = file_get_contents( $file );
03336                 if ( $blob ) {
03337                         return unserialize( $blob );
03338                 }
03339         }
03340         return false;
03341 }
03342 
03349 function wfMemcKey( /*... */ ) {
03350         global $wgCachePrefix;
03351         $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
03352         $args = func_get_args();
03353         $key = $prefix . ':' . implode( ':', $args );
03354         $key = str_replace( ' ', '_', $key );
03355         return $key;
03356 }
03357 
03366 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
03367         $args = array_slice( func_get_args(), 2 );
03368         if ( $prefix ) {
03369                 $key = "$db-$prefix:" . implode( ':', $args );
03370         } else {
03371                 $key = $db . ':' . implode( ':', $args );
03372         }
03373         return $key;
03374 }
03375 
03382 function wfWikiID() {
03383         global $wgDBprefix, $wgDBname;
03384         if ( $wgDBprefix ) {
03385                 return "$wgDBname-$wgDBprefix";
03386         } else {
03387                 return $wgDBname;
03388         }
03389 }
03390 
03398 function wfSplitWikiID( $wiki ) {
03399         $bits = explode( '-', $wiki, 2 );
03400         if ( count( $bits ) < 2 ) {
03401                 $bits[] = '';
03402         }
03403         return $bits;
03404 }
03405 
03428 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
03429         return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
03430 }
03431 
03438 function wfGetLB( $wiki = false ) {
03439         return wfGetLBFactory()->getMainLB( $wiki );
03440 }
03441 
03447 function &wfGetLBFactory() {
03448         return LBFactory::singleton();
03449 }
03450 
03471 function wfFindFile( $title, $options = array() ) {
03472         return RepoGroup::singleton()->findFile( $title, $options );
03473 }
03474 
03482 function wfLocalFile( $title ) {
03483         return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
03484 }
03485 
03490 function wfStreamFile( $fname, $headers = array() ) {
03491         wfDeprecated( __FUNCTION__, '1.19' );
03492         StreamFile::stream( $fname, $headers );
03493 }
03494 
03501 function wfQueriesMustScale() {
03502         global $wgMiserMode;
03503         return $wgMiserMode
03504                 || ( SiteStats::pages() > 100000
03505                 && SiteStats::edits() > 1000000
03506                 && SiteStats::users() > 10000 );
03507 }
03508 
03517 function wfScript( $script = 'index' ) {
03518         global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
03519         if ( $script === 'index' ) {
03520                 return $wgScript;
03521         } else if ( $script === 'load' ) {
03522                 return $wgLoadScript;
03523         } else {
03524                 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
03525         }
03526 }
03527 
03533 function wfGetScriptUrl() {
03534         if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
03535                 #
03536                 # as it was called, minus the query string.
03537                 #
03538                 # Some sites use Apache rewrite rules to handle subdomains,
03539                 # and have PHP set up in a weird way that causes PHP_SELF
03540                 # to contain the rewritten URL instead of the one that the
03541                 # outside world sees.
03542                 #
03543                 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
03544                 # provides containing the "before" URL.
03545                 return $_SERVER['SCRIPT_NAME'];
03546         } else {
03547                 return $_SERVER['URL'];
03548         }
03549 }
03550 
03558 function wfBoolToStr( $value ) {
03559         return $value ? 'true' : 'false';
03560 }
03561 
03568 function wfLoadExtensionMessages() {
03569         wfDeprecated( __FUNCTION__, '1.16' );
03570 }
03571 
03577 function wfGetNull() {
03578         return wfIsWindows()
03579                 ? 'NUL'
03580                 : '/dev/null';
03581 }
03582 
03593 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
03594         $lb = wfGetLB( $wiki );
03595         // bug 27975 - Don't try to wait for slaves if there are none
03596         // Prevents permission error when getting master position
03597         if ( $lb->getServerCount() > 1 ) {
03598                 $dbw = $lb->getConnection( DB_MASTER );
03599                 $pos = $dbw->getMasterPos();
03600                 $lb->waitForAll( $pos );
03601         }
03602 }
03603 
03608 function wfOut( $s ) {
03609         wfDeprecated( __FUNCTION__, '1.18' );
03610         global $wgCommandLineMode;
03611         if ( $wgCommandLineMode ) {
03612                 echo $s;
03613         } else {
03614                 echo htmlspecialchars( $s );
03615         }
03616         flush();
03617 }
03618 
03625 function wfCountDown( $n ) {
03626         for ( $i = $n; $i >= 0; $i-- ) {
03627                 if ( $i != $n ) {
03628                         echo str_repeat( "\x08", strlen( $i + 1 ) );
03629                 }
03630                 echo $i;
03631                 flush();
03632                 if ( $i ) {
03633                         sleep( 1 );
03634                 }
03635         }
03636         echo "\n";
03637 }
03638 
03648 function wfGenerateToken( $salt = '' ) {
03649         wfDeprecated( __METHOD__, '1.20' );
03650         $salt = serialize( $salt );
03651         return md5( mt_rand( 0, 0x7fffffff ) . $salt );
03652 }
03653 
03662 function wfStripIllegalFilenameChars( $name ) {
03663         global $wgIllegalFileChars;
03664         $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
03665         $name = wfBaseName( $name );
03666         $name = preg_replace(
03667                 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
03668                 '-',
03669                 $name
03670         );
03671         return $name;
03672 }
03673 
03679 function wfMemoryLimit() {
03680         global $wgMemoryLimit;
03681         $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
03682         if( $memlimit != -1 ) {
03683                 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
03684                 if( $conflimit == -1 ) {
03685                         wfDebug( "Removing PHP's memory limit\n" );
03686                         wfSuppressWarnings();
03687                         ini_set( 'memory_limit', $conflimit );
03688                         wfRestoreWarnings();
03689                         return $conflimit;
03690                 } elseif ( $conflimit > $memlimit ) {
03691                         wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
03692                         wfSuppressWarnings();
03693                         ini_set( 'memory_limit', $conflimit );
03694                         wfRestoreWarnings();
03695                         return $conflimit;
03696                 }
03697         }
03698         return $memlimit;
03699 }
03700 
03707 function wfShorthandToInteger( $string = '' ) {
03708         $string = trim( $string );
03709         if( $string === '' ) {
03710                 return -1;
03711         }
03712         $last = $string[strlen( $string ) - 1];
03713         $val = intval( $string );
03714         switch( $last ) {
03715                 case 'g':
03716                 case 'G':
03717                         $val *= 1024;
03718                         // break intentionally missing
03719                 case 'm':
03720                 case 'M':
03721                         $val *= 1024;
03722                         // break intentionally missing
03723                 case 'k':
03724                 case 'K':
03725                         $val *= 1024;
03726         }
03727 
03728         return $val;
03729 }
03730 
03738 function wfBCP47( $code ) {
03739         $codeSegment = explode( '-', $code );
03740         $codeBCP = array();
03741         foreach ( $codeSegment as $segNo => $seg ) {
03742                 if ( count( $codeSegment ) > 0 ) {
03743                         // when previous segment is x, it is a private segment and should be lc
03744                         if( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
03745                                 $codeBCP[$segNo] = strtolower( $seg );
03746                         // ISO 3166 country code
03747                         } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
03748                                 $codeBCP[$segNo] = strtoupper( $seg );
03749                         // ISO 15924 script code
03750                         } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
03751                                 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
03752                         // Use lowercase for other cases
03753                         } else {
03754                                 $codeBCP[$segNo] = strtolower( $seg );
03755                         }
03756                 } else {
03757                 // Use lowercase for single segment
03758                         $codeBCP[$segNo] = strtolower( $seg );
03759                 }
03760         }
03761         $langCode = implode( '-', $codeBCP );
03762         return $langCode;
03763 }
03764 
03771 function wfGetCache( $inputType ) {
03772         return ObjectCache::getInstance( $inputType );
03773 }
03774 
03780 function wfGetMainCache() {
03781         global $wgMainCacheType;
03782         return ObjectCache::getInstance( $wgMainCacheType );
03783 }
03784 
03790 function wfGetMessageCacheStorage() {
03791         global $wgMessageCacheType;
03792         return ObjectCache::getInstance( $wgMessageCacheType );
03793 }
03794 
03800 function wfGetParserCacheStorage() {
03801         global $wgParserCacheType;
03802         return ObjectCache::getInstance( $wgParserCacheType );
03803 }
03804 
03810 function wfGetLangConverterCacheStorage() {
03811         global $wgLanguageConverterCacheType;
03812         return ObjectCache::getInstance( $wgLanguageConverterCacheType );
03813 }
03814 
03822 function wfRunHooks( $event, $args = array() ) {
03823         return Hooks::run( $event, $args );
03824 }
03825 
03840 function wfUnpack( $format, $data, $length=false ) {
03841         if ( $length !== false ) {
03842                 $realLen = strlen( $data );
03843                 if ( $realLen < $length ) {
03844                         throw new MWException( "Tried to use wfUnpack on a "
03845                                 . "string of length $realLen, but needed one "
03846                                 . "of at least length $length."
03847                         );
03848                 }
03849         }
03850 
03851         wfSuppressWarnings();
03852         $result = unpack( $format, $data );
03853         wfRestoreWarnings();
03854 
03855         if ( $result === false ) {
03856                 // If it cannot extract the packed data.
03857                 throw new MWException( "unpack could not unpack binary data" );
03858         }
03859         return $result;
03860 }
03861 
03876 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
03877         static $badImageCache = null; // based on bad_image_list msg
03878         wfProfileIn( __METHOD__ );
03879 
03880         # Handle redirects
03881         $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
03882         if( $redirectTitle ) {
03883                 $name = $redirectTitle->getDbKey();
03884         }
03885 
03886         # Run the extension hook
03887         $bad = false;
03888         if( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
03889                 wfProfileOut( __METHOD__ );
03890                 return $bad;
03891         }
03892 
03893         $cacheable = ( $blacklist === null );
03894         if( $cacheable && $badImageCache !== null ) {
03895                 $badImages = $badImageCache;
03896         } else { // cache miss
03897                 if ( $blacklist === null ) {
03898                         $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
03899                 }
03900                 # Build the list now
03901                 $badImages = array();
03902                 $lines = explode( "\n", $blacklist );
03903                 foreach( $lines as $line ) {
03904                         # List items only
03905                         if ( substr( $line, 0, 1 ) !== '*' ) {
03906                                 continue;
03907                         }
03908 
03909                         # Find all links
03910                         $m = array();
03911                         if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
03912                                 continue;
03913                         }
03914 
03915                         $exceptions = array();
03916                         $imageDBkey = false;
03917                         foreach ( $m[1] as $i => $titleText ) {
03918                                 $title = Title::newFromText( $titleText );
03919                                 if ( !is_null( $title ) ) {
03920                                         if ( $i == 0 ) {
03921                                                 $imageDBkey = $title->getDBkey();
03922                                         } else {
03923                                                 $exceptions[$title->getPrefixedDBkey()] = true;
03924                                         }
03925                                 }
03926                         }
03927 
03928                         if ( $imageDBkey !== false ) {
03929                                 $badImages[$imageDBkey] = $exceptions;
03930                         }
03931                 }
03932                 if ( $cacheable ) {
03933                         $badImageCache = $badImages;
03934                 }
03935         }
03936 
03937         $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
03938         $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
03939         wfProfileOut( __METHOD__ );
03940         return $bad;
03941 }