Bump PHP version requirement to 7.0.0+
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
index 310adeb..7667a9e 100644 (file)
@@ -32,75 +32,6 @@ use MediaWiki\Shell\Shell;
 use Wikimedia\ScopedCallback;
 use Wikimedia\Rdbms\DBReplicationWaitError;
 
-// Hide compatibility functions from Doxygen
-/// @cond
-/**
- * Compatibility functions
- *
- * We support PHP 5.5.9 and up.
- * Re-implementations of newer functions or functions in non-standard
- * PHP extensions may be included here.
- */
-
-// hash_equals function only exists in PHP >= 5.6.0
-// https://secure.php.net/hash_equals
-if ( !function_exists( 'hash_equals' ) ) {
-       /**
-        * Check whether a user-provided string is equal to a fixed-length secret string
-        * without revealing bytes of the secret string through timing differences.
-        *
-        * The usual way to compare strings (PHP's === operator or the underlying memcmp()
-        * function in C) is to compare corresponding bytes and stop at the first difference,
-        * which would take longer for a partial match than for a complete mismatch. This
-        * is not secure when one of the strings (e.g. an HMAC or token) must remain secret
-        * and the other may come from an attacker. Statistical analysis of timing measurements
-        * over many requests may allow the attacker to guess the string's bytes one at a time
-        * (and check his guesses) even if the timing differences are extremely small.
-        *
-        * When making such a security-sensitive comparison, it is essential that the sequence
-        * in which instructions are executed and memory locations are accessed not depend on
-        * the secret string's value. HOWEVER, for simplicity, we do not attempt to minimize
-        * the inevitable leakage of the string's length. That is generally known anyway as
-        * a chararacteristic of the hash function used to compute the secret value.
-        *
-        * Longer explanation: http://www.emerose.com/timing-attacks-explained
-        *
-        * @codeCoverageIgnore
-        * @param string $known_string Fixed-length secret string to compare against
-        * @param string $user_string User-provided string
-        * @return bool True if the strings are the same, false otherwise
-        */
-       function hash_equals( $known_string, $user_string ) {
-               // Strict type checking as in PHP's native implementation
-               if ( !is_string( $known_string ) ) {
-                       trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
-                               gettype( $known_string ) . ' given', E_USER_WARNING );
-
-                       return false;
-               }
-
-               if ( !is_string( $user_string ) ) {
-                       trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
-                               gettype( $user_string ) . ' given', E_USER_WARNING );
-
-                       return false;
-               }
-
-               $known_string_len = strlen( $known_string );
-               if ( $known_string_len !== strlen( $user_string ) ) {
-                       return false;
-               }
-
-               $result = 0;
-               for ( $i = 0; $i < $known_string_len; $i++ ) {
-                       $result |= ord( $known_string[$i] ) ^ ord( $user_string[$i] );
-               }
-
-               return ( $result === 0 );
-       }
-}
-/// @endcond
-
 /**
  * Load an extension
  *
@@ -582,7 +513,7 @@ function wfAppendQuery( $url, $query ) {
  * like "subdir/foo.html", etc.
  *
  * @param string $url Either fully-qualified or a local path + query
- * @param string $defaultProto One of the PROTO_* constants. Determines the
+ * @param string|int|null $defaultProto One of the PROTO_* constants. Determines the
  *    protocol to use if $url or $wgServer is protocol-relative
  * @return string|false Fully-qualified URL, current-path-relative URL or false if
  *    no valid URL can be constructed
@@ -877,9 +808,9 @@ function wfParseUrl( $url ) {
        if ( $wasRelative ) {
                $url = "http:$url";
        }
-       MediaWiki\suppressWarnings();
+       Wikimedia\suppressWarnings();
        $bits = parse_url( $url );
-       MediaWiki\restoreWarnings();
+       Wikimedia\restoreWarnings();
        // parse_url() returns an array without scheme for some invalid URLs, e.g.
        // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
        if ( !$bits || !isset( $bits['scheme'] ) ) {
@@ -1010,7 +941,7 @@ function wfMakeUrlIndexes( $url ) {
 
 /**
  * Check whether a given URL has a domain that occurs in a given set of domains
- * @param string $url URL
+ * @param string $url
  * @param array $domains Array of domains (strings)
  * @return bool True if the host part of $url ends in one of the strings in $domains
  */
