Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 107
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
wfEntryPointCheck
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
PHPVersionCheck
0.00% covered (danger)
0.00%
0 / 101
0.00% covered (danger)
0.00%
0 / 8
702
0.00% covered (danger)
0.00%
0 / 1
 setFormat
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setScriptPath
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 checkRequiredPHPVersion
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
72
 checkVendorExistence
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 checkExtensionExistence
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
90
 outputHTMLHeader
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getIndexErrorOutput
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 triggerError
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21// phpcs:disable Generic.Arrays.DisallowLongArraySyntax,PSR2.Classes.PropertyDeclaration,MediaWiki.Usage.DirUsage
22// phpcs:disable Squiz.Scope.MemberVarScope.Missing,Squiz.Scope.MethodScope.Missing
23// phpcs:disable MediaWiki.Usage.StaticClosure.StaticClosure
24/**
25 * Check PHP Version, as well as for composer dependencies in entry points,
26 * and display something vaguely comprehensible in the event of a totally
27 * unrecoverable error.
28 *
29 * @note Since we can't rely on anything external, the minimum PHP versions
30 * and MW current version are hardcoded in this class.
31 *
32 * @note This class uses setter methods instead of a constructor so that
33 * it can be compatible with PHP 4 through PHP 8 (without warnings).
34 */
35class PHPVersionCheck {
36    /** @var string The number of the MediaWiki version used. If you're updating MW_VERSION in Defines.php, you must also update this value. */
37    var $mwVersion = '1.45';
38
39    /** @var string[] A mapping of PHP functions to PHP extensions. */
40    var $functionsExtensionsMapping = array(
41        'mb_substr'   => 'mbstring',
42        'xml_parser_create' => 'xml',
43        'ctype_digit' => 'ctype',
44        'json_decode' => 'json',
45        'iconv'       => 'iconv',
46        'mime_content_type' => 'fileinfo',
47        'intl_is_failure' => 'intl',
48    );
49
50    /**
51     * @var string The format used for errors. One of "text" or "html"
52     */
53    var $format = 'text';
54
55    /**
56     * @var string
57     */
58    var $scriptPath = '/';
59
60    /**
61     * Set the format used for errors.
62     *
63     * @param string $format One of "text" or "html"
64     */
65    function setFormat( $format ) {
66        $this->format = $format;
67    }
68
69    /**
70     * Set the script path used for images in HTML-formatted errors.
71     *
72     * @param string $scriptPath
73     */
74    function setScriptPath( $scriptPath ) {
75        $this->scriptPath = $scriptPath;
76    }
77
78    /**
79     * Displays an error, if the installed PHP version does not meet the minimum requirement.
80     */
81    function checkRequiredPHPVersion() {
82        $minimumVersion = '8.1.0';
83
84        /**
85         * This is a list of known-bad ranges of PHP versions. Syntax is like SemVer – either:
86         *
87         *  - '1.2.3' to prohibit a single version of PHP, or
88         *  - '1.2.3 – 1.2.5' to block a range, inclusive.
89         *
90         * Whitespace will be ignored.
91         *
92         * The key is not shown to users; use it to prompt future developers as to why this was
93         * chosen, ideally one or more Phabricator task references.
94         *
95         * Remember to drop irrelevant ranges when bumping $minimumVersion.
96         */
97        $knownBad = array(
98        );
99
100        $passes = version_compare( PHP_VERSION, $minimumVersion, '>=' );
101
102        $versionString = "PHP $minimumVersion or higher";
103
104        // Left as a programmatic check to make it easier to update.
105        if ( count( $knownBad ) ) {
106            $versionString .= ' (and not ' . implode( ', ', array_values( $knownBad ) ) . ')';
107
108            foreach ( $knownBad as $range ) {
109                // As we don't have composer at this point, we have to do our own version range checking.
110                if ( strpos( $range, '-' ) ) {
111                    $passes = $passes && !(
112                        version_compare( PHP_VERSION, trim( strstr( $range, '-', true ) ), '>=' )
113                        && version_compare( PHP_VERSION, trim( substr( strstr( $range, '-', false ), 1 ) ), '<' )
114                    );
115                } else {
116                    $passes = $passes && version_compare( PHP_VERSION, trim( $range ), '<>' );
117                }
118            }
119        }
120
121        if ( !$passes ) {
122            $cliText = "Error: You are using an unsupported PHP version (PHP " . PHP_VERSION . ").\n"
123            . "MediaWiki $this->mwVersion needs $versionString.\n\nCheck if you might have a newer "
124            . "PHP executable with a different name.\n\n";
125
126            $web = array();
127            $web['intro'] = "MediaWiki $this->mwVersion requires $versionString; you are using PHP "
128                . PHP_VERSION . ".";
129
130            $web['longTitle'] = "Supported PHP versions";
131            // phpcs:disable Generic.Files.LineLength
132            $web['longHtml'] = <<<HTML
133        <p>
134            Please consider <a href="https://www.php.net/downloads.php">upgrading your copy of PHP</a>.
135            PHP versions less than v8.1.0 are no longer <a href="https://www.php.net/supported-versions.php">supported</a>
136            by the PHP Group and will not receive security or bugfix updates.
137        </p>
138        <p>
139            If for some reason you are unable to upgrade your PHP version, you will need to
140            <a href="https://www.mediawiki.org/wiki/Download">download</a> an older version of
141            MediaWiki from our website. See our
142            <a href="https://www.mediawiki.org/wiki/Compatibility#PHP">compatibility page</a>
143            for details of which versions are compatible with prior versions of PHP.
144        </p>
145HTML;
146            // phpcs:enable Generic.Files.LineLength
147            $this->triggerError(
148                $web,
149                $cliText
150            );
151        }
152    }
153
154    /**
155     * Displays an error, if the vendor/autoload.php file could not be found.
156     */
157    function checkVendorExistence() {
158        if ( !file_exists( dirname( __FILE__ ) . '/../vendor/autoload.php' ) ) {
159            $cliText = "Error: You are missing some dependencies. \n"
160                . "MediaWiki has dependencies that need to be installed via Composer\n"
161                . "or from a separate repository. Please see\n"
162                . "https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries\n"
163                . "for help with installing them.";
164
165            $web = array();
166            $web['intro'] = "Installing some dependencies is required.";
167            $web['longTitle'] = 'Dependencies';
168            // phpcs:disable Generic.Files.LineLength
169            $web['longHtml'] = <<<HTML
170        <p>
171        MediaWiki has dependencies that need to be installed via Composer
172        or from a separate repository. Please see the
173        <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">instructions
174        for installing external libraries</a> on MediaWiki.org.
175        </p>
176HTML;
177            // phpcs:enable Generic.Files.LineLength
178
179            $this->triggerError( $web, $cliText );
180        }
181    }
182
183    /**
184     * Displays an error, if a PHP extension does not exist.
185     */
186    function checkExtensionExistence() {
187        $missingExtensions = array();
188        foreach ( $this->functionsExtensionsMapping as $function => $extension ) {
189            if ( !function_exists( $function ) ) {
190                $missingExtensions[] = array( $extension );
191            }
192        }
193
194        // Special case: either of those is required, but only on 32-bit systems (T391169)
195        if ( PHP_INT_SIZE < 8 && !extension_loaded( 'gmp' ) && !extension_loaded( 'bcmath' ) ) {
196            $missingExtensions[] = array( 'bcmath', 'gmp' );
197        }
198
199        if ( $missingExtensions ) {
200            $missingExtText = '';
201            $missingExtHtml = '';
202            $baseUrl = 'https://www.php.net';
203            foreach ( $missingExtensions as $extNames ) {
204                $plaintextLinks = array();
205                $htmlLinks = array();
206                foreach ( $extNames as $ext ) {
207                    $plaintextLinks[] = "$ext <$baseUrl/$ext>";
208                    $htmlLinks[] = "<b>$ext</b> (<a href=\"$baseUrl/$ext\">more information</a>)";
209                }
210
211                $missingExtText .= ' * ' . implode( ' or ', $plaintextLinks ) . "\n";
212                $missingExtHtml .= "<li>" . implode( ' or ', $htmlLinks ) . "</li>";
213            }
214
215            $cliText = "Error: Missing one or more required PHP extensions. Please see\n"
216                . "https://www.mediawiki.org/wiki/Manual:Installation_requirements#PHP\n"
217                . "for help with installing them.\n"
218                . "Please install or enable:\n" . $missingExtText;
219
220            $web = array();
221            $web['intro'] = "Installing some PHP extensions is required.";
222            $web['longTitle'] = 'Required PHP extensions';
223            $web['longHtml'] = <<<HTML
224        <p>
225        You are missing one or more extensions to PHP that MediaWiki requires to run. Please see the
226        <a href="https://www.mediawiki.org/wiki/Manual:Installation_requirements#PHP">PHP
227        installation requirements</a> on MediaWiki.org.
228        </p>
229        <p>Please install or enable:</p>
230        <ul>
231        $missingExtHtml
232        </ul>
233HTML;
234
235            $this->triggerError( $web, $cliText );
236        }
237    }
238
239    /**
240     * Output headers that prevents error pages to be cached.
241     */
242    function outputHTMLHeader() {
243        $protocol = isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
244
245        header( "$protocol 500 MediaWiki configuration Error" );
246        // Don't cache error pages! They cause no end of trouble...
247        header( 'Cache-Control: no-cache' );
248    }
249
250    /**
251     * Returns an error page, which is suitable for output to the end user via a web browser.
252     *
253     * @param string $introText
254     * @param string $longTitle
255     * @param string $longHtml
256     * @return string
257     */
258    function getIndexErrorOutput( $introText, $longTitle, $longHtml ) {
259        $encLogo =
260            htmlspecialchars( str_replace( '//', '/', $this->scriptPath . '/' ) .
261                'resources/assets/mediawiki.png' );
262
263        $introHtml = htmlspecialchars( $introText );
264        $longTitleHtml = htmlspecialchars( $longTitle );
265
266        header( 'Content-type: text/html; charset=UTF-8' );
267
268        $finalOutput = <<<HTML
269<!DOCTYPE html>
270<html lang="en" dir="ltr">
271    <head>
272        <meta charset="UTF-8" />
273        <title>MediaWiki {$this->mwVersion}</title>
274        <style media="screen">
275            body {
276                color: #000;
277                background-color: #fff;
278                font-family: sans-serif;
279                padding: 2em;
280                text-align: center;
281            }
282            p, img, h1, h2, ul {
283                text-align: left;
284                margin: 0.5em 0 1em;
285            }
286            h1 {
287                font-size: 120%;
288            }
289            h2 {
290                font-size: 110%;
291            }
292        </style>
293    </head>
294    <body>
295        <img src="{$encLogo}" alt="The MediaWiki logo" />
296        <h1>MediaWiki {$this->mwVersion} internal error</h1>
297        <p>
298            {$introHtml}
299        </p>
300        <h2>{$longTitleHtml}</h2>
301        {$longHtml}
302    </body>
303</html>
304HTML;
305
306        return $finalOutput;
307    }
308
309    /**
310     * Display something vaguely comprehensible in the event of a totally unrecoverable error.
311     * Does not assume access to *anything*; no globals, no autoloader, no database, no localisation.
312     * Safe for PHP4 (and putting this here means that WebStart.php and GlobalSettings.php
313     * no longer need to be).
314     *
315     * This function immediately terminates the PHP process.
316     *
317     * @param string[] $web
318     *  - (string) intro: Short error message, displayed on top.
319     *  - (string) longTitle: Title for the longer message.
320     *  - (string) longHtml: The longer message, as raw HTML.
321     * @param string $cliText
322     */
323    function triggerError( $web, $cliText ) {
324        if ( $this->format === 'html' ) {
325            // Used by index.php and mw-config/index.php
326            $this->outputHTMLHeader();
327            $finalOutput = $this->getIndexErrorOutput(
328                $web['intro'],
329                $web['longTitle'],
330                $web['longHtml']
331            );
332        } else {
333            // Used by Maintenance.php (CLI)
334            $finalOutput = $cliText;
335        }
336
337        echo "$finalOutput\n";
338        die( 1 );
339    }
340}
341
342/**
343 * Check PHP version and that external dependencies are installed, and
344 * display an informative error if either condition is not satisfied.
345 *
346 * @param string $format One of "text" or "html"
347 * @param string $scriptPath Used when an error is formatted as HTML.
348 */
349function wfEntryPointCheck( $format = 'text', $scriptPath = '/' ) {
350    $phpVersionCheck = new PHPVersionCheck();
351    $phpVersionCheck->setFormat( $format );
352    $phpVersionCheck->setScriptPath( $scriptPath );
353    $phpVersionCheck->checkRequiredPHPVersion();
354    $phpVersionCheck->checkVendorExistence();
355    $phpVersionCheck->checkExtensionExistence();
356}