MediaWiki  1.28.0
checkSyntax.php
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/Maintenance.php';
25 
31 class CheckSyntax extends Maintenance {
32 
33  // List of files we're going to check
34  private $mFiles = [], $mFailures = [], $mWarnings = [];
35  private $mIgnorePaths = [], $mNoStyleCheckPaths = [];
36 
37  public function __construct() {
38  parent::__construct();
39  $this->addDescription( 'Check syntax for all PHP files in MediaWiki' );
40  $this->addOption( 'with-extensions', 'Also recurse the extensions folder' );
41  $this->addOption(
42  'path',
43  'Specific path (file or directory) to check, either with absolute path or '
44  . 'relative to the root of this MediaWiki installation',
45  false,
46  true
47  );
48  $this->addOption(
49  'list-file',
50  'Text file containing list of files or directories to check',
51  false,
52  true
53  );
54  $this->addOption(
55  'modified',
56  'Check only files that were modified (requires Git command-line client)'
57  );
58  $this->addOption( 'syntax-only', 'Check for syntax validity only, skip code style warnings' );
59  }
60 
61  public function getDbType() {
62  return Maintenance::DB_NONE;
63  }
64 
65  public function execute() {
66  $this->buildFileList();
67 
68  $this->output( "Checking syntax (using php -l, this can take a long time)\n" );
69  foreach ( $this->mFiles as $f ) {
70  $this->checkFileWithCli( $f );
71  if ( !$this->hasOption( 'syntax-only' ) ) {
72  $this->checkForMistakes( $f );
73  }
74  }
75  $this->output( "\nDone! " . count( $this->mFiles ) . " files checked, " .
76  count( $this->mFailures ) . " failures and " . count( $this->mWarnings ) .
77  " warnings found\n" );
78  }
79 
83  private function buildFileList() {
84  global $IP;
85 
86  $this->mIgnorePaths = [
87  ];
88 
89  $this->mNoStyleCheckPaths = [
90  // Third-party code we don't care about
91  "/activemq_stomp/",
92  "EmailPage/PHPMailer",
93  "FCKeditor/fckeditor/",
94  '\bphplot-',
95  "/svggraph/",
96  "\bjsmin.php$",
97  "PEAR/File_Ogg/",
98  "QPoll/Excel/",
99  "/geshi/",
100  "/smarty/",
101  ];
102 
103  if ( $this->hasOption( 'path' ) ) {
104  $path = $this->getOption( 'path' );
105  if ( !$this->addPath( $path ) ) {
106  $this->error( "Error: can't find file or directory $path\n", true );
107  }
108 
109  return; // process only this path
110  } elseif ( $this->hasOption( 'list-file' ) ) {
111  $file = $this->getOption( 'list-file' );
112  MediaWiki\suppressWarnings();
113  $f = fopen( $file, 'r' );
114  MediaWiki\restoreWarnings();
115  if ( !$f ) {
116  $this->error( "Can't open file $file\n", true );
117  }
118  $path = trim( fgets( $f ) );
119  while ( $path ) {
120  $this->addPath( $path );
121  }
122  fclose( $f );
123 
124  return;
125  } elseif ( $this->hasOption( 'modified' ) ) {
126  $this->output( "Retrieving list from Git... " );
127  $files = $this->getGitModifiedFiles( $IP );
128  $this->output( "done\n" );
129  foreach ( $files as $file ) {
130  if ( $this->isSuitableFile( $file ) && !is_dir( $file ) ) {
131  $this->mFiles[] = $file;
132  }
133  }
134 
135  return;
136  }
137 
138  $this->output( 'Building file list...', 'listfiles' );
139 
140  // Only check files in these directories.
141  // Don't just put $IP, because the recursive dir thingie goes into all subdirs
142  $dirs = [
143  $IP . '/includes',
144  $IP . '/mw-config',
145  $IP . '/languages',
146  $IP . '/maintenance',
147  $IP . '/skins',
148  ];
149  if ( $this->hasOption( 'with-extensions' ) ) {
150  $dirs[] = $IP . '/extensions';
151  }
152 
153  foreach ( $dirs as $d ) {
154  $this->addDirectoryContent( $d );
155  }
156 
157  // Manually add two user-editable files that are usually sources of problems
158  if ( file_exists( "$IP/LocalSettings.php" ) ) {
159  $this->mFiles[] = "$IP/LocalSettings.php";
160  }
161 
162  $this->output( 'done.', 'listfiles' );
163  }
164 
170  private function getGitModifiedFiles( $path ) {
171 
172  global $wgMaxShellMemory;
173 
174  if ( !is_dir( "$path/.git" ) ) {
175  $this->error( "Error: Not a Git repository!\n", true );
176  }
177 
178  // git diff eats memory.
179  $oldMaxShellMemory = $wgMaxShellMemory;
180  if ( $wgMaxShellMemory < 1024000 ) {
181  $wgMaxShellMemory = 1024000;
182  }
183 
184  $ePath = wfEscapeShellArg( $path );
185 
186  // Find an ancestor in common with master (rather than just using its HEAD)
187  // to prevent files only modified there from showing up in the list.
188  $cmd = "cd $ePath && git merge-base master HEAD";
189  $retval = 0;
190  $output = wfShellExec( $cmd, $retval );
191  if ( $retval !== 0 ) {
192  $this->error( "Error retrieving base SHA1 from Git!\n", true );
193  }
194 
195  // Find files in the working tree that changed since then.
196  $eBase = wfEscapeShellArg( rtrim( $output, "\n" ) );
197  $cmd = "cd $ePath && git diff --name-only --diff-filter AM $eBase";
198  $retval = 0;
199  $output = wfShellExec( $cmd, $retval );
200  if ( $retval !== 0 ) {
201  $this->error( "Error retrieving list from Git!\n", true );
202  }
203 
204  $wgMaxShellMemory = $oldMaxShellMemory;
205 
206  $arr = [];
207  $filename = strtok( $output, "\n" );
208  while ( $filename !== false ) {
209  if ( $filename !== '' ) {
210  $arr[] = "$path/$filename";
211  }
212  $filename = strtok( "\n" );
213  }
214 
215  return $arr;
216  }
217 
223  private function isSuitableFile( $file ) {
224  $file = str_replace( '\\', '/', $file );
225  $ext = pathinfo( $file, PATHINFO_EXTENSION );
226  if ( $ext != 'php' && $ext != 'inc' && $ext != 'php5' ) {
227  return false;
228  }
229  foreach ( $this->mIgnorePaths as $regex ) {
230  $m = [];
231  if ( preg_match( "~{$regex}~", $file, $m ) ) {
232  return false;
233  }
234  }
235 
236  return true;
237  }
238 
244  private function addPath( $path ) {
245  global $IP;
246 
247  return $this->addFileOrDir( $path ) || $this->addFileOrDir( "$IP/$path" );
248  }
249 
255  private function addFileOrDir( $path ) {
256  if ( is_dir( $path ) ) {
257  $this->addDirectoryContent( $path );
258  } elseif ( file_exists( $path ) ) {
259  $this->mFiles[] = $path;
260  } else {
261  return false;
262  }
263 
264  return true;
265  }
266 
272  private function addDirectoryContent( $dir ) {
273  $iterator = new RecursiveIteratorIterator(
274  new RecursiveDirectoryIterator( $dir ),
275  RecursiveIteratorIterator::SELF_FIRST
276  );
277  foreach ( $iterator as $file ) {
278  if ( $this->isSuitableFile( $file->getRealPath() ) ) {
279  $this->mFiles[] = $file->getRealPath();
280  }
281  }
282  }
283 
289  private function checkFileWithCli( $file ) {
290  $res = exec( 'php -l ' . wfEscapeShellArg( $file ) );
291  if ( strpos( $res, 'No syntax errors detected' ) === false ) {
292  $this->mFailures[$file] = $res;
293  $this->output( $res . "\n" );
294 
295  return false;
296  }
297 
298  return true;
299  }
300 
307  private function checkForMistakes( $file ) {
308  foreach ( $this->mNoStyleCheckPaths as $regex ) {
309  $m = [];
310  if ( preg_match( "~{$regex}~", $file, $m ) ) {
311  return;
312  }
313  }
314 
315  $text = file_get_contents( $file );
316  $tokens = token_get_all( $text );
317 
318  $this->checkEvilToken( $file, $tokens, '@', 'Error supression operator (@)' );
319  $this->checkRegex( $file, $text, '/^[\s\r\n]+<\?/', 'leading whitespace' );
320  $this->checkRegex( $file, $text, '/\?>[\s\r\n]*$/', 'trailing ?>' );
321  $this->checkRegex( $file, $text, '/^[\xFF\xFE\xEF]/', 'byte-order mark' );
322  }
323 
324  private function checkRegex( $file, $text, $regex, $desc ) {
325  if ( !preg_match( $regex, $text ) ) {
326  return;
327  }
328 
329  if ( !isset( $this->mWarnings[$file] ) ) {
330  $this->mWarnings[$file] = [];
331  }
332  $this->mWarnings[$file][] = $desc;
333  $this->output( "Warning in file $file: $desc found.\n" );
334  }
335 
336  private function checkEvilToken( $file, $tokens, $evilToken, $desc ) {
337  if ( !in_array( $evilToken, $tokens ) ) {
338  return;
339  }
340 
341  if ( !isset( $this->mWarnings[$file] ) ) {
342  $this->mWarnings[$file] = [];
343  }
344  $this->mWarnings[$file][] = $desc;
345  $this->output( "Warning in file $file: $desc found.\n" );
346  }
347 }
348 
349 $maintClass = "CheckSyntax";
350 require_once RUN_MAINTENANCE_IF_MAIN;
checkEvilToken($file, $tokens, $evilToken, $desc)
addDirectoryContent($dir)
Add all suitable files in given directory or its subdirectories to the file list. ...
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:57
buildFileList()
Build the list of files we'll check for syntax errors.
Definition: checkSyntax.php:83
if(count($args)==0) $dir
$IP
Definition: WebStart.php:58
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
Maintenance script to check syntax of all PHP files in MediaWiki.
Definition: checkSyntax.php:31
$files
hasOption($name)
Checks to see if a particular param exists.
wfShellExec($cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
checkFileWithCli($file)
Check a file for syntax errors using php -l.
checkRegex($file, $text, $regex, $desc)
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
addPath($path)
Add given path to file list, searching it in include path if needed.
$res
Definition: database.txt:21
getGitModifiedFiles($path)
Returns a list of tracked files in a Git work tree differing from the master branch.
checkForMistakes($file)
Check a file for non-fatal coding errors, such as byte-order marks in the beginning or pointless ...
$tokens
addDescription($text)
Set the description text.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
getOption($name, $default=null)
Get an option, or return the default.
output($out, $channel=null)
Throw some output to the user.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1046
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
error($err, $die=0)
Throw an error to the user.
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
$maintClass
addFileOrDir($path)
Add given file to file list, or, if it's a directory, add its content.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition: hooks.txt:242
isSuitableFile($file)
Returns true if $file is of a type we can check.