Merge "Allow findHooks.php to compare parameter count of hooks"
[lhc/web/wiklou.git] / maintenance / findHooks.php
1 <?php
2 /**
3 * Simple script that try to find documented hook and hooks actually
4 * in the code and show what's missing.
5 *
6 * This script assumes that:
7 * - hooks names in hooks.txt are at the beginning of a line and single quoted.
8 * - hooks names in code are the first parameter of wfRunHooks.
9 *
10 * if --online option is passed, the script will compare the hooks in the code
11 * with the ones at http://www.mediawiki.org/wiki/Manual:Hooks
12 *
13 * Any instance of wfRunHooks that doesn't meet these parameters will be noted.
14 *
15 * Copyright © Antoine Musso
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License along
28 * with this program; if not, write to the Free Software Foundation, Inc.,
29 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 * http://www.gnu.org/copyleft/gpl.html
31 *
32 * @file
33 * @ingroup Maintenance
34 * @author Antoine Musso <hashar at free dot fr>
35 */
36
37 require_once __DIR__ . '/Maintenance.php';
38
39 /**
40 * Maintenance script that compares documented and actually present mismatches.
41 *
42 * @ingroup Maintenance
43 */
44 class FindHooks extends Maintenance {
45 /*
46 * Hooks that are ignored
47 */
48 protected static $ignore = array( 'testRunLegacyHooks' );
49
50 public function __construct() {
51 parent::__construct();
52 $this->mDescription = 'Find hooks that are undocumented, missing, or just plain wrong';
53 $this->addOption( 'online', 'Check against MediaWiki.org hook documentation' );
54 }
55
56 public function getDbType() {
57 return Maintenance::DB_NONE;
58 }
59
60 public function execute() {
61 global $IP;
62
63 $documentedHooks = $this->getHooksFromDoc( $IP . '/docs/hooks.txt' );
64 $potentialHooks = array();
65 $bad = array();
66
67 // TODO: Don't hardcode the list of directories
68 $pathinc = array(
69 $IP . '/',
70 $IP . '/includes/',
71 $IP . '/includes/actions/',
72 $IP . '/includes/api/',
73 $IP . '/includes/cache/',
74 $IP . '/includes/changes/',
75 $IP . '/includes/changetags/',
76 $IP . '/includes/clientpool/',
77 $IP . '/includes/content/',
78 $IP . '/includes/context/',
79 $IP . '/includes/dao/',
80 $IP . '/includes/db/',
81 $IP . '/includes/debug/',
82 $IP . '/includes/deferred/',
83 $IP . '/includes/diff/',
84 $IP . '/includes/exception/',
85 $IP . '/includes/externalstore/',
86 $IP . '/includes/filebackend/',
87 $IP . '/includes/filerepo/',
88 $IP . '/includes/filerepo/file/',
89 $IP . '/includes/gallery/',
90 $IP . '/includes/htmlform/',
91 $IP . '/includes/installer/',
92 $IP . '/includes/interwiki/',
93 $IP . '/includes/jobqueue/',
94 $IP . '/includes/json/',
95 $IP . '/includes/logging/',
96 $IP . '/includes/mail/',
97 $IP . '/includes/media/',
98 $IP . '/includes/page/',
99 $IP . '/includes/parser/',
100 $IP . '/includes/password/',
101 $IP . '/includes/rcfeed/',
102 $IP . '/includes/resourceloader/',
103 $IP . '/includes/revisiondelete/',
104 $IP . '/includes/search/',
105 $IP . '/includes/site/',
106 $IP . '/includes/skins/',
107 $IP . '/includes/specialpage/',
108 $IP . '/includes/specials/',
109 $IP . '/includes/upload/',
110 $IP . '/includes/utils/',
111 $IP . '/languages/',
112 $IP . '/maintenance/',
113 $IP . '/maintenance/language/',
114 $IP . '/tests/',
115 $IP . '/tests/parser/',
116 $IP . '/tests/phpunit/suites/',
117 );
118
119 foreach ( $pathinc as $dir ) {
120 $potentialHooks = array_merge( $potentialHooks, $this->getHooksFromPath( $dir ) );
121 $bad = array_merge( $bad, $this->getBadHooksFromPath( $dir ) );
122 }
123
124 $documented = array_keys( $documentedHooks );
125 $potential = array_keys( $potentialHooks );
126 $potential = array_unique( $potential );
127 $bad = array_diff( array_unique( $bad ), self::$ignore );
128 $todo = array_diff( $potential, $documented, self::$ignore );
129 $deprecated = array_diff( $documented, $potential, self::$ignore );
130
131 // Check parameter count
132 $badParameter = array();
133 foreach ( $potentialHooks as $hook => $args ) {
134 if ( !isset( $documentedHooks[$hook] ) ) {
135 // Not documented, but that will also be in $todo
136 continue;
137 }
138 $argsDoc = $documentedHooks[$hook];
139 if ( $args === 'unknown' || $argsDoc === 'unknown' ) {
140 // Could not get parameter information
141 continue;
142 }
143 if ( count( $argsDoc ) !== count( $args ) ) {
144 $badParameter[] = $hook . ': Doc: ' . count( $argsDoc ) . ' vs. Code: ' . count( $args );
145 }
146 }
147
148 // let's show the results:
149 $this->printArray( 'Undocumented', $todo );
150 $this->printArray( 'Documented and not found', $deprecated );
151 $this->printArray( 'Unclear hook calls', $bad );
152 $this->printArray( 'Different parameter count', $badParameter );
153
154 if ( count( $todo ) == 0 && count( $deprecated ) == 0 && count( $bad ) == 0
155 && count( $badParameter ) == 0
156 ) {
157 $this->output( "Looks good!\n" );
158 } else {
159 $this->error( 'The script finished with errors.', 1 );
160 }
161 }
162
163 /**
164 * Get the hook documentation, either locally or from MediaWiki.org
165 * @param string $doc
166 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
167 */
168 private function getHooksFromDoc( $doc ) {
169 if ( $this->hasOption( 'online' ) ) {
170 return $this->getHooksFromOnlineDoc();
171 } else {
172 return $this->getHooksFromLocalDoc( $doc );
173 }
174 }
175
176 /**
177 * Get hooks from a local file (for example docs/hooks.txt)
178 * @param string $doc Filename to look in
179 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
180 */
181 private function getHooksFromLocalDoc( $doc ) {
182 $m = array();
183 $content = file_get_contents( $doc );
184 preg_match_all(
185 "/\n'(.*?)':.*((?:\n.+)*)/",
186 $content,
187 $m,
188 PREG_SET_ORDER
189 );
190
191 // Extract the documented parameter
192 $hooks = array();
193 foreach ( $m as $match ) {
194 $args = array();
195 if ( isset( $match[2] ) ) {
196 $n = array();
197 if ( preg_match_all( "/\n(&?\\$\w+):.+/", $match[2], $n ) ) {
198 $args = $n[1];
199 }
200 }
201 $hooks[$match[1]] = $args;
202 }
203 return $hooks;
204 }
205
206 /**
207 * Get hooks from www.mediawiki.org using the API
208 * @return array Array: key => hook name; value => string 'unknown'
209 */
210 private function getHooksFromOnlineDoc() {
211 $allhooks = $this->getHooksFromOnlineDocCategory( 'MediaWiki_hooks' );
212 $removed = $this->getHooksFromOnlineDocCategory( 'Removed_hooks' );
213 return array_diff_key( $allhooks, $removed );
214 }
215
216 /**
217 * @param string $title
218 * @return array
219 */
220 private function getHooksFromOnlineDocCategory( $title ) {
221 $params = array(
222 'action' => 'query',
223 'list' => 'categorymembers',
224 'cmtitle' => "Category:$title",
225 'cmlimit' => 500,
226 'format' => 'json',
227 'continue' => '',
228 );
229
230 $retval = array();
231 while ( true ) {
232 $json = Http::get(
233 wfAppendQuery( 'http://www.mediawiki.org/w/api.php', $params ),
234 array(),
235 __METHOD__
236 );
237 $data = FormatJson::decode( $json, true );
238 foreach ( $data['query']['categorymembers'] as $page ) {
239 if ( preg_match( '/Manual\:Hooks\/([a-zA-Z0-9- :]+)/', $page['title'], $m ) ) {
240 // parameters are unknown, because that needs parsing of wikitext
241 $retval[str_replace( ' ', '_', $m[1] )] = 'unknown';
242 }
243 }
244 if ( !isset( $data['continue'] ) ) {
245 return $retval;
246 }
247 $params = array_replace( $params, $data['continue'] );
248 }
249 }
250
251 /**
252 * Get hooks from a PHP file
253 * @param string $file Full filename to the PHP file.
254 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
255 */
256 private function getHooksFromFile( $file ) {
257 $content = file_get_contents( $file );
258 $m = array();
259 preg_match_all(
260 // All functions which runs hooks
261 '/(?:wfRunHooks|Hooks\:\:run|ContentHandler\:\:runLegacyHooks)\s*\(\s*' .
262 // First argument is the hook name as string
263 '([\'"])(.*?)\1' .
264 // Comma for second argument
265 '(?:\s*(,))?' .
266 // Second argument must start with array to be processed
267 '(?:\s*array\s*\(' .
268 // Matching inside array - allows one deep of brackets
269 '((?:[^\(\)]|\([^\(\)]*\))*)' .
270 // End
271 '\))?/',
272 $content,
273 $m,
274 PREG_SET_ORDER
275 );
276
277 // Extract parameter
278 $hooks = array();
279 foreach ( $m as $match ) {
280 $args = array();
281 if ( isset( $match[4] ) ) {
282 $n = array();
283 if ( preg_match_all( '/((?:[^,\(\)]|\([^\(\)]*\))+)/', $match[4], $n ) ) {
284 $args = array_map( 'trim', $n[1] );
285 }
286 } elseif ( isset( $match[3] ) ) {
287 // Found a parameter for Hooks::run,
288 // but could not extract the hooks argument,
289 // because there are given by a variable
290 $args = 'unknown';
291 }
292 $hooks[$match[2]] = $args;
293 }
294
295 return $hooks;
296 }
297
298 /**
299 * Get hooks from the source code.
300 * @param string $path Directory where the include files can be found
301 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
302 */
303 private function getHooksFromPath( $path ) {
304 $hooks = array();
305 $dh = opendir( $path );
306 if ( $dh ) {
307 while ( ( $file = readdir( $dh ) ) !== false ) {
308 if ( filetype( $path . $file ) == 'file' ) {
309 $hooks = array_merge( $hooks, $this->getHooksFromFile( $path . $file ) );
310 }
311 }
312 closedir( $dh );
313 }
314
315 return $hooks;
316 }
317
318 /**
319 * Get bad hooks (where the hook name could not be determined) from a PHP file
320 * @param string $file Full filename to the PHP file.
321 * @return array Array of bad wfRunHooks() lines
322 */
323 private function getBadHooksFromFile( $file ) {
324 $content = file_get_contents( $file );
325 $m = array();
326 # We want to skip the "function wfRunHooks()" one. :)
327 preg_match_all( '/(?<!function )wfRunHooks\(\s*[^\s\'"].*/', $content, $m );
328 $list = array();
329 foreach ( $m[0] as $match ) {
330 $list[] = $match . "(" . $file . ")";
331 }
332
333 return $list;
334 }
335
336 /**
337 * Get bad hooks from the source code.
338 * @param string $path Directory where the include files can be found
339 * @return array Array of bad wfRunHooks() lines
340 */
341 private function getBadHooksFromPath( $path ) {
342 $hooks = array();
343 $dh = opendir( $path );
344 if ( $dh ) {
345 while ( ( $file = readdir( $dh ) ) !== false ) {
346 # We don't want to read this file as it contains bad calls to wfRunHooks()
347 if ( filetype( $path . $file ) == 'file' && !$path . $file == __FILE__ ) {
348 $hooks = array_merge( $hooks, $this->getBadHooksFromFile( $path . $file ) );
349 }
350 }
351 closedir( $dh );
352 }
353
354 return $hooks;
355 }
356
357 /**
358 * Nicely output the array
359 * @param string $msg A message to show before the value
360 * @param array $arr
361 * @param bool $sort Whether to sort the array (Default: true)
362 */
363 private function printArray( $msg, $arr, $sort = true ) {
364 if ( $sort ) {
365 asort( $arr );
366 }
367
368 foreach ( $arr as $v ) {
369 $this->output( "$msg: $v\n" );
370 }
371 }
372 }
373
374 $maintClass = 'FindHooks';
375 require_once RUN_MAINTENANCE_IF_MAIN;