MediaWiki  REL1_21
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 // Support for Wietse Venema's taint feature
00098 if ( !function_exists( 'istainted' ) ) {
00103         function istainted( $var ) {
00104                 return 0;
00105         }
00107         function taint( $var, $level = 0 ) {}
00109         function untaint( $var, $level = 0 ) {}
00110         define( 'TC_HTML', 1 );
00111         define( 'TC_SHELL', 1 );
00112         define( 'TC_MYSQL', 1 );
00113         define( 'TC_PCRE', 1 );
00114         define( 'TC_SELF', 1 );
00115 }
00117 
00124 function wfArrayDiff2( $a, $b ) {
00125         return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
00126 }
00127 
00133 function wfArrayDiff2_cmp( $a, $b ) {
00134         if ( !is_array( $a ) ) {
00135                 return strcmp( $a, $b );
00136         } elseif ( count( $a ) !== count( $b ) ) {
00137                 return count( $a ) < count( $b ) ? -1 : 1;
00138         } else {
00139                 reset( $a );
00140                 reset( $b );
00141                 while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
00142                         $cmp = strcmp( $valueA, $valueB );
00143                         if ( $cmp !== 0 ) {
00144                                 return $cmp;
00145                         }
00146                 }
00147                 return 0;
00148         }
00149 }
00150 
00160 function wfArrayLookup( $a, $b ) {
00161         return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
00162 }
00163 
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                 // bug 45069
00812                 if ( isset( $bits['path'] ) ) {
00813                         /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
00814                         if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
00815                                 $bits['path'] = '/' . $bits['path'];
00816                         }
00817                 } else {
00818                         $bits['path'] = '';
00819                 }
00820         }
00821 
00822         // If the URL was protocol-relative, fix scheme and delimiter
00823         if ( $wasRelative ) {
00824                 $bits['scheme'] = '';
00825                 $bits['delimiter'] = '//';
00826         }
00827         return $bits;
00828 }
00829 
00840 function wfExpandIRI( $url ) {
00841         return preg_replace_callback( '/((?:%[89A-F][0-9A-F])+)/i', 'wfExpandIRI_callback', wfExpandUrl( $url ) );
00842 }
00843 
00849 function wfExpandIRI_callback( $matches ) {
00850         return urldecode( $matches[1] );
00851 }
00852 
00859 function wfMakeUrlIndexes( $url ) {
00860         $bits = wfParseUrl( $url );
00861 
00862         // Reverse the labels in the hostname, convert to lower case
00863         // For emails reverse domainpart only
00864         if ( $bits['scheme'] == 'mailto' ) {
00865                 $mailparts = explode( '@', $bits['host'], 2 );
00866                 if ( count( $mailparts ) === 2 ) {
00867                         $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
00868                 } else {
00869                         // No domain specified, don't mangle it
00870                         $domainpart = '';
00871                 }
00872                 $reversedHost = $domainpart . '@' . $mailparts[0];
00873         } else {
00874                 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
00875         }
00876         // Add an extra dot to the end
00877         // Why? Is it in wrong place in mailto links?
00878         if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
00879                 $reversedHost .= '.';
00880         }
00881         // Reconstruct the pseudo-URL
00882         $prot = $bits['scheme'];
00883         $index = $prot . $bits['delimiter'] . $reversedHost;
00884         // Leave out user and password. Add the port, path, query and fragment
00885         if ( isset( $bits['port'] ) ) {
00886                 $index .= ':' . $bits['port'];
00887         }
00888         if ( isset( $bits['path'] ) ) {
00889                 $index .= $bits['path'];
00890         } else {
00891                 $index .= '/';
00892         }
00893         if ( isset( $bits['query'] ) ) {
00894                 $index .= '?' . $bits['query'];
00895         }
00896         if ( isset( $bits['fragment'] ) ) {
00897                 $index .= '#' . $bits['fragment'];
00898         }
00899 
00900         if ( $prot == '' ) {
00901                 return array( "http:$index", "https:$index" );
00902         } else {
00903                 return array( $index );
00904         }
00905 }
00906 
00913 function wfMatchesDomainList( $url, $domains ) {
00914         $bits = wfParseUrl( $url );
00915         if ( is_array( $bits ) && isset( $bits['host'] ) ) {
00916                 foreach ( (array)$domains as $domain ) {
00917                         // FIXME: This gives false positives. http://nds-nl.wikipedia.org will match nl.wikipedia.org
00918                         // We should use something that interprets dots instead
00919                         if ( substr( $bits['host'], -strlen( $domain ) ) === $domain ) {
00920                                 return true;
00921                         }
00922                 }
00923         }
00924         return false;
00925 }
00926 
00940 function wfDebug( $text, $logonly = false ) {
00941         global $wgDebugLogFile, $wgProfileOnly, $wgDebugRawPage, $wgDebugLogPrefix;
00942 
00943         if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
00944                 return;
00945         }
00946 
00947         $timer = wfDebugTimer();
00948         if ( $timer !== '' ) {
00949                 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
00950         }
00951 
00952         if ( !$logonly ) {
00953                 MWDebug::debugMsg( $text );
00954         }
00955 
00956         if ( wfRunHooks( 'Debug', array( $text, null /* no log group */ ) ) ) {
00957                 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
00958                         # Strip unprintables; they can switch terminal modes when binary data
00959                         # gets dumped, which is pretty annoying.
00960                         $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
00961                         $text = $wgDebugLogPrefix . $text;
00962                         wfErrorLog( $text, $wgDebugLogFile );
00963                 }
00964         }
00965 }
00966 
00971 function wfIsDebugRawPage() {
00972         static $cache;
00973         if ( $cache !== null ) {
00974                 return $cache;
00975         }
00976         # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
00977         if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
00978                 || (
00979                         isset( $_SERVER['SCRIPT_NAME'] )
00980                         && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
00981                 ) )
00982         {
00983                 $cache = true;
00984         } else {
00985                 $cache = false;
00986         }
00987         return $cache;
00988 }
00989 
00995 function wfDebugTimer() {
00996         global $wgDebugTimestamps, $wgRequestTime;
00997 
00998         if ( !$wgDebugTimestamps ) {
00999                 return '';
01000         }
01001 
01002         $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
01003         $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
01004         return "$prefix $mem  ";
01005 }
01006 
01012 function wfDebugMem( $exact = false ) {
01013         $mem = memory_get_usage();
01014         if( !$exact ) {
01015                 $mem = floor( $mem / 1024 ) . ' kilobytes';
01016         } else {
01017                 $mem .= ' bytes';
01018         }
01019         wfDebug( "Memory usage: $mem\n" );
01020 }
01021 
01031 function wfDebugLog( $logGroup, $text, $public = true ) {
01032         global $wgDebugLogGroups;
01033         $text = trim( $text ) . "\n";
01034         if( isset( $wgDebugLogGroups[$logGroup] ) ) {
01035                 $time = wfTimestamp( TS_DB );
01036                 $wiki = wfWikiID();
01037                 $host = wfHostname();
01038                 if ( wfRunHooks( 'Debug', array( $text, $logGroup ) ) ) {
01039                         wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
01040                 }
01041         } elseif ( $public === true ) {
01042                 wfDebug( "[$logGroup] $text", true );
01043         }
01044 }
01045 
01051 function wfLogDBError( $text ) {
01052         global $wgDBerrorLog, $wgDBerrorLogTZ;
01053         static $logDBErrorTimeZoneObject = null;
01054 
01055         if ( $wgDBerrorLog ) {
01056                 $host = wfHostname();
01057                 $wiki = wfWikiID();
01058 
01059                 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
01060                         $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
01061                 }
01062 
01063                 // Workaround for https://bugs.php.net/bug.php?id=52063
01064                 // Can be removed when min PHP > 5.3.2
01065                 if ( $logDBErrorTimeZoneObject === null ) {
01066                         $d = date_create( "now" );
01067                 } else {
01068                         $d = date_create( "now", $logDBErrorTimeZoneObject );
01069                 }
01070 
01071                 $date = $d->format( 'D M j G:i:s T Y' );
01072 
01073                 $text = "$date\t$host\t$wiki\t$text";
01074                 wfErrorLog( $text, $wgDBerrorLog );
01075         }
01076 }
01077 
01090 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
01091         MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
01092 }
01093 
01104 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
01105         MWDebug::warning( $msg, $callerOffset + 1, $level );
01106 }
01107 
01118 function wfErrorLog( $text, $file ) {
01119         if ( substr( $file, 0, 4 ) == 'udp:' ) {
01120                 # Needs the sockets extension
01121                 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
01122                         // IPv6 bracketed host
01123                         $host = $m[2];
01124                         $port = intval( $m[3] );
01125                         $prefix = isset( $m[4] ) ? $m[4] : false;
01126                         $domain = AF_INET6;
01127                 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
01128                         $host = $m[2];
01129                         if ( !IP::isIPv4( $host ) ) {
01130                                 $host = gethostbyname( $host );
01131                         }
01132                         $port = intval( $m[3] );
01133                         $prefix = isset( $m[4] ) ? $m[4] : false;
01134                         $domain = AF_INET;
01135                 } else {
01136                         throw new MWException( __METHOD__ . ': Invalid UDP specification' );
01137                 }
01138 
01139                 // Clean it up for the multiplexer
01140                 if ( strval( $prefix ) !== '' ) {
01141                         $text = preg_replace( '/^/m', $prefix . ' ', $text );
01142 
01143                         // Limit to 64KB
01144                         if ( strlen( $text ) > 65506 ) {
01145                                 $text = substr( $text, 0, 65506 );
01146                         }
01147 
01148                         if ( substr( $text, -1 ) != "\n" ) {
01149                                 $text .= "\n";
01150                         }
01151                 } elseif ( strlen( $text ) > 65507 ) {
01152                         $text = substr( $text, 0, 65507 );
01153                 }
01154 
01155                 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
01156                 if ( !$sock ) {
01157                         return;
01158                 }
01159 
01160                 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
01161                 socket_close( $sock );
01162         } else {
01163                 wfSuppressWarnings();
01164                 $exists = file_exists( $file );
01165                 $size = $exists ? filesize( $file ) : false;
01166                 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
01167                         file_put_contents( $file, $text, FILE_APPEND );
01168                 }
01169                 wfRestoreWarnings();
01170         }
01171 }
01172 
01176 function wfLogProfilingData() {
01177         global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
01178         global $wgProfileLimit, $wgUser;
01179 
01180         $profiler = Profiler::instance();
01181 
01182         # Profiling must actually be enabled...
01183         if ( $profiler->isStub() ) {
01184                 return;
01185         }
01186 
01187         // Get total page request time and only show pages that longer than
01188         // $wgProfileLimit time (default is 0)
01189         $elapsed = microtime( true ) - $wgRequestTime;
01190         if ( $elapsed <= $wgProfileLimit ) {
01191                 return;
01192         }
01193 
01194         $profiler->logData();
01195 
01196         // Check whether this should be logged in the debug file.
01197         if ( $wgDebugLogFile == '' || ( !$wgDebugRawPage && wfIsDebugRawPage() ) ) {
01198                 return;
01199         }
01200 
01201         $forward = '';
01202         if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
01203                 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
01204         }
01205         if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
01206                 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
01207         }
01208         if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
01209                 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
01210         }
01211         if ( $forward ) {
01212                 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
01213         }
01214         // Don't load $wgUser at this late stage just for statistics purposes
01215         // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
01216         if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
01217                 $forward .= ' anon';
01218         }
01219 
01220         // Command line script uses a FauxRequest object which does not have
01221         // any knowledge about an URL and throw an exception instead.
01222         try {
01223                 $requestUrl = $wgRequest->getRequestURL();
01224         } catch ( MWException $e ) {
01225                 $requestUrl = 'n/a';
01226         }
01227 
01228         $log = sprintf( "%s\t%04.3f\t%s\n",
01229                 gmdate( 'YmdHis' ), $elapsed,
01230                 urldecode( $requestUrl . $forward ) );
01231 
01232         wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
01233 }
01234 
01242 function wfIncrStats( $key, $count = 1 ) {
01243         global $wgStatsMethod;
01244 
01245         $count = intval( $count );
01246         if ( $count == 0 ) {
01247                 return;
01248         }
01249 
01250         if( $wgStatsMethod == 'udp' ) {
01251                 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgAggregateStatsID;
01252                 static $socket;
01253 
01254                 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : wfWikiID();
01255 
01256                 if ( !$socket ) {
01257                         $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
01258                         $statline = "stats/{$id} - 1 1 1 1 1 -total\n";
01259                         socket_sendto(
01260                                 $socket,
01261                                 $statline,
01262                                 strlen( $statline ),
01263                                 0,
01264                                 $wgUDPProfilerHost,
01265                                 $wgUDPProfilerPort
01266                         );
01267                 }
01268                 $statline = "stats/{$id} - {$count} 1 1 1 1 {$key}\n";
01269                 wfSuppressWarnings();
01270                 socket_sendto(
01271                         $socket,
01272                         $statline,
01273                         strlen( $statline ),
01274                         0,
01275                         $wgUDPProfilerHost,
01276                         $wgUDPProfilerPort
01277                 );
01278                 wfRestoreWarnings();
01279         } elseif( $wgStatsMethod == 'cache' ) {
01280                 global $wgMemc;
01281                 $key = wfMemcKey( 'stats', $key );
01282                 if ( is_null( $wgMemc->incr( $key, $count ) ) ) {
01283                         $wgMemc->add( $key, $count );
01284                 }
01285         } else {
01286                 // Disabled
01287         }
01288 }
01289 
01297 function wfReadOnly() {
01298         global $wgReadOnlyFile, $wgReadOnly;
01299 
01300         if ( !is_null( $wgReadOnly ) ) {
01301                 return (bool)$wgReadOnly;
01302         }
01303         if ( $wgReadOnlyFile == '' ) {
01304                 return false;
01305         }
01306         // Set $wgReadOnly for faster access next time
01307         if ( is_file( $wgReadOnlyFile ) ) {
01308                 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
01309         } else {
01310                 $wgReadOnly = false;
01311         }
01312         return (bool)$wgReadOnly;
01313 }
01314 
01318 function wfReadOnlyReason() {
01319         global $wgReadOnly;
01320         wfReadOnly();
01321         return $wgReadOnly;
01322 }
01323 
01339 function wfGetLangObj( $langcode = false ) {
01340         # Identify which language to get or create a language object for.
01341         # Using is_object here due to Stub objects.
01342         if( is_object( $langcode ) ) {
01343                 # Great, we already have the object (hopefully)!
01344                 return $langcode;
01345         }
01346 
01347         global $wgContLang, $wgLanguageCode;
01348         if( $langcode === true || $langcode === $wgLanguageCode ) {
01349                 # $langcode is the language code of the wikis content language object.
01350                 # or it is a boolean and value is true
01351                 return $wgContLang;
01352         }
01353 
01354         global $wgLang;
01355         if( $langcode === false || $langcode === $wgLang->getCode() ) {
01356                 # $langcode is the language code of user language object.
01357                 # or it was a boolean and value is false
01358                 return $wgLang;
01359         }
01360 
01361         $validCodes = array_keys( Language::fetchLanguageNames() );
01362         if( in_array( $langcode, $validCodes ) ) {
01363                 # $langcode corresponds to a valid language.
01364                 return Language::factory( $langcode );
01365         }
01366 
01367         # $langcode is a string, but not a valid language code; use content language.
01368         wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
01369         return $wgContLang;
01370 }
01371 
01379 function wfUILang() {
01380         wfDeprecated( __METHOD__, '1.18' );
01381         global $wgLang;
01382         return $wgLang;
01383 }
01384 
01398 function wfMessage( $key /*...*/) {
01399         $params = func_get_args();
01400         array_shift( $params );
01401         if ( isset( $params[0] ) && is_array( $params[0] ) ) {
01402                 $params = $params[0];
01403         }
01404         return new Message( $key, $params );
01405 }
01406 
01415 function wfMessageFallback( /*...*/ ) {
01416         $args = func_get_args();
01417         return MWFunction::callArray( 'Message::newFallbackSequence', $args );
01418 }
01419 
01439 function wfMsg( $key ) {
01440         wfDeprecated( __METHOD__, '1.21' );
01441 
01442         $args = func_get_args();
01443         array_shift( $args );
01444         return wfMsgReal( $key, $args );
01445 }
01446 
01455 function wfMsgNoTrans( $key ) {
01456         wfDeprecated( __METHOD__, '1.21' );
01457 
01458         $args = func_get_args();
01459         array_shift( $args );
01460         return wfMsgReal( $key, $args, true, false, false );
01461 }
01462 
01488 function wfMsgForContent( $key ) {
01489         wfDeprecated( __METHOD__, '1.21' );
01490 
01491         global $wgForceUIMsgAsContentMsg;
01492         $args = func_get_args();
01493         array_shift( $args );
01494         $forcontent = true;
01495         if( is_array( $wgForceUIMsgAsContentMsg ) &&
01496                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
01497         {
01498                 $forcontent = false;
01499         }
01500         return wfMsgReal( $key, $args, true, $forcontent );
01501 }
01502 
01511 function wfMsgForContentNoTrans( $key ) {
01512         wfDeprecated( __METHOD__, '1.21' );
01513 
01514         global $wgForceUIMsgAsContentMsg;
01515         $args = func_get_args();
01516         array_shift( $args );
01517         $forcontent = true;
01518         if( is_array( $wgForceUIMsgAsContentMsg ) &&
01519                 in_array( $key, $wgForceUIMsgAsContentMsg ) )
01520         {
01521                 $forcontent = false;
01522         }
01523         return wfMsgReal( $key, $args, true, $forcontent, false );
01524 }
01525 
01538 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
01539         wfDeprecated( __METHOD__, '1.21' );
01540 
01541         wfProfileIn( __METHOD__ );
01542         $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
01543         $message = wfMsgReplaceArgs( $message, $args );
01544         wfProfileOut( __METHOD__ );
01545         return $message;
01546 }
01547 
01560 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
01561         wfDeprecated( __METHOD__, '1.21' );
01562 
01563         wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
01564 
01565         $cache = MessageCache::singleton();
01566         $message = $cache->get( $key, $useDB, $langCode );
01567         if( $message === false ) {
01568                 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
01569         } elseif ( $transform ) {
01570                 $message = $cache->transform( $message );
01571         }
01572         return $message;
01573 }
01574 
01583 function wfMsgReplaceArgs( $message, $args ) {
01584         # Fix windows line-endings
01585         # Some messages are split with explode("\n", $msg)
01586         $message = str_replace( "\r", '', $message );
01587 
01588         // Replace arguments
01589         if ( count( $args ) ) {
01590                 if ( is_array( $args[0] ) ) {
01591                         $args = array_values( $args[0] );
01592                 }
01593                 $replacementKeys = array();
01594                 foreach( $args as $n => $param ) {
01595                         $replacementKeys['$' . ( $n + 1 )] = $param;
01596                 }
01597                 $message = strtr( $message, $replacementKeys );
01598         }
01599 
01600         return $message;
01601 }
01602 
01616 function wfMsgHtml( $key ) {
01617         wfDeprecated( __METHOD__, '1.21' );
01618 
01619         $args = func_get_args();
01620         array_shift( $args );
01621         return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
01622 }
01623 
01637 function wfMsgWikiHtml( $key ) {
01638         wfDeprecated( __METHOD__, '1.21' );
01639 
01640         $args = func_get_args();
01641         array_shift( $args );
01642         return wfMsgReplaceArgs(
01643                 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
01644                 /* can't be set to false */ true, /* interface */ true )->getText(),
01645                 $args );
01646 }
01647 
01670 function wfMsgExt( $key, $options ) {
01671         wfDeprecated( __METHOD__, '1.21' );
01672 
01673         $args = func_get_args();
01674         array_shift( $args );
01675         array_shift( $args );
01676         $options = (array)$options;
01677 
01678         foreach( $options as $arrayKey => $option ) {
01679                 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
01680                         # An unknown index, neither numeric nor "language"
01681                         wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
01682                 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
01683                 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
01684                 'replaceafter', 'parsemag', 'content' ) ) ) {
01685                         # A numeric index with unknown value
01686                         wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
01687                 }
01688         }
01689 
01690         if( in_array( 'content', $options, true ) ) {
01691                 $forContent = true;
01692                 $langCode = true;
01693                 $langCodeObj = null;
01694         } elseif( array_key_exists( 'language', $options ) ) {
01695                 $forContent = false;
01696                 $langCode = wfGetLangObj( $options['language'] );
01697                 $langCodeObj = $langCode;
01698         } else {
01699                 $forContent = false;
01700                 $langCode = false;
01701                 $langCodeObj = null;
01702         }
01703 
01704         $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
01705 
01706         if( !in_array( 'replaceafter', $options, true ) ) {
01707                 $string = wfMsgReplaceArgs( $string, $args );
01708         }
01709 
01710         $messageCache = MessageCache::singleton();
01711         $parseInline = in_array( 'parseinline', $options, true );
01712         if( in_array( 'parse', $options, true ) || $parseInline ) {
01713                 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
01714                 if ( $string instanceof ParserOutput ) {
01715                         $string = $string->getText();
01716                 }
01717 
01718                 if ( $parseInline ) {
01719                         $m = array();
01720                         if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
01721                                 $string = $m[1];
01722                         }
01723                 }
01724         } elseif ( in_array( 'parsemag', $options, true ) ) {
01725                 $string = $messageCache->transform( $string,
01726                                 !$forContent, $langCodeObj );
01727         }
01728 
01729         if ( in_array( 'escape', $options, true ) ) {
01730                 $string = htmlspecialchars ( $string );
01731         } elseif ( in_array( 'escapenoentities', $options, true ) ) {
01732                 $string = Sanitizer::escapeHtmlAllowEntities( $string );
01733         }
01734 
01735         if( in_array( 'replaceafter', $options, true ) ) {
01736                 $string = wfMsgReplaceArgs( $string, $args );
01737         }
01738 
01739         return $string;
01740 }
01741 
01752 function wfEmptyMsg( $key ) {
01753         wfDeprecated( __METHOD__, '1.21' );
01754 
01755         return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
01756 }
01757 
01765 function wfDebugDieBacktrace( $msg = '' ) {
01766         throw new MWException( $msg );
01767 }
01768 
01776 function wfHostname() {
01777         static $host;
01778         if ( is_null( $host ) ) {
01779 
01780                 # Hostname overriding
01781                 global $wgOverrideHostname;
01782                 if( $wgOverrideHostname !== false ) {
01783                         # Set static and skip any detection
01784                         $host = $wgOverrideHostname;
01785                         return $host;
01786                 }
01787 
01788                 if ( function_exists( 'posix_uname' ) ) {
01789                         // This function not present on Windows
01790                         $uname = posix_uname();
01791                 } else {
01792                         $uname = false;
01793                 }
01794                 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
01795                         $host = $uname['nodename'];
01796                 } elseif ( getenv( 'COMPUTERNAME' ) ) {
01797                         # Windows computer name
01798                         $host = getenv( 'COMPUTERNAME' );
01799                 } else {
01800                         # This may be a virtual server.
01801                         $host = $_SERVER['SERVER_NAME'];
01802                 }
01803         }
01804         return $host;
01805 }
01806 
01813 function wfReportTime() {
01814         global $wgRequestTime, $wgShowHostnames;
01815 
01816         $elapsed = microtime( true ) - $wgRequestTime;
01817 
01818         return $wgShowHostnames
01819                 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
01820                 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
01821 }
01822 
01838 function wfDebugBacktrace( $limit = 0 ) {
01839         static $disabled = null;
01840 
01841         if( extension_loaded( 'Zend Optimizer' ) ) {
01842                 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
01843                 return array();
01844         }
01845 
01846         if ( is_null( $disabled ) ) {
01847                 $disabled = false;
01848                 $functions = explode( ',', ini_get( 'disable_functions' ) );
01849                 $functions = array_map( 'trim', $functions );
01850                 $functions = array_map( 'strtolower', $functions );
01851                 if ( in_array( 'debug_backtrace', $functions ) ) {
01852                         wfDebug( "debug_backtrace is in disabled_functions\n" );
01853                         $disabled = true;
01854                 }
01855         }
01856         if ( $disabled ) {
01857                 return array();
01858         }
01859 
01860         if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
01861                 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
01862         } else {
01863                 return array_slice( debug_backtrace(), 1 );
01864         }
01865 }
01866 
01872 function wfBacktrace() {
01873         global $wgCommandLineMode;
01874 
01875         if ( $wgCommandLineMode ) {
01876                 $msg = '';
01877         } else {
01878                 $msg = "<ul>\n";
01879         }
01880         $backtrace = wfDebugBacktrace();
01881         foreach( $backtrace as $call ) {
01882                 if( isset( $call['file'] ) ) {
01883                         $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
01884                         $file = $f[count( $f ) - 1];
01885                 } else {
01886                         $file = '-';
01887                 }
01888                 if( isset( $call['line'] ) ) {
01889                         $line = $call['line'];
01890                 } else {
01891                         $line = '-';
01892                 }
01893                 if ( $wgCommandLineMode ) {
01894                         $msg .= "$file line $line calls ";
01895                 } else {
01896                         $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
01897                 }
01898                 if( !empty( $call['class'] ) ) {
01899                         $msg .= $call['class'] . $call['type'];
01900                 }
01901                 $msg .= $call['function'] . '()';
01902 
01903                 if ( $wgCommandLineMode ) {
01904                         $msg .= "\n";
01905                 } else {
01906                         $msg .= "</li>\n";
01907                 }
01908         }
01909         if ( $wgCommandLineMode ) {
01910                 $msg .= "\n";
01911         } else {
01912                 $msg .= "</ul>\n";
01913         }
01914 
01915         return $msg;
01916 }
01917 
01927 function wfGetCaller( $level = 2 ) {
01928         $backtrace = wfDebugBacktrace( $level + 1 );
01929         if ( isset( $backtrace[$level] ) ) {
01930                 return wfFormatStackFrame( $backtrace[$level] );
01931         } else {
01932                 return 'unknown';
01933         }
01934 }
01935 
01944 function wfGetAllCallers( $limit = 3 ) {
01945         $trace = array_reverse( wfDebugBacktrace() );
01946         if ( !$limit || $limit > count( $trace ) - 1 ) {
01947                 $limit = count( $trace ) - 1;
01948         }
01949         $trace = array_slice( $trace, -$limit - 1, $limit );
01950         return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
01951 }
01952 
01959 function wfFormatStackFrame( $frame ) {
01960         return isset( $frame['class'] ) ?
01961                 $frame['class'] . '::' . $frame['function'] :
01962                 $frame['function'];
01963 }
01964 
01965 /* Some generic result counters, pulled out of SearchEngine */
01966 
01974 function wfShowingResults( $offset, $limit ) {
01975         return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
01976 }
01977 
01989 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
01990         wfDeprecated( __METHOD__, '1.19' );
01991 
01992         global $wgLang;
01993 
01994         $query = wfCgiToArray( $query );
01995 
01996         if( is_object( $link ) ) {
01997                 $title = $link;
01998         } else {
01999                 $title = Title::newFromText( $link );
02000                 if( is_null( $title ) ) {
02001                         return false;
02002                 }
02003         }
02004 
02005         return $wgLang->viewPrevNext( $title, $offset, $limit, $query, $atend );
02006 }
02007 
02018 function wfSpecialList( $page, $details, $oppositedm = true ) {
02019         wfDeprecated( __METHOD__, '1.19' );
02020 
02021         global $wgLang;
02022         return $wgLang->specialList( $page, $details, $oppositedm );
02023 }
02024 
02032 function wfClientAcceptsGzip( $force = false ) {
02033         static $result = null;
02034         if ( $result === null || $force ) {
02035                 $result = false;
02036                 if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
02037                         # @todo FIXME: We may want to blacklist some broken browsers
02038                         $m = array();
02039                         if( preg_match(
02040                                 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
02041                                 $_SERVER['HTTP_ACCEPT_ENCODING'],
02042                                 $m )
02043                         )
02044                         {
02045                                 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
02046                                         $result = false;
02047                                         return $result;
02048                                 }
02049                                 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
02050                                 $result = true;
02051                         }
02052                 }
02053         }
02054         return $result;
02055 }
02056 
02066 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
02067         global $wgRequest;
02068         return $wgRequest->getLimitOffset( $deflimit, $optionname );
02069 }
02070 
02080 function wfEscapeWikiText( $text ) {
02081         $text = strtr( "\n$text", array(
02082                 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
02083                 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
02084                 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
02085                 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
02086                 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
02087                 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
02088         ) );
02089         return substr( $text, 1 );
02090 }
02091 
02096 function wfTime() {
02097         return microtime( true );
02098 }
02099 
02110 function wfSetVar( &$dest, $source, $force = false ) {
02111         $temp = $dest;
02112         if ( !is_null( $source ) || $force ) {
02113                 $dest = $source;
02114         }
02115         return $temp;
02116 }
02117 
02127 function wfSetBit( &$dest, $bit, $state = true ) {
02128         $temp = (bool)( $dest & $bit );
02129         if ( !is_null( $state ) ) {
02130                 if ( $state ) {
02131                         $dest |= $bit;
02132                 } else {
02133                         $dest &= ~$bit;
02134                 }
02135         }
02136         return $temp;
02137 }
02138 
02145 function wfVarDump( $var ) {
02146         global $wgOut;
02147         $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
02148         if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
02149                 print $s;
02150         } else {
02151                 $wgOut->addHTML( $s );
02152         }
02153 }
02154 
02162 function wfHttpError( $code, $label, $desc ) {
02163         global $wgOut;
02164         $wgOut->disable();
02165         header( "HTTP/1.0 $code $label" );
02166         header( "Status: $code $label" );
02167         $wgOut->sendCacheControl();
02168 
02169         header( 'Content-type: text/html; charset=utf-8' );
02170         print "<!doctype html>" .
02171                 '<html><head><title>' .
02172                 htmlspecialchars( $label ) .
02173                 '</title></head><body><h1>' .
02174                 htmlspecialchars( $label ) .
02175                 '</h1><p>' .
02176                 nl2br( htmlspecialchars( $desc ) ) .
02177                 "</p></body></html>\n";
02178 }
02179 
02197 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
02198         if( $resetGzipEncoding ) {
02199                 // Suppress Content-Encoding and Content-Length
02200                 // headers from 1.10+s wfOutputHandler
02201                 global $wgDisableOutputCompression;
02202                 $wgDisableOutputCompression = true;
02203         }
02204         while( $status = ob_get_status() ) {
02205                 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
02206                         // Probably from zlib.output_compression or other
02207                         // PHP-internal setting which can't be removed.
02208                         //
02209                         // Give up, and hope the result doesn't break
02210                         // output behavior.
02211                         break;
02212                 }
02213                 if( !ob_end_clean() ) {
02214                         // Could not remove output buffer handler; abort now
02215                         // to avoid getting in some kind of infinite loop.
02216                         break;
02217                 }
02218                 if( $resetGzipEncoding ) {
02219                         if( $status['name'] == 'ob_gzhandler' ) {
02220                                 // Reset the 'Content-Encoding' field set by this handler
02221                                 // so we can start fresh.
02222                                 header_remove( 'Content-Encoding' );
02223                                 break;
02224                         }
02225                 }
02226         }
02227 }
02228 
02241 function wfClearOutputBuffers() {
02242         wfResetOutputBuffers( false );
02243 }
02244 
02253 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
02254         # No arg means accept anything (per HTTP spec)
02255         if( !$accept ) {
02256                 return array( $def => 1.0 );
02257         }
02258 
02259         $prefs = array();
02260 
02261         $parts = explode( ',', $accept );
02262 
02263         foreach( $parts as $part ) {
02264                 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
02265                 $values = explode( ';', trim( $part ) );
02266                 $match = array();
02267                 if ( count( $values ) == 1 ) {
02268                         $prefs[$values[0]] = 1.0;
02269                 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
02270                         $prefs[$values[0]] = floatval( $match[1] );
02271                 }
02272         }
02273 
02274         return $prefs;
02275 }
02276 
02289 function mimeTypeMatch( $type, $avail ) {
02290         if( array_key_exists( $type, $avail ) ) {
02291                 return $type;
02292         } else {
02293                 $parts = explode( '/', $type );
02294                 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
02295                         return $parts[0] . '/*';
02296                 } elseif( array_key_exists( '*/*', $avail ) ) {
02297                         return '*/*';
02298                 } else {
02299                         return null;
02300                 }
02301         }
02302 }
02303 
02317 function wfNegotiateType( $cprefs, $sprefs ) {
02318         $combine = array();
02319 
02320         foreach( array_keys( $sprefs ) as $type ) {
02321                 $parts = explode( '/', $type );
02322                 if( $parts[1] != '*' ) {
02323                         $ckey = mimeTypeMatch( $type, $cprefs );
02324                         if( $ckey ) {
02325                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
02326                         }
02327                 }
02328         }
02329 
02330         foreach( array_keys( $cprefs ) as $type ) {
02331                 $parts = explode( '/', $type );
02332                 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
02333                         $skey = mimeTypeMatch( $type, $sprefs );
02334                         if( $skey ) {
02335                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
02336                         }
02337                 }
02338         }
02339 
02340         $bestq = 0;
02341         $besttype = null;
02342 
02343         foreach( array_keys( $combine ) as $type ) {
02344                 if( $combine[$type] > $bestq ) {
02345                         $besttype = $type;
02346                         $bestq = $combine[$type];
02347                 }
02348         }
02349 
02350         return $besttype;
02351 }
02352 
02358 function wfSuppressWarnings( $end = false ) {
02359         static $suppressCount = 0;
02360         static $originalLevel = false;
02361 
02362         if ( $end ) {
02363                 if ( $suppressCount ) {
02364                         --$suppressCount;
02365                         if ( !$suppressCount ) {
02366                                 error_reporting( $originalLevel );
02367                         }
02368                 }
02369         } else {
02370                 if ( !$suppressCount ) {
02371                         $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT ) );
02372                 }
02373                 ++$suppressCount;
02374         }
02375 }
02376 
02380 function wfRestoreWarnings() {
02381         wfSuppressWarnings( true );
02382 }
02383 
02384 # Autodetect, convert and provide timestamps of various types
02385 
02389 define( 'TS_UNIX', 0 );
02390 
02394 define( 'TS_MW', 1 );
02395 
02399 define( 'TS_DB', 2 );
02400 
02404 define( 'TS_RFC2822', 3 );
02405 
02411 define( 'TS_ISO_8601', 4 );
02412 
02420 define( 'TS_EXIF', 5 );
02421 
02425 define( 'TS_ORACLE', 6 );
02426 
02430 define( 'TS_POSTGRES', 7 );
02431 
02435 define( 'TS_ISO_8601_BASIC', 9 );
02436 
02446 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
02447         try {
02448                 $timestamp = new MWTimestamp( $ts );
02449                 return $timestamp->getTimestamp( $outputtype );
02450         } catch( TimestampException $e ) {
02451                 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
02452                 return false;
02453         }
02454 }
02455 
02464 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
02465         if( is_null( $ts ) ) {
02466                 return null;
02467         } else {
02468                 return wfTimestamp( $outputtype, $ts );
02469         }
02470 }
02471 
02477 function wfTimestampNow() {
02478         # return NOW
02479         return wfTimestamp( TS_MW, time() );
02480 }
02481 
02487 function wfIsWindows() {
02488         static $isWindows = null;
02489         if ( $isWindows === null ) {
02490                 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
02491         }
02492         return $isWindows;
02493 }
02494 
02500 function wfIsHipHop() {
02501         return function_exists( 'hphp_thread_set_warmup_enabled' );
02502 }
02503 
02510 function swap( &$x, &$y ) {
02511         $z = $x;
02512         $x = $y;
02513         $y = $z;
02514 }
02515 
02527 function wfTempDir() {
02528         global $wgTmpDirectory;
02529 
02530         if ( $wgTmpDirectory !== false ) {
02531                 return $wgTmpDirectory;
02532         }
02533 
02534         $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
02535 
02536         foreach( $tmpDir as $tmp ) {
02537                 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
02538                         return $tmp;
02539                 }
02540         }
02541         return sys_get_temp_dir();
02542 }
02543 
02553 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
02554         global $wgDirectoryMode;
02555 
02556         if ( FileBackend::isStoragePath( $dir ) ) { // sanity
02557                 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
02558         }
02559 
02560         if ( !is_null( $caller ) ) {
02561                 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
02562         }
02563 
02564         if( strval( $dir ) === '' || file_exists( $dir ) ) {
02565                 return true;
02566         }
02567 
02568         $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
02569 
02570         if ( is_null( $mode ) ) {
02571                 $mode = $wgDirectoryMode;
02572         }
02573 
02574         // Turn off the normal warning, we're doing our own below
02575         wfSuppressWarnings();
02576         $ok = mkdir( $dir, $mode, true ); // PHP5 <3
02577         wfRestoreWarnings();
02578 
02579         if( !$ok ) {
02580                 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
02581                 trigger_error( sprintf( "%s: failed to mkdir \"%s\" mode 0%o", __FUNCTION__, $dir, $mode ),
02582                         E_USER_WARNING );
02583         }
02584         return $ok;
02585 }
02586 
02591 function wfRecursiveRemoveDir( $dir ) {
02592         wfDebug( __FUNCTION__ . "( $dir )\n" );
02593         // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
02594         if ( is_dir( $dir ) ) {
02595                 $objects = scandir( $dir );
02596                 foreach ( $objects as $object ) {
02597                         if ( $object != "." && $object != ".." ) {
02598                                 if ( filetype( $dir . '/' . $object ) == "dir" ) {
02599                                         wfRecursiveRemoveDir( $dir . '/' . $object );
02600                                 } else {
02601                                         unlink( $dir . '/' . $object );
02602                                 }
02603                         }
02604                 }
02605                 reset( $objects );
02606                 rmdir( $dir );
02607         }
02608 }
02609 
02616 function wfPercent( $nr, $acc = 2, $round = true ) {
02617         $ret = sprintf( "%.${acc}f", $nr );
02618         return $round ? round( $ret, $acc ) . '%' : "$ret%";
02619 }
02620 
02630 function in_string( $needle, $str, $insensitive = false ) {
02631         wfDeprecated( __METHOD__, '1.21' );
02632         $func = 'strpos';
02633         if( $insensitive ) $func = 'stripos';
02634 
02635         return $func( $str, $needle ) !== false;
02636 }
02637 
02661 function wfIniGetBool( $setting ) {
02662         $val = ini_get( $setting );
02663         // 'on' and 'true' can't have whitespace around them, but '1' can.
02664         return strtolower( $val ) == 'on'
02665                 || strtolower( $val ) == 'true'
02666                 || strtolower( $val ) == 'yes'
02667                 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
02668 }
02669 
02679 function wfDl( $extension, $fileName = null ) {
02680         if( extension_loaded( $extension ) ) {
02681                 return true;
02682         }
02683 
02684         $canDl = false;
02685         if( PHP_SAPI == 'cli' || PHP_SAPI == 'cgi' || PHP_SAPI == 'embed' ) {
02686                 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
02687                 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
02688         }
02689 
02690         if( $canDl ) {
02691                 $fileName = $fileName ? $fileName : $extension;
02692                 if( wfIsWindows() ) {
02693                         $fileName = 'php_' . $fileName;
02694                 }
02695                 wfSuppressWarnings();
02696                 dl( $fileName . '.' . PHP_SHLIB_SUFFIX );
02697                 wfRestoreWarnings();
02698         }
02699         return extension_loaded( $extension );
02700 }
02701 
02713 function wfEscapeShellArg() {
02714         wfInitShellLocale();
02715 
02716         $args = func_get_args();
02717         $first = true;
02718         $retVal = '';
02719         foreach ( $args as $arg ) {
02720                 if ( !$first ) {
02721                         $retVal .= ' ';
02722                 } else {
02723                         $first = false;
02724                 }
02725 
02726                 if ( wfIsWindows() ) {
02727                         // Escaping for an MSVC-style command line parser and CMD.EXE
02728                         // Refs:
02729                         //  * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
02730                         //  * http://technet.microsoft.com/en-us/library/cc723564.aspx
02731                         //  * Bug #13518
02732                         //  * CR r63214
02733                         // Double the backslashes before any double quotes. Escape the double quotes.
02734                         $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
02735                         $arg = '';
02736                         $iteration = 0;
02737                         foreach ( $tokens as $token ) {
02738                                 if ( $iteration % 2 == 1 ) {
02739                                         // Delimiter, a double quote preceded by zero or more slashes
02740                                         $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
02741                                 } elseif ( $iteration % 4 == 2 ) {
02742                                         // ^ in $token will be outside quotes, need to be escaped
02743                                         $arg .= str_replace( '^', '^^', $token );
02744                                 } else { // $iteration % 4 == 0
02745                                         // ^ in $token will appear inside double quotes, so leave as is
02746                                         $arg .= $token;
02747                                 }
02748                                 $iteration++;
02749                         }
02750                         // Double the backslashes before the end of the string, because
02751                         // we will soon add a quote
02752                         $m = array();
02753                         if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
02754                                 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
02755                         }
02756 
02757                         // Add surrounding quotes
02758                         $retVal .= '"' . $arg . '"';
02759                 } else {
02760                         $retVal .= escapeshellarg( $arg );
02761                 }
02762         }
02763         return $retVal;
02764 }
02765 
02778 function wfShellExec( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
02779         global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
02780                 $wgMaxShellWallClockTime, $wgShellCgroup;
02781 
02782         static $disabled;
02783         if ( is_null( $disabled ) ) {
02784                 $disabled = false;
02785                 if( wfIniGetBool( 'safe_mode' ) ) {
02786                         wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
02787                         $disabled = 'safemode';
02788                 } else {
02789                         $functions = explode( ',', ini_get( 'disable_functions' ) );
02790                         $functions = array_map( 'trim', $functions );
02791                         $functions = array_map( 'strtolower', $functions );
02792                         if ( in_array( 'passthru', $functions ) ) {
02793                                 wfDebug( "passthru is in disabled_functions\n" );
02794                                 $disabled = 'passthru';
02795                         }
02796                 }
02797         }
02798         if ( $disabled ) {
02799                 $retval = 1;
02800                 return $disabled == 'safemode' ?
02801                         'Unable to run external programs in safe mode.' :
02802                         'Unable to run external programs, passthru() is disabled.';
02803         }
02804 
02805         wfInitShellLocale();
02806 
02807         $envcmd = '';
02808         foreach( $environ as $k => $v ) {
02809                 if ( wfIsWindows() ) {
02810                         /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
02811                          * appear in the environment variable, so we must use carat escaping as documented in
02812                          * http://technet.microsoft.com/en-us/library/cc723564.aspx
02813                          * Note however that the quote isn't listed there, but is needed, and the parentheses
02814                          * are listed there but doesn't appear to need it.
02815                          */
02816                         $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
02817                 } else {
02818                         /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
02819                          * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
02820                          */
02821                         $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
02822                 }
02823         }
02824         $cmd = $envcmd . $cmd;
02825 
02826         if ( php_uname( 's' ) == 'Linux' ) {
02827                 $time = intval ( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
02828                 if ( isset( $limits['walltime'] ) ) {
02829                         $wallTime = intval( $limits['walltime'] );
02830                 } elseif ( isset( $limits['time'] ) ) {
02831                         $wallTime = $time;
02832                 } else {
02833                         $wallTime = intval( $wgMaxShellWallClockTime );
02834                 }
02835                 $mem = intval ( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
02836                 $filesize = intval ( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
02837 
02838                 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
02839                         $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
02840                                 escapeshellarg( $cmd ) . ' ' .
02841                                 escapeshellarg(
02842                                         "MW_CPU_LIMIT=$time; " .
02843                                         'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
02844                                         "MW_MEM_LIMIT=$mem; " .
02845                                         "MW_FILE_SIZE_LIMIT=$filesize; " .
02846                                         "MW_WALL_CLOCK_LIMIT=$wallTime"
02847                                 );
02848                 }
02849         }
02850         wfDebug( "wfShellExec: $cmd\n" );
02851 
02852         $retval = 1; // error by default?
02853         ob_start();
02854         passthru( $cmd, $retval );
02855         $output = ob_get_contents();
02856         ob_end_clean();
02857 
02858         if ( $retval == 127 ) {
02859                 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
02860         }
02861         return $output;
02862 }
02863 
02868 function wfInitShellLocale() {
02869         static $done = false;
02870         if ( $done ) {
02871                 return;
02872         }
02873         $done = true;
02874         global $wgShellLocale;
02875         if ( !wfIniGetBool( 'safe_mode' ) ) {
02876                 putenv( "LC_CTYPE=$wgShellLocale" );
02877                 setlocale( LC_CTYPE, $wgShellLocale );
02878         }
02879 }
02880 
02885 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
02886         return wfShellWikiCmd( $script, $parameters, $options );
02887 }
02888 
02900 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
02901         global $wgPhpCli;
02902         // Give site config file a chance to run the script in a wrapper.
02903         // The caller may likely want to call wfBasename() on $script.
02904         wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
02905         $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
02906         if ( isset( $options['wrapper'] ) ) {
02907                 $cmd[] = $options['wrapper'];
02908         }
02909         $cmd[] = $script;
02910         // Escape each parameter for shell
02911         return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
02912 }
02913 
02924 function wfMerge( $old, $mine, $yours, &$result ) {
02925         global $wgDiff3;
02926 
02927         # This check may also protect against code injection in
02928         # case of broken installations.
02929         wfSuppressWarnings();
02930         $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
02931         wfRestoreWarnings();
02932 
02933         if( !$haveDiff3 ) {
02934                 wfDebug( "diff3 not found\n" );
02935                 return false;
02936         }
02937 
02938         # Make temporary files
02939         $td = wfTempDir();
02940         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
02941         $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
02942         $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
02943 
02944         # NOTE: diff3 issues a warning to stderr if any of the files does not end with
02945         #       a newline character. To avoid this, we normalize the trailing whitespace before
02946         #       creating the diff.
02947 
02948         fwrite( $oldtextFile, rtrim( $old ) . "\n" );
02949         fclose( $oldtextFile );
02950         fwrite( $mytextFile, rtrim( $mine ) . "\n" );
02951         fclose( $mytextFile );
02952         fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
02953         fclose( $yourtextFile );
02954 
02955         # Check for a conflict
02956         $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
02957                 wfEscapeShellArg( $mytextName ) . ' ' .
02958                 wfEscapeShellArg( $oldtextName ) . ' ' .
02959                 wfEscapeShellArg( $yourtextName );
02960         $handle = popen( $cmd, 'r' );
02961 
02962         if( fgets( $handle, 1024 ) ) {
02963                 $conflict = true;
02964         } else {
02965                 $conflict = false;
02966         }
02967         pclose( $handle );
02968 
02969         # Merge differences
02970         $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
02971                 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
02972         $handle = popen( $cmd, 'r' );
02973         $result = '';
02974         do {
02975                 $data = fread( $handle, 8192 );
02976                 if ( strlen( $data ) == 0 ) {
02977                         break;
02978                 }
02979                 $result .= $data;
02980         } while ( true );
02981         pclose( $handle );
02982         unlink( $mytextName );
02983         unlink( $oldtextName );
02984         unlink( $yourtextName );
02985 
02986         if ( $result === '' && $old !== '' && !$conflict ) {
02987                 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
02988                 $conflict = true;
02989         }
02990         return !$conflict;
02991 }
02992 
03002 function wfDiff( $before, $after, $params = '-u' ) {
03003         if ( $before == $after ) {
03004                 return '';
03005         }
03006 
03007         global $wgDiff;
03008         wfSuppressWarnings();
03009         $haveDiff = $wgDiff && file_exists( $wgDiff );
03010         wfRestoreWarnings();
03011 
03012         # This check may also protect against code injection in
03013         # case of broken installations.
03014         if( !$haveDiff ) {
03015                 wfDebug( "diff executable not found\n" );
03016                 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
03017                 $format = new UnifiedDiffFormatter();
03018                 return $format->format( $diffs );
03019         }
03020 
03021         # Make temporary files
03022         $td = wfTempDir();
03023         $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
03024         $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
03025 
03026         fwrite( $oldtextFile, $before );
03027         fclose( $oldtextFile );
03028         fwrite( $newtextFile, $after );
03029         fclose( $newtextFile );
03030 
03031         // Get the diff of the two files
03032         $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
03033 
03034         $h = popen( $cmd, 'r' );
03035 
03036         $diff = '';
03037 
03038         do {
03039                 $data = fread( $h, 8192 );
03040                 if ( strlen( $data ) == 0 ) {
03041                         break;
03042                 }
03043                 $diff .= $data;
03044         } while ( true );
03045 
03046         // Clean up
03047         pclose( $h );
03048         unlink( $oldtextName );
03049         unlink( $newtextName );
03050 
03051         // Kill the --- and +++ lines. They're not useful.
03052         $diff_lines = explode( "\n", $diff );
03053         if ( strpos( $diff_lines[0], '---' ) === 0 ) {
03054                 unset( $diff_lines[0] );
03055         }
03056         if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
03057                 unset( $diff_lines[1] );
03058         }
03059 
03060         $diff = implode( "\n", $diff_lines );
03061 
03062         return $diff;
03063 }
03064 
03081 function wfUsePHP( $req_ver ) {
03082         $php_ver = PHP_VERSION;
03083 
03084         if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
03085                 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
03086         }
03087 }
03088 
03103 function wfUseMW( $req_ver ) {
03104         global $wgVersion;
03105 
03106         if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
03107                 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
03108         }
03109 }
03110 
03123 function wfBaseName( $path, $suffix = '' ) {
03124         $encSuffix = ( $suffix == '' )
03125                 ? ''
03126                 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
03127         $matches = array();
03128         if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
03129                 return $matches[1];
03130         } else {
03131                 return '';
03132         }
03133 }
03134 
03144 function wfRelativePath( $path, $from ) {
03145         // Normalize mixed input on Windows...
03146         $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
03147         $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
03148 
03149         // Trim trailing slashes -- fix for drive root
03150         $path = rtrim( $path, DIRECTORY_SEPARATOR );
03151         $from = rtrim( $from, DIRECTORY_SEPARATOR );
03152 
03153         $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
03154         $against = explode( DIRECTORY_SEPARATOR, $from );
03155 
03156         if( $pieces[0] !== $against[0] ) {
03157                 // Non-matching Windows drive letters?
03158                 // Return a full path.
03159                 return $path;
03160         }
03161 
03162         // Trim off common prefix
03163         while( count( $pieces ) && count( $against )
03164                 && $pieces[0] == $against[0] ) {
03165                 array_shift( $pieces );
03166                 array_shift( $against );
03167         }
03168 
03169         // relative dots to bump us to the parent
03170         while( count( $against ) ) {
03171                 array_unshift( $pieces, '..' );
03172                 array_shift( $against );
03173         }
03174 
03175         array_push( $pieces, wfBaseName( $path ) );
03176 
03177         return implode( DIRECTORY_SEPARATOR, $pieces );
03178 }
03179 
03187 function wfDoUpdates( $commit = '' ) {
03188         wfDeprecated( __METHOD__, '1.19' );
03189         DeferredUpdates::doUpdates( $commit );
03190 }
03191 
03207 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true, $engine = 'auto' ) {
03208         $input = (string)$input;
03209         if(
03210                 $sourceBase < 2 ||
03211                 $sourceBase > 36 ||
03212                 $destBase < 2 ||
03213                 $destBase > 36 ||
03214                 $sourceBase != (int) $sourceBase ||
03215                 $destBase != (int) $destBase ||
03216                 $pad != (int) $pad ||
03217                 !preg_match( "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i", $input )
03218         ) {
03219                 return false;
03220         }
03221 
03222         static $baseChars = array (
03223                 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
03224                 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
03225                 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
03226                 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
03227                 34 => 'y', 35 => 'z',
03228 
03229                 '0' => 0,  '1' => 1,  '2' => 2,  '3' => 3,  '4' => 4,  '5' => 5,
03230                 '6' => 6,  '7' => 7,  '8' => 8,  '9' => 9,  'a' => 10, 'b' => 11,
03231                 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
03232                 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
03233                 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
03234                 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
03235         );
03236 
03237         if( extension_loaded( 'gmp' ) && ( $engine == 'auto' || $engine == 'gmp' ) ) {
03238                 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
03239         } elseif( extension_loaded( 'bcmath' ) && ( $engine == 'auto' || $engine == 'bcmath' ) ) {
03240                 $decimal = '0';
03241                 foreach( str_split( strtolower( $input ) ) as $char ) {
03242                         $decimal = bcmul( $decimal, $sourceBase );
03243                         $decimal = bcadd( $decimal, $baseChars[$char] );
03244                 }
03245 
03246                 for( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
03247                         $result .= $baseChars[bcmod( $decimal, $destBase )];
03248                 }
03249 
03250                 $result = strrev( $result );
03251         } else {
03252                 $inDigits = array();
03253                 foreach( str_split( strtolower( $input ) ) as $char ) {
03254                         $inDigits[] = $baseChars[$char];
03255                 }
03256 
03257                 // Iterate over the input, modulo-ing out an output digit
03258                 // at a time until input is gone.
03259                 $result = '';
03260                 while( $inDigits ) {
03261                         $work = 0;
03262                         $workDigits = array();
03263 
03264                         // Long division...
03265                         foreach( $inDigits as $digit ) {
03266                                 $work *= $sourceBase;
03267                                 $work += $digit;
03268 
03269                                 if( $workDigits || $work >= $destBase ) {
03270                                         $workDigits[] = (int) ( $work / $destBase );
03271                                 }
03272                                 $work %= $destBase;
03273                         }
03274 
03275                         // All that division leaves us with a remainder,
03276                         // which is conveniently our next output digit.
03277                         $result .= $baseChars[$work];
03278 
03279                         // And we continue!
03280                         $inDigits = $workDigits;
03281                 }
03282 
03283                 $result = strrev( $result );
03284         }
03285 
03286         if( !$lowercase ) {
03287                 $result = strtoupper( $result );
03288         }
03289 
03290         return str_pad( $result, $pad, '0', STR_PAD_LEFT );
03291 }
03292 
03301 function wfCreateObject( $name, $p ) {
03302         wfDeprecated( __FUNCTION__, '1.18' );
03303         return MWFunction::newObj( $name, $p );
03304 }
03305 
03309 function wfHttpOnlySafe() {
03310         global $wgHttpOnlyBlacklist;
03311 
03312         if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
03313                 foreach( $wgHttpOnlyBlacklist as $regex ) {
03314                         if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
03315                                 return false;
03316                         }
03317                 }
03318         }
03319 
03320         return true;
03321 }
03322 
03327 function wfCheckEntropy() {
03328         return (
03329                         ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
03330                         || ini_get( 'session.entropy_file' )
03331                 )
03332                 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
03333 }
03334 
03339 function wfFixSessionID() {
03340         // If the cookie or session id is already set we already have a session and should abort
03341         if ( isset( $_COOKIE[ session_name() ] ) || session_id() ) {
03342                 return;
03343         }
03344 
03345         // PHP's built-in session entropy is enabled if:
03346         // - entropy_file is set or you're on Windows with php 5.3.3+
03347         // - AND entropy_length is > 0
03348         // We treat it as disabled if it doesn't have an entropy length of at least 32
03349         $entropyEnabled = wfCheckEntropy();
03350 
03351         // If built-in entropy is not enabled or not sufficient override php's built in session id generation code
03352         if ( !$entropyEnabled ) {
03353                 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, overriding session id generation using our cryptrand source.\n" );
03354                 session_id( MWCryptRand::generateHex( 32 ) );
03355         }
03356 }
03357 
03363 function wfSetupSession( $sessionId = false ) {
03364         global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
03365                         $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
03366         if( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
03367                 ObjectCacheSessionHandler::install();
03368         } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
03369                 # Only set this if $wgSessionHandler isn't null and session.save_handler
03370                 # hasn't already been set to the desired value (that causes errors)
03371                 ini_set( 'session.save_handler', $wgSessionHandler );
03372         }
03373         $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
03374         wfDebugLog( 'cookie',
03375                 'session_set_cookie_params: "' . implode( '", "',
03376                         array(
03377                                 0,
03378                                 $wgCookiePath,
03379                                 $wgCookieDomain,
03380                                 $wgCookieSecure,
03381                                 $httpOnlySafe ) ) . '"' );
03382         session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
03383         session_cache_limiter( 'private, must-revalidate' );
03384         if ( $sessionId ) {
03385                 session_id( $sessionId );
03386         } else {
03387                 wfFixSessionID();
03388         }
03389         wfSuppressWarnings();
03390         session_start();
03391         wfRestoreWarnings();
03392 }
03393 
03400 function wfGetPrecompiledData( $name ) {
03401         global $IP;
03402 
03403         $file = "$IP/serialized/$name";
03404         if ( file_exists( $file ) ) {
03405                 $blob = file_get_contents( $file );
03406                 if ( $blob ) {
03407                         return unserialize( $blob );
03408                 }
03409         }
03410         return false;
03411 }
03412 
03419 function wfMemcKey( /*... */ ) {
03420         global $wgCachePrefix;
03421         $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
03422         $args = func_get_args();
03423         $key = $prefix . ':' . implode( ':', $args );
03424         $key = str_replace( ' ', '_', $key );
03425         return $key;
03426 }
03427 
03436 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
03437         $args = array_slice( func_get_args(), 2 );
03438         if ( $prefix ) {
03439                 $key = "$db-$prefix:" . implode( ':', $args );
03440         } else {
03441                 $key = $db . ':' . implode( ':', $args );
03442         }
03443         return $key;
03444 }
03445 
03452 function wfWikiID() {
03453         global $wgDBprefix, $wgDBname;
03454         if ( $wgDBprefix ) {
03455                 return "$wgDBname-$wgDBprefix";
03456         } else {
03457                 return $wgDBname;
03458         }
03459 }
03460 
03468 function wfSplitWikiID( $wiki ) {
03469         $bits = explode( '-', $wiki, 2 );
03470         if ( count( $bits ) < 2 ) {
03471                 $bits[] = '';
03472         }
03473         return $bits;
03474 }
03475 
03498 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
03499         return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
03500 }
03501 
03508 function wfGetLB( $wiki = false ) {
03509         return wfGetLBFactory()->getMainLB( $wiki );
03510 }
03511 
03517 function &wfGetLBFactory() {
03518         return LBFactory::singleton();
03519 }
03520 
03541 function wfFindFile( $title, $options = array() ) {
03542         return RepoGroup::singleton()->findFile( $title, $options );
03543 }
03544 
03552 function wfLocalFile( $title ) {
03553         return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
03554 }
03555 
03560 function wfStreamFile( $fname, $headers = array() ) {
03561         wfDeprecated( __FUNCTION__, '1.19' );
03562         StreamFile::stream( $fname, $headers );
03563 }
03564 
03571 function wfQueriesMustScale() {
03572         global $wgMiserMode;
03573         return $wgMiserMode
03574                 || ( SiteStats::pages() > 100000
03575                 && SiteStats::edits() > 1000000
03576                 && SiteStats::users() > 10000 );
03577 }
03578 
03587 function wfScript( $script = 'index' ) {
03588         global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
03589         if ( $script === 'index' ) {
03590                 return $wgScript;
03591         } else if ( $script === 'load' ) {
03592                 return $wgLoadScript;
03593         } else {
03594                 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
03595         }
03596 }
03597 
03603 function wfGetScriptUrl() {
03604         if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
03605                 #
03606                 # as it was called, minus the query string.
03607                 #
03608                 # Some sites use Apache rewrite rules to handle subdomains,
03609                 # and have PHP set up in a weird way that causes PHP_SELF
03610                 # to contain the rewritten URL instead of the one that the
03611                 # outside world sees.
03612                 #
03613                 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
03614                 # provides containing the "before" URL.
03615                 return $_SERVER['SCRIPT_NAME'];
03616         } else {
03617                 return $_SERVER['URL'];
03618         }
03619 }
03620 
03628 function wfBoolToStr( $value ) {
03629         return $value ? 'true' : 'false';
03630 }
03631 
03637 function wfGetNull() {
03638         return wfIsWindows()
03639                 ? 'NUL'
03640                 : '/dev/null';
03641 }
03642 
03653 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
03654         $lb = wfGetLB( $wiki );
03655         // bug 27975 - Don't try to wait for slaves if there are none
03656         // Prevents permission error when getting master position
03657         if ( $lb->getServerCount() > 1 ) {
03658                 $dbw = $lb->getConnection( DB_MASTER );
03659                 $pos = $dbw->getMasterPos();
03660                 $lb->waitForAll( $pos );
03661         }
03662 }
03663 
03668 function wfOut( $s ) {
03669         wfDeprecated( __FUNCTION__, '1.18' );
03670         global $wgCommandLineMode;
03671         if ( $wgCommandLineMode ) {
03672                 echo $s;
03673         } else {
03674                 echo htmlspecialchars( $s );
03675         }
03676         flush();
03677 }
03678 
03685 function wfCountDown( $n ) {
03686         for ( $i = $n; $i >= 0; $i-- ) {
03687                 if ( $i != $n ) {
03688                         echo str_repeat( "\x08", strlen( $i + 1 ) );
03689                 }
03690                 echo $i;
03691                 flush();
03692                 if ( $i ) {
03693                         sleep( 1 );
03694                 }
03695         }
03696         echo "\n";
03697 }
03698 
03708 function wfGenerateToken( $salt = '' ) {
03709         wfDeprecated( __METHOD__, '1.20' );
03710         $salt = serialize( $salt );
03711         return md5( mt_rand( 0, 0x7fffffff ) . $salt );
03712 }
03713 
03722 function wfStripIllegalFilenameChars( $name ) {
03723         global $wgIllegalFileChars;
03724         $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
03725         $name = wfBaseName( $name );
03726         $name = preg_replace(
03727                 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
03728                 '-',
03729                 $name
03730         );
03731         return $name;
03732 }
03733 
03739 function wfMemoryLimit() {
03740         global $wgMemoryLimit;
03741         $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
03742         if( $memlimit != -1 ) {
03743                 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
03744                 if( $conflimit == -1 ) {
03745                         wfDebug( "Removing PHP's memory limit\n" );
03746                         wfSuppressWarnings();
03747                         ini_set( 'memory_limit', $conflimit );
03748                         wfRestoreWarnings();
03749                         return $conflimit;
03750                 } elseif ( $conflimit > $memlimit ) {
03751                         wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
03752                         wfSuppressWarnings();
03753                         ini_set( 'memory_limit', $conflimit );
03754                         wfRestoreWarnings();
03755                         return $conflimit;
03756                 }
03757         }
03758         return $memlimit;
03759 }
03760 
03767 function wfShorthandToInteger( $string = '' ) {
03768         $string = trim( $string );
03769         if( $string === '' ) {
03770                 return -1;
03771         }
03772         $last = $string[strlen( $string ) - 1];
03773         $val = intval( $string );
03774         switch( $last ) {
03775                 case 'g':
03776                 case 'G':
03777                         $val *= 1024;
03778                         // break intentionally missing
03779                 case 'm':
03780                 case 'M':
03781                         $val *= 1024;
03782                         // break intentionally missing
03783                 case 'k':
03784                 case 'K':
03785                         $val *= 1024;
03786         }
03787 
03788         return $val;
03789 }
03790 
03798 function wfBCP47( $code ) {
03799         $codeSegment = explode( '-', $code );
03800         $codeBCP = array();
03801         foreach ( $codeSegment as $segNo => $seg ) {
03802                 if ( count( $codeSegment ) > 0 ) {
03803                         // when previous segment is x, it is a private segment and should be lc
03804                         if( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
03805                                 $codeBCP[$segNo] = strtolower( $seg );
03806                         // ISO 3166 country code
03807                         } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
03808                                 $codeBCP[$segNo] = strtoupper( $seg );
03809                         // ISO 15924 script code
03810                         } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
03811                                 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
03812                         // Use lowercase for other cases
03813                         } else {
03814                                 $codeBCP[$segNo] = strtolower( $seg );
03815                         }
03816                 } else {
03817                 // Use lowercase for single segment
03818                         $codeBCP[$segNo] = strtolower( $seg );
03819                 }
03820         }
03821         $langCode = implode( '-', $codeBCP );
03822         return $langCode;
03823 }
03824 
03831 function wfGetCache( $inputType ) {
03832         return ObjectCache::getInstance( $inputType );
03833 }
03834 
03840 function wfGetMainCache() {
03841         global $wgMainCacheType;
03842         return ObjectCache::getInstance( $wgMainCacheType );
03843 }
03844 
03850 function wfGetMessageCacheStorage() {
03851         global $wgMessageCacheType;
03852         return ObjectCache::getInstance( $wgMessageCacheType );
03853 }
03854 
03860 function wfGetParserCacheStorage() {
03861         global $wgParserCacheType;
03862         return ObjectCache::getInstance( $wgParserCacheType );
03863 }
03864 
03870 function wfGetLangConverterCacheStorage() {
03871         global $wgLanguageConverterCacheType;
03872         return ObjectCache::getInstance( $wgLanguageConverterCacheType );
03873 }
03874 
03882 function wfRunHooks( $event, $args = array() ) {
03883         return Hooks::run( $event, $args );
03884 }
03885 
03900 function wfUnpack( $format, $data, $length=false ) {
03901         if ( $length !== false ) {
03902                 $realLen = strlen( $data );
03903                 if ( $realLen < $length ) {
03904                         throw new MWException( "Tried to use wfUnpack on a "
03905                                 . "string of length $realLen, but needed one "
03906                                 . "of at least length $length."
03907                         );
03908                 }
03909         }
03910 
03911         wfSuppressWarnings();
03912         $result = unpack( $format, $data );
03913         wfRestoreWarnings();
03914 
03915         if ( $result === false ) {
03916                 // If it cannot extract the packed data.
03917                 throw new MWException( "unpack could not unpack binary data" );
03918         }
03919         return $result;
03920 }
03921 
03936 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
03937         static $badImageCache = null; // based on bad_image_list msg
03938         wfProfileIn( __METHOD__ );
03939 
03940         # Handle redirects
03941         $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
03942         if( $redirectTitle ) {
03943                 $name = $redirectTitle->getDbKey();
03944         }
03945 
03946         # Run the extension hook
03947         $bad = false;
03948         if( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
03949                 wfProfileOut( __METHOD__ );
03950                 return $bad;
03951         }
03952 
03953         $cacheable = ( $blacklist === null );
03954         if( $cacheable && $badImageCache !== null ) {
03955                 $badImages = $badImageCache;
03956         } else { // cache miss
03957                 if ( $blacklist === null ) {
03958                         $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
03959                 }
03960                 # Build the list now
03961                 $badImages = array();
03962                 $lines = explode( "\n", $blacklist );
03963                 foreach( $lines as $line ) {
03964                         # List items only
03965                         if ( substr( $line, 0, 1 ) !== '*' ) {
03966                                 continue;
03967                         }
03968 
03969                         # Find all links
03970                         $m = array();
03971                         if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
03972                                 continue;
03973                         }
03974 
03975                         $exceptions = array();
03976                         $imageDBkey = false;
03977                         foreach ( $m[1] as $i => $titleText ) {
03978                                 $title = Title::newFromText( $titleText );
03979                                 if ( !is_null( $title ) ) {
03980                                         if ( $i == 0 ) {
03981                                                 $imageDBkey = $title->getDBkey();
03982                                         } else {
03983                                                 $exceptions[$title->getPrefixedDBkey()] = true;
03984                                         }
03985                                 }
03986                         }
03987 
03988                         if ( $imageDBkey !== false ) {
03989                                 $badImages[$imageDBkey] = $exceptions;
03990                         }
03991                 }
03992                 if ( $cacheable ) {
03993                         $badImageCache = $badImages;
03994                 }
03995         }
03996 
03997         $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
03998         $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
03999         wfProfileOut( __METHOD__ );
04000         return $bad;
04001 }