3 * Simple script that try to find documented hook and hooks actually
4 * in the code and show what's missing.
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.
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
13 * Any instance of wfRunHooks that doesn't meet these parameters will be noted.
15 * Copyright © Antoine Musso
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.
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.
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
33 * @ingroup Maintenance
34 * @author Antoine Musso <hashar at free dot fr>
37 require_once __DIR__
. '/Maintenance.php';
40 * Maintenance script that compares documented and actually present mismatches.
42 * @ingroup Maintenance
44 class FindHooks
extends Maintenance
{
45 const FIND_NON_RECURSIVE
= 0;
46 const FIND_RECURSIVE
= 1;
49 * Hooks that are ignored
51 protected static $ignore = [ 'testRunLegacyHooks', 'Test' ];
53 public function __construct() {
54 parent
::__construct();
55 $this->addDescription( 'Find hooks that are undocumented, missing, or just plain wrong' );
56 $this->addOption( 'online', 'Check against MediaWiki.org hook documentation' );
59 public function getDbType() {
60 return Maintenance
::DB_NONE
;
63 public function execute() {
66 $documentedHooks = $this->getHooksFromDoc( $IP . '/docs/hooks.txt' );
75 // Omit $IP/tests/phpunit as it contains hook tests that shouldn't be documented
77 "$IP/tests/phpunit/suites",
83 foreach ( $recurseDirs as $dir ) {
84 $ret = $this->getHooksFromDir( $dir, self
::FIND_RECURSIVE
);
85 $potentialHooks = array_merge( $potentialHooks, $ret['good'] );
86 $badHooks = array_merge( $badHooks, $ret['bad'] );
88 foreach ( $nonRecurseDirs as $dir ) {
89 $ret = $this->getHooksFromDir( $dir );
90 $potentialHooks = array_merge( $potentialHooks, $ret['good'] );
91 $badHooks = array_merge( $badHooks, $ret['bad'] );
94 $documented = array_keys( $documentedHooks );
95 $potential = array_keys( $potentialHooks );
96 $potential = array_unique( $potential );
97 $badHooks = array_diff( array_unique( $badHooks ), self
::$ignore );
98 $todo = array_diff( $potential, $documented, self
::$ignore );
99 $deprecated = array_diff( $documented, $potential, self
::$ignore );
101 // Check parameter count and references
102 $badParameterCount = $badParameterReference = [];
103 foreach ( $potentialHooks as $hook => $args ) {
104 if ( !isset( $documentedHooks[$hook] ) ) {
105 // Not documented, but that will also be in $todo
108 $argsDoc = $documentedHooks[$hook];
109 if ( $args === 'unknown' ||
$argsDoc === 'unknown' ) {
110 // Could not get parameter information
113 if ( count( $argsDoc ) !== count( $args ) ) {
114 $badParameterCount[] = $hook . ': Doc: ' . count( $argsDoc ) . ' vs. Code: ' . count( $args );
116 // Check if & is equal
117 foreach ( $argsDoc as $index => $argDoc ) {
118 $arg = $args[$index];
119 if ( ( $arg[0] === '&' ) !== ( $argDoc[0] === '&' ) ) {
120 $badParameterReference[] = $hook . ': References different: Doc: ' . $argDoc .
121 ' vs. Code: ' . $arg;
128 $this->printArray( 'Undocumented', $todo );
129 $this->printArray( 'Documented and not found', $deprecated );
130 $this->printArray( 'Unclear hook calls', $badHooks );
131 $this->printArray( 'Different parameter count', $badParameterCount );
132 $this->printArray( 'Different parameter reference', $badParameterReference );
134 if ( !$todo && !$deprecated && !$badHooks
135 && !$badParameterCount && !$badParameterReference
137 $this->output( "Looks good!\n" );
139 $this->error( 'The script finished with errors.', 1 );
144 * Get the hook documentation, either locally or from MediaWiki.org
146 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
148 private function getHooksFromDoc( $doc ) {
149 if ( $this->hasOption( 'online' ) ) {
150 return $this->getHooksFromOnlineDoc();
152 return $this->getHooksFromLocalDoc( $doc );
157 * Get hooks from a local file (for example docs/hooks.txt)
158 * @param string $doc Filename to look in
159 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
161 private function getHooksFromLocalDoc( $doc ) {
163 $content = file_get_contents( $doc );
165 "/\n'(.*?)':.*((?:\n.+)*)/",
171 // Extract the documented parameter
173 foreach ( $m as $match ) {
175 if ( isset( $match[2] ) ) {
177 if ( preg_match_all( "/\n(&?\\$\w+):.+/", $match[2], $n ) ) {
181 $hooks[$match[1]] = $args;
187 * Get hooks from www.mediawiki.org using the API
188 * @return array Array: key => hook name; value => string 'unknown'
190 private function getHooksFromOnlineDoc() {
191 $allhooks = $this->getHooksFromOnlineDocCategory( 'MediaWiki_hooks' );
192 $removed = $this->getHooksFromOnlineDocCategory( 'Removed_hooks' );
193 return array_diff_key( $allhooks, $removed );
197 * @param string $title
200 private function getHooksFromOnlineDocCategory( $title ) {
203 'list' => 'categorymembers',
204 'cmtitle' => "Category:$title",
213 wfAppendQuery( 'http://www.mediawiki.org/w/api.php', $params ),
217 $data = FormatJson
::decode( $json, true );
218 foreach ( $data['query']['categorymembers'] as $page ) {
219 if ( preg_match( '/Manual\:Hooks\/([a-zA-Z0-9- :]+)/', $page['title'], $m ) ) {
220 // parameters are unknown, because that needs parsing of wikitext
221 $retval[str_replace( ' ', '_', $m[1] )] = 'unknown';
224 if ( !isset( $data['continue'] ) ) {
227 $params = array_replace( $params, $data['continue'] );
232 * Get hooks from a PHP file
233 * @param string $filePath Full file path to the PHP file.
234 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
236 private function getHooksFromFile( $filePath ) {
237 $content = file_get_contents( $filePath );
240 // All functions which runs hooks
241 '/(?:wfRunHooks|Hooks\:\:run|ContentHandler\:\:runLegacyHooks)\s*\(\s*' .
242 // First argument is the hook name as string
244 // Comma for second argument
246 // Second argument must start with array to be processed
248 // Matching inside array - allows one deep of brackets
249 '((?:[^\(\)]|\([^\(\)]*\))*)' .
259 foreach ( $m as $match ) {
261 if ( isset( $match[4] ) ) {
263 if ( preg_match_all( '/((?:[^,\(\)]|\([^\(\)]*\))+)/', $match[4], $n ) ) {
264 $args = array_map( 'trim', $n[1] );
266 } elseif ( isset( $match[3] ) ) {
267 // Found a parameter for Hooks::run,
268 // but could not extract the hooks argument,
269 // because there are given by a variable
272 $hooks[$match[2]] = $args;
279 * Get bad hooks (where the hook name could not be determined) from a PHP file
280 * @param string $filePath Full filename to the PHP file.
281 * @return array Array of bad wfRunHooks() lines
283 private function getBadHooksFromFile( $filePath ) {
284 $content = file_get_contents( $filePath );
286 // We want to skip the "function wfRunHooks()" one. :)
287 preg_match_all( '/(?<!function )wfRunHooks\(\s*[^\s\'"].*/', $content, $m );
289 foreach ( $m[0] as $match ) {
290 $list[] = $match . "(" . $filePath . ")";
297 * Get hooks from a directory of PHP files.
298 * @param string $dir Directory path to start at
299 * @param int $recursive Pass self::FIND_RECURSIVE
300 * @return array Array: key => hook name; value => array of arguments or string 'unknown'
302 private function getHooksFromDir( $dir, $recurse = 0 ) {
306 if ( $recurse === self
::FIND_RECURSIVE
) {
307 $iterator = new RecursiveIteratorIterator(
308 new RecursiveDirectoryIterator( $dir ),
309 RecursiveIteratorIterator
::SELF_FIRST | RecursiveDirectoryIterator
::SKIP_DOTS
312 $iterator = new DirectoryIterator( $dir );
315 foreach ( $iterator as $info ) {
316 // Ignore directories, ignore json (installer and api i18n),
317 // ignore extension-less files like HISTORY
318 if ( $info->isFile() && $info->getExtension() !== 'json' && $info->getExtension()
319 // Skip this file as it contains text that looks like a bad wfRunHooks() call
320 && $info->getRealPath() !== __FILE__
322 $good = array_merge( $good, $this->getHooksFromFile( $info->getRealPath() ) );
323 $bad = array_merge( $bad, $this->getBadHooksFromFile( $info->getRealPath() ) );
327 return [ 'good' => $good, 'bad' => $bad ];
331 * Nicely output the array
332 * @param string $msg A message to show before the value
334 * @param bool $sort Whether to sort the array (Default: true)
336 private function printArray( $msg, $arr, $sort = true ) {
341 foreach ( $arr as $v ) {
342 $this->output( "$msg: $v\n" );
347 $maintClass = 'FindHooks';
348 require_once RUN_MAINTENANCE_IF_MAIN
;