@@ -1050,7 +981,7 @@ function wfMatchesDomainList( $url, $domains ) {
  */
 function wfDebug( $text, $dest = 'all', array $context = [] ) {
        global $wgDebugRawPage, $wgDebugLogPrefix;
-       global $wgDebugTimestamps, $wgRequestTime;
+       global $wgDebugTimestamps;
 
        if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
                return;
@@ -1061,7 +992,7 @@ function wfDebug( $text, $dest = 'all', array $context = [] ) {
        if ( $wgDebugTimestamps ) {
                $context['seconds_elapsed'] = sprintf(
                        '%6.4f',
-                       microtime( true ) - $wgRequestTime
+                       microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT']
                );
                $context['memory_used'] = sprintf(
                        '%5.1fM',
@@ -1514,9 +1445,11 @@ function wfHostname() {
  * @return string
  */
 function wfReportTime() {
-       global $wgRequestTime, $wgShowHostnames;
+       global $wgShowHostnames;
 
-       $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
+       $elapsed = ( microtime( true ) - $_SERVER['REQUEST_TIME_FLOAT'] );
+       // seconds to milliseconds
+       $responseTime = round( $elapsed * 1000 );
        $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
        if ( $wgShowHostnames ) {
                $reportVars['wgHostname'] = wfHostname();
@@ -1843,7 +1776,7 @@ function wfHttpError( $code, $label, $desc ) {
 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
        if ( $resetGzipEncoding ) {
                // Suppress Content-Encoding and Content-Length
-               // headers from 1.10+s wfOutputHandler
+               // headers from OutputHandler::handle.
                global $wgDisableOutputCompression;
                $wgDisableOutputCompression = true;
        }
@@ -2009,19 +1942,19 @@ function wfNegotiateType( $cprefs, $sprefs ) {
 /**
  * Reference-counted warning suppression
  *
- * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly
+ * @deprecated since 1.26, use Wikimedia\suppressWarnings() directly
  * @param bool $end
  */
 function wfSuppressWarnings( $end = false ) {
-       MediaWiki\suppressWarnings( $end );
+       Wikimedia\suppressWarnings( $end );
 }
 
 /**
- * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly
+ * @deprecated since 1.26, use Wikimedia\restoreWarnings() directly
  * Restore error level to previous value
  */
 function wfRestoreWarnings() {
-       MediaWiki\suppressWarnings( true );
+       Wikimedia\restoreWarnings();
 }
 
 /**
@@ -2088,6 +2021,16 @@ function wfIsHHVM() {
        return defined( 'HHVM_VERSION' );
 }
 
+/**
+ * Check if we are running from the commandline
+ *
+ * @since 1.31
+ * @return bool
+ */
+function wfIsCLI() {
+       return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
+}
+
 /**
  * Tries to get the system directory for temporary files. First
  * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
@@ -2140,9 +2083,9 @@ function wfMkdirParents( $dir, $mode = null, $caller = null ) {
        }
 
        // Turn off the normal warning, we're doing our own below
-       MediaWiki\suppressWarnings();
+       Wikimedia\suppressWarnings();
        $ok = mkdir( $dir, $mode, true ); // PHP5 <3
-       MediaWiki\restoreWarnings();
+       Wikimedia\restoreWarnings();
 
        if ( !$ok ) {
                // directory may have been created on another request since we last checked
@@ -2315,6 +2258,8 @@ function wfShellExec( $cmd, &$retval = null, $environ = [],
                        ->limits( $limits )
                        ->includeStderr( $includeStderr )
                        ->profileMethod( $profileMethod )
+                       // For b/c
+                       ->restrict( Shell::RESTRICT_NONE )
                        ->execute();
        } catch ( ProcOpenError $ex ) {
                $retval = -1;
@@ -2365,6 +2310,8 @@ function wfInitShellLocale() {
  * Note that $parameters should be a flat array and an option with an argument
  * should consist of two consecutive items in the array (do not use "--option value").
  *
+ * @deprecated since 1.31, use Shell::makeScriptCommand()
+ *
  * @param string $script MediaWiki cli script path
  * @param array $parameters Arguments and options to the script
  * @param array $options Associative array of options:
@@ -2402,9 +2349,9 @@ function wfMerge( $old, $mine, $yours, &$result, &$mergeAttemptResult = null ) {
 
        # This check may also protect against code injection in
        # case of broken installations.
-       MediaWiki\suppressWarnings();
+       Wikimedia\suppressWarnings();
        $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
-       MediaWiki\restoreWarnings();
+       Wikimedia\restoreWarnings();
 
        if ( !$haveDiff3 ) {
                wfDebug( "diff3 not found\n" );
@@ -2486,9 +2433,9 @@ function wfDiff( $before, $after, $params = '-u' ) {
        }
 
        global $wgDiff;
-       MediaWiki\suppressWarnings();
+       Wikimedia\suppressWarnings();
        $haveDiff = $wgDiff && file_exists( $wgDiff );
-       MediaWiki\restoreWarnings();
+       Wikimedia\restoreWarnings();
 
        # This check may also protect against code injection in
        # case of broken installations.
@@ -2676,30 +2623,6 @@ function wfRelativePath( $path, $from ) {
        return implode( DIRECTORY_SEPARATOR, $pieces );
 }
 
-/**
- * Convert an arbitrarily-long digit string from one numeric base
- * to another, optionally zero-padding to a minimum column width.
- *
- * Supports base 2 through 36; digit values 10-36 are represented
- * as lowercase letters a-z. Input is case-insensitive.
- *
- * @deprecated since 1.27 Use Wikimedia\base_convert() directly
- *
- * @param string $input Input number
- * @param int $sourceBase Base of the input number
- * @param int $destBase Desired base of the output
- * @param int $pad Minimum number of digits in the output (pad with zeroes)
- * @param bool $lowercase Whether to output in lowercase or uppercase
- * @param string $engine Either "gmp", "bcmath", or "php"
- * @return string|bool The output number as a string, or false on error
- */
-function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
-       $lowercase = true, $engine = 'auto'
-) {
-       wfDeprecated( __FUNCTION__, '1.27' );
-       return Wikimedia\base_convert( $input, $sourceBase, $destBase, $pad, $lowercase, $engine );
-}
-
 /**
  * Reset the session id
  *
@@ -2744,7 +2667,7 @@ function wfSetupSession( $sessionId = false ) {
        if ( session_id() !== $session->getId() ) {
                session_id( $session->getId() );
        }
-       MediaWiki\quietCall( 'session_start' );
+       Wikimedia\quietCall( 'session_start' );
 }
 
 /**
@@ -3031,7 +2954,7 @@ function wfWaitForSlaves(
        $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
 ) {
        if ( $timeout === null ) {
-               $timeout = ( PHP_SAPI === 'cli' ) ? 86400 : 10;
+               $timeout = wfIsCLI() ? 60 : 10;
        }
 
        if ( $cluster === '*' ) {
@@ -3042,7 +2965,8 @@ function wfWaitForSlaves(
        }
 
        try {
-               wfGetLBFactory()->waitForReplication( [
+               $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
+               $lbFactory->waitForReplication( [
                        'wiki' => $wiki,
                        'cluster' => $cluster,
                        'timeout' => $timeout,
@@ -3112,15 +3036,15 @@ function wfMemoryLimit() {
                $conflimit = wfShorthandToInteger( $wgMemoryLimit );
                if ( $conflimit == -1 ) {
                        wfDebug( "Removing PHP's memory limit\n" );
-                       MediaWiki\suppressWarnings();
+                       Wikimedia\suppressWarnings();
                        ini_set( 'memory_limit', $conflimit );
-                       MediaWiki\restoreWarnings();
+                       Wikimedia\restoreWarnings();
                        return $conflimit;
                } elseif ( $conflimit > $memlimit ) {
                        wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
-                       MediaWiki\suppressWarnings();
+                       Wikimedia\suppressWarnings();
                        ini_set( 'memory_limit', $conflimit );
-                       MediaWiki\restoreWarnings();
+                       Wikimedia\restoreWarnings();
                        return $conflimit;
                }
        }
@@ -3273,9 +3197,9 @@ function wfUnpack( $format, $data, $length = false ) {
                }
        }
 
-       MediaWiki\suppressWarnings();
+       Wikimedia\suppressWarnings();
        $result = unpack( $format, $data );
-       MediaWiki\restoreWarnings();
+       Wikimedia\restoreWarnings();
 
        if ( $result === false ) {
                // If it cannot extract the packed data.
@@ -3517,19 +3441,3 @@ function wfGetRusage() {
                return getrusage( 0 /* RUSAGE_SELF */ );
        }
 }
-
-/**
- * Begin profiling of a function
- * @param string $functionname Name of the function we will profile
- * @deprecated since 1.25
- */
-function wfProfileIn( $functionname ) {
-}
-
-/**
- * Stop profiling of a function
- * @param string $functionname Name of the function we have profiled
- * @deprecated since 1.25
- */
-function wfProfileOut( $functionname = 'missing' ) {
-}