3 * Check syntax of all PHP files in MediaWiki
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup Maintenance
24 require_once( dirname( __FILE__
) . '/Maintenance.php' );
26 class CheckSyntax
extends Maintenance
{
28 // List of files we're going to check
29 private $mFiles = array(), $mFailures = array(), $mWarnings = array();
30 private $mIgnorePaths = array(), $mNoStyleCheckPaths = array();
32 public function __construct() {
33 parent
::__construct();
34 $this->mDescription
= "Check syntax for all PHP files in MediaWiki";
35 $this->addOption( 'with-extensions', 'Also recurse the extensions folder' );
36 $this->addOption( 'path', 'Specific path (file or directory) to check, either with absolute path or relative to the root of this MediaWiki installation',
38 $this->addOption( 'list-file', 'Text file containing list of files or directories to check', false, true );
39 $this->addOption( 'modified', 'Check only files that were modified (requires Git command-line client)' );
40 $this->addOption( 'syntax-only', 'Check for syntax validity only, skip code style warnings' );
43 public function getDbType() {
44 return Maintenance
::DB_NONE
;
47 public function execute() {
48 $this->buildFileList();
50 // ParseKit is broken on PHP 5.3+, disabled until this is fixed
51 $useParseKit = function_exists( 'parsekit_compile_file' ) && version_compare( PHP_VERSION
, '5.3', '<' );
53 $str = 'Checking syntax (using ' . ( $useParseKit ?
54 'parsekit' : ' php -l, this can take a long time' ) . ")\n";
55 $this->output( $str );
56 foreach ( $this->mFiles
as $f ) {
58 $this->checkFileWithParsekit( $f );
60 $this->checkFileWithCli( $f );
62 if ( !$this->hasOption( 'syntax-only' ) ) {
63 $this->checkForMistakes( $f );
66 $this->output( "\nDone! " . count( $this->mFiles
) . " files checked, " .
67 count( $this->mFailures
) . " failures and " . count( $this->mWarnings
) .
68 " warnings found\n" );
72 * Build the list of files we'll check for syntax errors
74 private function buildFileList() {
77 $this->mIgnorePaths
= array(
78 // Compat stuff, explodes on PHP 5.3
79 "includes/NamespaceCompat.php$",
82 $this->mNoStyleCheckPaths
= array(
83 // Third-party code we don't care about
85 "EmailPage/PHPMailer",
86 "FCKeditor/fckeditor/",
96 if ( $this->hasOption( 'path' ) ) {
97 $path = $this->getOption( 'path' );
98 if ( !$this->addPath( $path ) ) {
99 $this->error( "Error: can't find file or directory $path\n", true );
101 return; // process only this path
102 } elseif ( $this->hasOption( 'list-file' ) ) {
103 $file = $this->getOption( 'list-file' );
104 wfSuppressWarnings();
105 $f = fopen( $file, 'r' );
108 $this->error( "Can't open file $file\n", true );
110 $path = trim( fgets( $f ) );
112 $this->addPath( $path );
116 } elseif ( $this->hasOption( 'modified' ) ) {
117 $this->output( "Retrieving list from Git... " );
118 $files = $this->getGitModifiedFiles( $IP );
119 $this->output( "done\n" );
120 foreach ( $files as $file ) {
121 if ( $this->isSuitableFile( $file ) && !is_dir( $file ) ) {
122 $this->mFiles
[] = $file;
128 $this->output( 'Building file list...', 'listfiles' );
130 // Only check files in these directories.
131 // Don't just put $IP, because the recursive dir thingie goes into all subdirs
136 $IP . '/maintenance',
139 if ( $this->hasOption( 'with-extensions' ) ) {
140 $dirs[] = $IP . '/extensions';
143 foreach ( $dirs as $d ) {
144 $this->addDirectoryContent( $d );
147 // Manually add two user-editable files that are usually sources of problems
148 if ( file_exists( "$IP/LocalSettings.php" ) ) {
149 $this->mFiles
[] = "$IP/LocalSettings.php";
151 if ( file_exists( "$IP/AdminSettings.php" ) ) {
152 $this->mFiles
[] = "$IP/AdminSettings.php";
155 $this->output( 'done.', 'listfiles' );
159 * Returns a list of tracked files in a Git work tree differing from the master branch.
160 * @param $path string: Path to the repository
161 * @return array: Resulting list of changed files
163 private function getGitModifiedFiles( $path ) {
165 global $wgMaxShellMemory;
167 if ( !is_dir( "$path/.git" ) ) {
168 $this->error( "Error: Not a Git repository!\n", true );
171 // git diff eats memory.
172 $oldMaxShellMemory = $wgMaxShellMemory;
173 if ( $wgMaxShellMemory < 1024000 ) {
174 $wgMaxShellMemory = 1024000;
177 $ePath = wfEscapeShellArg( $path );
179 // Find an ancestor in common with master (rather than just using its HEAD)
180 // to prevent files only modified there from showing up in the list.
181 $cmd = "cd $ePath && git merge-base master HEAD";
183 $output = wfShellExec( $cmd, $retval );
184 if ( $retval !== 0 ) {
185 $this->error( "Error retrieving base SHA1 from Git!\n", true );
188 // Find files in the working tree that changed since then.
189 $eBase = wfEscapeShellArg( rtrim( $output, "\n" ) );
190 $cmd = "cd $ePath && git diff --name-only --diff-filter AM $eBase";
192 $output = wfShellExec( $cmd, $retval );
193 if ( $retval !== 0 ) {
194 $this->error( "Error retrieving list from Git!\n", true );
197 $wgMaxShellMemory = $oldMaxShellMemory;
200 $filename = strtok( $output, "\n" );
201 while ( $filename !== false ) {
202 if ( $filename !== '' ) {
203 $arr[] = "$path/$filename";
205 $filename = strtok( "\n" );
212 * Returns true if $file is of a type we can check
213 * @param $file string
216 private function isSuitableFile( $file ) {
217 $file = str_replace( '\\', '/', $file );
218 $ext = pathinfo( $file, PATHINFO_EXTENSION
);
219 if ( $ext != 'php' && $ext != 'inc' && $ext != 'php5' )
221 foreach ( $this->mIgnorePaths
as $regex ) {
223 if ( preg_match( "~{$regex}~", $file, $m ) )
230 * Add given path to file list, searching it in include path if needed
231 * @param $path string
234 private function addPath( $path ) {
236 return $this->addFileOrDir( $path ) ||
$this->addFileOrDir( "$IP/$path" );
240 * Add given file to file list, or, if it's a directory, add its content
241 * @param $path string
244 private function addFileOrDir( $path ) {
245 if ( is_dir( $path ) ) {
246 $this->addDirectoryContent( $path );
247 } elseif ( file_exists( $path ) ) {
248 $this->mFiles
[] = $path;
256 * Add all suitable files in given directory or its subdirectories to the file list
258 * @param $dir String: directory to process
260 private function addDirectoryContent( $dir ) {
261 $iterator = new RecursiveIteratorIterator(
262 new RecursiveDirectoryIterator( $dir ),
263 RecursiveIteratorIterator
::SELF_FIRST
265 foreach ( $iterator as $file ) {
266 if ( $this->isSuitableFile( $file->getRealPath() ) ) {
267 $this->mFiles
[] = $file->getRealPath();
273 * Check a file for syntax errors using Parsekit. Shamelessly stolen
274 * from tools/lint.php by TimStarling
275 * @param $file String Path to a file to check for syntax errors
278 private function checkFileWithParsekit( $file ) {
279 static $okErrors = array(
280 'Redefining already defined constructor',
281 'Assigning the return value of new by reference is deprecated',
284 parsekit_compile_file( $file, $errors, PARSEKIT_SIMPLE
);
287 foreach ( $errors as $error ) {
288 foreach ( $okErrors as $okError ) {
289 if ( substr( $error['errstr'], 0, strlen( $okError ) ) == $okError ) {
294 $this->output( "Error in $file line {$error['lineno']}: {$error['errstr']}\n" );
295 $this->mFailures
[$file] = $errors;
302 * Check a file for syntax errors using php -l
303 * @param $file String Path to a file to check for syntax errors
306 private function checkFileWithCli( $file ) {
307 $res = exec( 'php -l ' . wfEscapeShellArg( $file ) );
308 if ( strpos( $res, 'No syntax errors detected' ) === false ) {
309 $this->mFailures
[$file] = $res;
310 $this->output( $res . "\n" );
317 * Check a file for non-fatal coding errors, such as byte-order marks in the beginning
318 * or pointless ?> closing tags at the end.
320 * @param $file String String Path to a file to check for errors
323 private function checkForMistakes( $file ) {
324 foreach ( $this->mNoStyleCheckPaths
as $regex ) {
326 if ( preg_match( "~{$regex}~", $file, $m ) )
330 $text = file_get_contents( $file );
331 $tokens = token_get_all( $text );
333 $this->checkEvilToken( $file, $tokens, '@', 'Error supression operator (@)');
334 $this->checkRegex( $file, $text, '/^[\s\r\n]+<\?/', 'leading whitespace' );
335 $this->checkRegex( $file, $text, '/\?>[\s\r\n]*$/', 'trailing ?>' );
336 $this->checkRegex( $file, $text, '/^[\xFF\xFE\xEF]/', 'byte-order mark' );
339 private function checkRegex( $file, $text, $regex, $desc ) {
340 if ( !preg_match( $regex, $text ) ) {
344 if ( !isset( $this->mWarnings
[$file] ) ) {
345 $this->mWarnings
[$file] = array();
347 $this->mWarnings
[$file][] = $desc;
348 $this->output( "Warning in file $file: $desc found.\n" );
351 private function checkEvilToken( $file, $tokens, $evilToken, $desc ) {
352 if ( !in_array( $evilToken, $tokens ) ) {
356 if ( !isset( $this->mWarnings
[$file] ) ) {
357 $this->mWarnings
[$file] = array();
359 $this->mWarnings
[$file][] = $desc;
360 $this->output( "Warning in file $file: $desc found.\n" );
364 $maintClass = "CheckSyntax";
365 require_once( RUN_MAINTENANCE_IF_MAIN
);