PageRenderTime 33ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/maintenance/checkSyntax.php

https://gitlab.com/link233/bootmw
PHP | 350 lines | 244 code | 42 blank | 64 comment | 25 complexity | 47b553d58250aad66e742e8408307624 MD5 | raw file
  1. <?php
  2. /**
  3. * Check syntax of all PHP files in MediaWiki
  4. *
  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.
  9. *
  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.
  14. *
  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
  19. *
  20. * @file
  21. * @ingroup Maintenance
  22. */
  23. require_once __DIR__ . '/Maintenance.php';
  24. /**
  25. * Maintenance script to check syntax of all PHP files in MediaWiki.
  26. *
  27. * @ingroup Maintenance
  28. */
  29. class CheckSyntax extends Maintenance {
  30. // List of files we're going to check
  31. private $mFiles = [], $mFailures = [], $mWarnings = [];
  32. private $mIgnorePaths = [], $mNoStyleCheckPaths = [];
  33. public function __construct() {
  34. parent::__construct();
  35. $this->addDescription( 'Check syntax for all PHP files in MediaWiki' );
  36. $this->addOption( 'with-extensions', 'Also recurse the extensions folder' );
  37. $this->addOption(
  38. 'path',
  39. 'Specific path (file or directory) to check, either with absolute path or '
  40. . 'relative to the root of this MediaWiki installation',
  41. false,
  42. true
  43. );
  44. $this->addOption(
  45. 'list-file',
  46. 'Text file containing list of files or directories to check',
  47. false,
  48. true
  49. );
  50. $this->addOption(
  51. 'modified',
  52. 'Check only files that were modified (requires Git command-line client)'
  53. );
  54. $this->addOption( 'syntax-only', 'Check for syntax validity only, skip code style warnings' );
  55. }
  56. public function getDbType() {
  57. return Maintenance::DB_NONE;
  58. }
  59. public function execute() {
  60. $this->buildFileList();
  61. $this->output( "Checking syntax (using php -l, this can take a long time)\n" );
  62. foreach ( $this->mFiles as $f ) {
  63. $this->checkFileWithCli( $f );
  64. if ( !$this->hasOption( 'syntax-only' ) ) {
  65. $this->checkForMistakes( $f );
  66. }
  67. }
  68. $this->output( "\nDone! " . count( $this->mFiles ) . " files checked, " .
  69. count( $this->mFailures ) . " failures and " . count( $this->mWarnings ) .
  70. " warnings found\n" );
  71. }
  72. /**
  73. * Build the list of files we'll check for syntax errors
  74. */
  75. private function buildFileList() {
  76. global $IP;
  77. $this->mIgnorePaths = [
  78. ];
  79. $this->mNoStyleCheckPaths = [
  80. // Third-party code we don't care about
  81. "/activemq_stomp/",
  82. "EmailPage/PHPMailer",
  83. "FCKeditor/fckeditor/",
  84. '\bphplot-',
  85. "/svggraph/",
  86. "\bjsmin.php$",
  87. "PEAR/File_Ogg/",
  88. "QPoll/Excel/",
  89. "/geshi/",
  90. "/smarty/",
  91. ];
  92. if ( $this->hasOption( 'path' ) ) {
  93. $path = $this->getOption( 'path' );
  94. if ( !$this->addPath( $path ) ) {
  95. $this->error( "Error: can't find file or directory $path\n", true );
  96. }
  97. return; // process only this path
  98. } elseif ( $this->hasOption( 'list-file' ) ) {
  99. $file = $this->getOption( 'list-file' );
  100. MediaWiki\suppressWarnings();
  101. $f = fopen( $file, 'r' );
  102. MediaWiki\restoreWarnings();
  103. if ( !$f ) {
  104. $this->error( "Can't open file $file\n", true );
  105. }
  106. $path = trim( fgets( $f ) );
  107. while ( $path ) {
  108. $this->addPath( $path );
  109. }
  110. fclose( $f );
  111. return;
  112. } elseif ( $this->hasOption( 'modified' ) ) {
  113. $this->output( "Retrieving list from Git... " );
  114. $files = $this->getGitModifiedFiles( $IP );
  115. $this->output( "done\n" );
  116. foreach ( $files as $file ) {
  117. if ( $this->isSuitableFile( $file ) && !is_dir( $file ) ) {
  118. $this->mFiles[] = $file;
  119. }
  120. }
  121. return;
  122. }
  123. $this->output( 'Building file list...', 'listfiles' );
  124. // Only check files in these directories.
  125. // Don't just put $IP, because the recursive dir thingie goes into all subdirs
  126. $dirs = [
  127. $IP . '/includes',
  128. $IP . '/mw-config',
  129. $IP . '/languages',
  130. $IP . '/maintenance',
  131. $IP . '/skins',
  132. ];
  133. if ( $this->hasOption( 'with-extensions' ) ) {
  134. $dirs[] = $IP . '/extensions';
  135. }
  136. foreach ( $dirs as $d ) {
  137. $this->addDirectoryContent( $d );
  138. }
  139. // Manually add two user-editable files that are usually sources of problems
  140. if ( file_exists( "$IP/LocalSettings.php" ) ) {
  141. $this->mFiles[] = "$IP/LocalSettings.php";
  142. }
  143. $this->output( 'done.', 'listfiles' );
  144. }
  145. /**
  146. * Returns a list of tracked files in a Git work tree differing from the master branch.
  147. * @param string $path Path to the repository
  148. * @return array Resulting list of changed files
  149. */
  150. private function getGitModifiedFiles( $path ) {
  151. global $wgMaxShellMemory;
  152. if ( !is_dir( "$path/.git" ) ) {
  153. $this->error( "Error: Not a Git repository!\n", true );
  154. }
  155. // git diff eats memory.
  156. $oldMaxShellMemory = $wgMaxShellMemory;
  157. if ( $wgMaxShellMemory < 1024000 ) {
  158. $wgMaxShellMemory = 1024000;
  159. }
  160. $ePath = wfEscapeShellArg( $path );
  161. // Find an ancestor in common with master (rather than just using its HEAD)
  162. // to prevent files only modified there from showing up in the list.
  163. $cmd = "cd $ePath && git merge-base master HEAD";
  164. $retval = 0;
  165. $output = wfShellExec( $cmd, $retval );
  166. if ( $retval !== 0 ) {
  167. $this->error( "Error retrieving base SHA1 from Git!\n", true );
  168. }
  169. // Find files in the working tree that changed since then.
  170. $eBase = wfEscapeShellArg( rtrim( $output, "\n" ) );
  171. $cmd = "cd $ePath && git diff --name-only --diff-filter AM $eBase";
  172. $retval = 0;
  173. $output = wfShellExec( $cmd, $retval );
  174. if ( $retval !== 0 ) {
  175. $this->error( "Error retrieving list from Git!\n", true );
  176. }
  177. $wgMaxShellMemory = $oldMaxShellMemory;
  178. $arr = [];
  179. $filename = strtok( $output, "\n" );
  180. while ( $filename !== false ) {
  181. if ( $filename !== '' ) {
  182. $arr[] = "$path/$filename";
  183. }
  184. $filename = strtok( "\n" );
  185. }
  186. return $arr;
  187. }
  188. /**
  189. * Returns true if $file is of a type we can check
  190. * @param string $file
  191. * @return bool
  192. */
  193. private function isSuitableFile( $file ) {
  194. $file = str_replace( '\\', '/', $file );
  195. $ext = pathinfo( $file, PATHINFO_EXTENSION );
  196. if ( $ext != 'php' && $ext != 'inc' && $ext != 'php5' ) {
  197. return false;
  198. }
  199. foreach ( $this->mIgnorePaths as $regex ) {
  200. $m = [];
  201. if ( preg_match( "~{$regex}~", $file, $m ) ) {
  202. return false;
  203. }
  204. }
  205. return true;
  206. }
  207. /**
  208. * Add given path to file list, searching it in include path if needed
  209. * @param string $path
  210. * @return bool
  211. */
  212. private function addPath( $path ) {
  213. global $IP;
  214. return $this->addFileOrDir( $path ) || $this->addFileOrDir( "$IP/$path" );
  215. }
  216. /**
  217. * Add given file to file list, or, if it's a directory, add its content
  218. * @param string $path
  219. * @return bool
  220. */
  221. private function addFileOrDir( $path ) {
  222. if ( is_dir( $path ) ) {
  223. $this->addDirectoryContent( $path );
  224. } elseif ( file_exists( $path ) ) {
  225. $this->mFiles[] = $path;
  226. } else {
  227. return false;
  228. }
  229. return true;
  230. }
  231. /**
  232. * Add all suitable files in given directory or its subdirectories to the file list
  233. *
  234. * @param string $dir Directory to process
  235. */
  236. private function addDirectoryContent( $dir ) {
  237. $iterator = new RecursiveIteratorIterator(
  238. new RecursiveDirectoryIterator( $dir ),
  239. RecursiveIteratorIterator::SELF_FIRST
  240. );
  241. foreach ( $iterator as $file ) {
  242. if ( $this->isSuitableFile( $file->getRealPath() ) ) {
  243. $this->mFiles[] = $file->getRealPath();
  244. }
  245. }
  246. }
  247. /**
  248. * Check a file for syntax errors using php -l
  249. * @param string $file Path to a file to check for syntax errors
  250. * @return bool
  251. */
  252. private function checkFileWithCli( $file ) {
  253. $res = exec( 'php -l ' . wfEscapeShellArg( $file ) );
  254. if ( strpos( $res, 'No syntax errors detected' ) === false ) {
  255. $this->mFailures[$file] = $res;
  256. $this->output( $res . "\n" );
  257. return false;
  258. }
  259. return true;
  260. }
  261. /**
  262. * Check a file for non-fatal coding errors, such as byte-order marks in the beginning
  263. * or pointless ?> closing tags at the end.
  264. *
  265. * @param string $file String Path to a file to check for errors
  266. */
  267. private function checkForMistakes( $file ) {
  268. foreach ( $this->mNoStyleCheckPaths as $regex ) {
  269. $m = [];
  270. if ( preg_match( "~{$regex}~", $file, $m ) ) {
  271. return;
  272. }
  273. }
  274. $text = file_get_contents( $file );
  275. $tokens = token_get_all( $text );
  276. $this->checkEvilToken( $file, $tokens, '@', 'Error supression operator (@)' );
  277. $this->checkRegex( $file, $text, '/^[\s\r\n]+<\?/', 'leading whitespace' );
  278. $this->checkRegex( $file, $text, '/\?>[\s\r\n]*$/', 'trailing ?>' );
  279. $this->checkRegex( $file, $text, '/^[\xFF\xFE\xEF]/', 'byte-order mark' );
  280. }
  281. private function checkRegex( $file, $text, $regex, $desc ) {
  282. if ( !preg_match( $regex, $text ) ) {
  283. return;
  284. }
  285. if ( !isset( $this->mWarnings[$file] ) ) {
  286. $this->mWarnings[$file] = [];
  287. }
  288. $this->mWarnings[$file][] = $desc;
  289. $this->output( "Warning in file $file: $desc found.\n" );
  290. }
  291. private function checkEvilToken( $file, $tokens, $evilToken, $desc ) {
  292. if ( !in_array( $evilToken, $tokens ) ) {
  293. return;
  294. }
  295. if ( !isset( $this->mWarnings[$file] ) ) {
  296. $this->mWarnings[$file] = [];
  297. }
  298. $this->mWarnings[$file][] = $desc;
  299. $this->output( "Warning in file $file: $desc found.\n" );
  300. }
  301. }
  302. $maintClass = "CheckSyntax";
  303. require_once RUN_MAINTENANCE_IF_MAIN;