MediaWiki  1.28.0
findHooks.php
Go to the documentation of this file.
1 <?php
37 require_once __DIR__ . '/Maintenance.php';
38 
44 class FindHooks extends Maintenance {
45  const FIND_NON_RECURSIVE = 0;
46  const FIND_RECURSIVE = 1;
47 
48  /*
49  * Hooks that are ignored
50  */
51  protected static $ignore = [ 'testRunLegacyHooks', 'Test' ];
52 
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' );
57  }
58 
59  public function getDbType() {
60  return Maintenance::DB_NONE;
61  }
62 
63  public function execute() {
64  global $IP;
65 
66  $documentedHooks = $this->getHooksFromDoc( $IP . '/docs/hooks.txt' );
67  $potentialHooks = [];
68  $badHooks = [];
69 
70  $recurseDirs = [
71  "$IP/includes/",
72  "$IP/mw-config/",
73  "$IP/languages/",
74  "$IP/maintenance/",
75  // Omit $IP/tests/phpunit as it contains hook tests that shouldn't be documented
76  "$IP/tests/parser",
77  "$IP/tests/phpunit/suites",
78  ];
79  $nonRecurseDirs = [
80  "$IP/",
81  ];
82 
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'] );
87  }
88  foreach ( $nonRecurseDirs as $dir ) {
89  $ret = $this->getHooksFromDir( $dir );
90  $potentialHooks = array_merge( $potentialHooks, $ret['good'] );
91  $badHooks = array_merge( $badHooks, $ret['bad'] );
92  }
93 
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 );
100 
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
106  continue;
107  }
108  $argsDoc = $documentedHooks[$hook];
109  if ( $args === 'unknown' || $argsDoc === 'unknown' ) {
110  // Could not get parameter information
111  continue;
112  }
113  if ( count( $argsDoc ) !== count( $args ) ) {
114  $badParameterCount[] = $hook . ': Doc: ' . count( $argsDoc ) . ' vs. Code: ' . count( $args );
115  } else {
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;
122  }
123  }
124  }
125  }
126 
127  // Print the results
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 );
133 
134  if ( !$todo && !$deprecated && !$badHooks
135  && !$badParameterCount && !$badParameterReference
136  ) {
137  $this->output( "Looks good!\n" );
138  } else {
139  $this->error( 'The script finished with errors.', 1 );
140  }
141  }
142 
148  private function getHooksFromDoc( $doc ) {
149  if ( $this->hasOption( 'online' ) ) {
150  return $this->getHooksFromOnlineDoc();
151  } else {
152  return $this->getHooksFromLocalDoc( $doc );
153  }
154  }
155 
161  private function getHooksFromLocalDoc( $doc ) {
162  $m = [];
163  $content = file_get_contents( $doc );
164  preg_match_all(
165  "/\n'(.*?)':.*((?:\n.+)*)/",
166  $content,
167  $m,
168  PREG_SET_ORDER
169  );
170 
171  // Extract the documented parameter
172  $hooks = [];
173  foreach ( $m as $match ) {
174  $args = [];
175  if ( isset( $match[2] ) ) {
176  $n = [];
177  if ( preg_match_all( "/\n(&?\\$\w+):.+/", $match[2], $n ) ) {
178  $args = $n[1];
179  }
180  }
181  $hooks[$match[1]] = $args;
182  }
183  return $hooks;
184  }
185 
190  private function getHooksFromOnlineDoc() {
191  $allhooks = $this->getHooksFromOnlineDocCategory( 'MediaWiki_hooks' );
192  $removed = $this->getHooksFromOnlineDocCategory( 'Removed_hooks' );
193  return array_diff_key( $allhooks, $removed );
194  }
195 
200  private function getHooksFromOnlineDocCategory( $title ) {
201  $params = [
202  'action' => 'query',
203  'list' => 'categorymembers',
204  'cmtitle' => "Category:$title",
205  'cmlimit' => 500,
206  'format' => 'json',
207  'continue' => '',
208  ];
209 
210  $retval = [];
211  while ( true ) {
212  $json = Http::get(
213  wfAppendQuery( 'http://www.mediawiki.org/w/api.php', $params ),
214  [],
215  __METHOD__
216  );
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';
222  }
223  }
224  if ( !isset( $data['continue'] ) ) {
225  return $retval;
226  }
227  $params = array_replace( $params, $data['continue'] );
228  }
229  }
230 
236  private function getHooksFromFile( $filePath ) {
237  $content = file_get_contents( $filePath );
238  $m = [];
239  preg_match_all(
240  // All functions which runs hooks
241  '/(?:wfRunHooks|Hooks\:\:run|ContentHandler\:\:runLegacyHooks)\s*\(\s*' .
242  // First argument is the hook name as string
243  '([\'"])(.*?)\1' .
244  // Comma for second argument
245  '(?:\s*(,))?' .
246  // Second argument must start with array to be processed
247  '(?:\s*(?:array\s*\(|\[)' .
248  // Matching inside array - allows one deep of brackets
249  '((?:[^\(\)\[\]]|\((?-1)\)|\[(?-1)\])*)' .
250  // End
251  '[\)\]])?/',
252  $content,
253  $m,
254  PREG_SET_ORDER
255  );
256 
257  // Extract parameter
258  $hooks = [];
259  foreach ( $m as $match ) {
260  $args = [];
261  if ( isset( $match[4] ) ) {
262  $n = [];
263  if ( preg_match_all( '/((?:[^,\(\)]|\([^\(\)]*\))+)/', $match[4], $n ) ) {
264  $args = array_map( 'trim', $n[1] );
265  }
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
270  $args = 'unknown';
271  }
272  $hooks[$match[2]] = $args;
273  }
274 
275  return $hooks;
276  }
277 
283  private function getBadHooksFromFile( $filePath ) {
284  $content = file_get_contents( $filePath );
285  $m = [];
286  // We want to skip the "function wfRunHooks()" one. :)
287  preg_match_all( '/(?<!function )wfRunHooks\(\s*[^\s\'"].*/', $content, $m );
288  $list = [];
289  foreach ( $m[0] as $match ) {
290  $list[] = $match . "(" . $filePath . ")";
291  }
292 
293  return $list;
294  }
295 
302  private function getHooksFromDir( $dir, $recurse = 0 ) {
303  $good = [];
304  $bad = [];
305 
306  if ( $recurse === self::FIND_RECURSIVE ) {
307  $iterator = new RecursiveIteratorIterator(
308  new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::SKIP_DOTS ),
309  RecursiveIteratorIterator::SELF_FIRST
310  );
311  } else {
312  $iterator = new DirectoryIterator( $dir );
313  }
314 
315  foreach ( $iterator as $info ) {
316  // Ignore directories, work only on php files,
317  if ( $info->isFile() && in_array( $info->getExtension(), [ 'php', 'inc' ] )
318  // Skip this file as it contains text that looks like a bad wfRunHooks() call
319  && $info->getRealPath() !== __FILE__
320  ) {
321  $good = array_merge( $good, $this->getHooksFromFile( $info->getRealPath() ) );
322  $bad = array_merge( $bad, $this->getBadHooksFromFile( $info->getRealPath() ) );
323  }
324  }
325 
326  return [ 'good' => $good, 'bad' => $bad ];
327  }
328 
334  private function printArray( $msg, $arr ) {
335  asort( $arr );
336 
337  foreach ( $arr as $v ) {
338  $this->output( "$msg: $v\n" );
339  }
340  }
341 }
342 
343 $maintClass = 'FindHooks';
344 require_once RUN_MAINTENANCE_IF_MAIN;
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:57
if(count($args)==0) $dir
$IP
Definition: WebStart.php:58
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1936
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
Maintenance script that compares documented and actually present mismatches.
Definition: findHooks.php:44
const FIND_RECURSIVE
Definition: findHooks.php:46
hasOption($name)
Checks to see if a particular param exists.
getHooksFromOnlineDocCategory($title)
Definition: findHooks.php:200
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
if($line===false) $args
Definition: cdb.php:64
getHooksFromDir($dir, $recurse=0)
Get hooks from a directory of PHP files.
Definition: findHooks.php:302
const FIND_NON_RECURSIVE
Definition: findHooks.php:45
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
wfAppendQuery($url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
$params
__construct()
Definition: findHooks.php:53
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
addDescription($text)
Set the description text.
getHooksFromOnlineDoc()
Get hooks from www.mediawiki.org using the API.
Definition: findHooks.php:190
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
output($out, $channel=null)
Throw some output to the user.
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
static $ignore
Definition: findHooks.php:51
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 $content
Definition: hooks.txt:1046
getHooksFromLocalDoc($doc)
Get hooks from a local file (for example docs/hooks.txt)
Definition: findHooks.php:161
getHooksFromFile($filePath)
Get hooks from a PHP file.
Definition: findHooks.php:236
error($err, $die=0)
Throw an error to the user.
$maintClass
Definition: findHooks.php:343
getBadHooksFromFile($filePath)
Get bad hooks (where the hook name could not be determined) from a PHP file.
Definition: findHooks.php:283
static get($url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
Definition: Http.php:94
printArray($msg, $arr)
Nicely sort an print an array.
Definition: findHooks.php:334
static decode($value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
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
getHooksFromDoc($doc)
Get the hook documentation, either locally or from MediaWiki.org.
Definition: findHooks.php:148
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2491