Debian Codegraph @

extensions/Linter/includes/Hooks.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Linter;
22
23 use JobQueueGroup;
24 use MediaWiki\Api\ApiQuerySiteinfo;
25 use MediaWiki\Api\Hook\APIQuerySiteInfoGeneralInfoHook;
26 use MediaWiki\Config\Config;
27 use MediaWiki\Content\Content;
28 use MediaWiki\Context\IContextSource;
29 use MediaWiki\Deferred\DeferrableUpdate;
30 use MediaWiki\Deferred\MWCallableUpdate;
31 use MediaWiki\Hook\InfoActionHook;
32 use MediaWiki\Hook\ParserLogLinterDataHook;
33 use MediaWiki\Linker\LinkRenderer;
34 use MediaWiki\Logger\LoggerFactory;
35 use MediaWiki\Output\Hook\BeforePageDisplayHook;
36 use MediaWiki\Output\OutputPage;
37 use MediaWiki\Page\Hook\RevisionFromEditCompleteHook;
38 use MediaWiki\Page\Hook\WikiPageDeletionUpdatesHook;
39 use MediaWiki\Page\ParserOutputAccess;
40 use MediaWiki\Page\WikiPageFactory;
41 use MediaWiki\Revision\RenderedRevision;
42 use MediaWiki\Revision\RevisionRecord;
43 use MediaWiki\SpecialPage\SpecialPage;
44 use MediaWiki\Storage\Hook\RevisionDataUpdatesHook;
45 use MediaWiki\Title\Title;
46 use MediaWiki\User\UserIdentity;
47 use Skin;
48 use WikiPage;
49
50 class Hooks implements
51 APIQuerySiteInfoGeneralInfoHook,
52 BeforePageDisplayHook,
53 InfoActionHook,
54 ParserLogLinterDataHook,
55 RevisionFromEditCompleteHook,
56 WikiPageDeletionUpdatesHook,
57 RevisionDataUpdatesHook
58 {
59 private LinkRenderer $linkRenderer;
60 private JobQueueGroup $jobQueueGroup;
61 private WikiPageFactory $wikiPageFactory;
62 private ParserOutputAccess $parserOutputAccess;
63 private CategoryManager $categoryManager;
64 private TotalsLookup $totalsLookup;
65 private Database $database;
66 private bool $parseOnDerivedDataUpdates;
67
68 /**
69 * @param LinkRenderer $linkRenderer
70 * @param JobQueueGroup $jobQueueGroup
71 * @param WikiPageFactory $wikiPageFactory
72 * @param ParserOutputAccess $parserOutputAccess
73 * @param CategoryManager $categoryManager
74 * @param TotalsLookup $totalsLookup
75 * @param Database $database
76 */
77 public function __construct(
78 LinkRenderer $linkRenderer,
79 JobQueueGroup $jobQueueGroup,
80 WikiPageFactory $wikiPageFactory,
81 ParserOutputAccess $parserOutputAccess,
82 CategoryManager $categoryManager,
83 TotalsLookup $totalsLookup,
84 Database $database,
85 Config $config
86 ) {
87 $this->linkRenderer = $linkRenderer;
88 $this->jobQueueGroup = $jobQueueGroup;
89 $this->wikiPageFactory = $wikiPageFactory;
90 $this->parserOutputAccess = $parserOutputAccess;
91 $this->categoryManager = $categoryManager;
92 $this->totalsLookup = $totalsLookup;
93 $this->database = $database;
94 $this->parseOnDerivedDataUpdates = $config->get( 'LinterParseOnDerivedDataUpdate' );
95 }
96
97 /**
98 * Hook: BeforePageDisplay
99 *
100 * If there is a lintid parameter, look up that error in the database
101 * and setup and output our client-side helpers
102 *
103 * @param OutputPage $out
104 * @param Skin $skin
105 */
106 public function onBeforePageDisplay( $out, $skin ): void {
107 $request = $out->getRequest();
108 $lintId = $request->getInt( 'lintid' );
109 if ( !$lintId ) {
110 return;
111 }
112 $title = $out->getTitle();
113 if ( !$title ) {
114 return;
115 }
116
117 $lintError = $this->database->getFromId( $lintId );
118 if ( !$lintError ) {
119 // Already fixed or bogus URL parameter?
120 return;
121 }
122
123 $out->addJsConfigVars( [
124 'wgLinterErrorCategory' => $lintError->category,
125 'wgLinterErrorLocation' => $lintError->location,
126 ] );
127 $out->addModules( 'ext.linter.edit' );
128 }
129
130 /**
131 * Hook: WikiPageDeletionUpdates
132 *
133 * Remove entries from the linter table upon page deletion
134 *
135 * @param WikiPage $wikiPage
136 * @param Content $content
137 * @param array &$updates
138 */
139 public function onWikiPageDeletionUpdates( $wikiPage, $content, &$updates ) {
140 // The article id of the title is set to 0 when the page is deleted so
141 // capture it before creating the callback.
142 $id = $wikiPage->getId();
143 $ns = $wikiPage->getNamespace();
144
145 $updates[] = new MWCallableUpdate( function () use ( $id, $ns ) {
146 $this->totalsLookup->updateStats(
147 $this->database->setForPage( $id, $ns, [] )
148 );
149 }, __METHOD__ );
150 }
151
152 /**
153 * This should match Parsoid's PageConfig::hasLintableContentModel()
154 */
155 public const LINTABLE_CONTENT_MODELS = [ CONTENT_MODEL_WIKITEXT, 'proofread-page' ];
156
157 /**
158 * Hook: RevisionFromEditComplete
159 *
160 * Remove entries from the linter table upon page content model change away from wikitext
161 *
162 * @param WikiPage $wikiPage
163 * @param RevisionRecord $newRevisionRecord
164 * @param bool|int $originalRevId
165 * @param UserIdentity $user
166 * @param string[] &$tags
167 */
168 public function onRevisionFromEditComplete(
169 $wikiPage, $newRevisionRecord, $originalRevId, $user, &$tags
170 ) {
171 // This is just a stop-gap to deal with callers that aren't complying
172 // with the advertised hook signature.
173 if ( !is_array( $tags ) ) {
174 return;
175 }
176
177 if (
178 in_array( "mw-blank", $tags ) ||
179 ( in_array( "mw-contentmodelchange", $tags ) &&
180 !in_array( $wikiPage->getContentModel(), self::LINTABLE_CONTENT_MODELS ) )
181 ) {
182 $this->totalsLookup->updateStats(
183 $this->database->setForPage(
184 $wikiPage->getId(), $wikiPage->getNamespace(), []
185 )
186 );
187 }
188 }
189
190 /**
191 * Hook: APIQuerySiteInfoGeneralInfo
192 *
193 * Expose categories via action=query&meta=siteinfo
194 *
195 * @param ApiQuerySiteInfo $api
196 * @param array &$data
197 */
198 public function onAPIQuerySiteInfoGeneralInfo( $api, &$data ) {
199 $data['linter'] = [
200 'high' => $this->categoryManager->getHighPriority(),
201 'medium' => $this->categoryManager->getMediumPriority(),
202 'low' => $this->categoryManager->getLowPriority(),
203 ];
204 }
205
206 /**
207 * Hook: InfoAction
208 *
209 * Display quick summary of errors for this page on ?action=info
210 *
211 * @param IContextSource $context
212 * @param array &$pageInfo
213 */
214 public function onInfoAction( $context, &$pageInfo ) {
215 $title = $context->getTitle();
216 $pageId = $title->getArticleID();
217 if ( !$pageId ) {
218 return;
219 }
220 $totals = array_filter( $this->database->getTotalsForPage( $pageId ) );
221 if ( !$totals ) {
222 // No errors, yay!
223 return;
224 }
225
226 foreach ( $totals as $name => $count ) {
227 $pageInfo['linter'][] = [
228 $context->msg( "linter-category-$name" ),
229 htmlspecialchars( (string)$count )
230 ];
231 }
232
233 $pageInfo['linter'][] = [
234 'below',
235 $this->linkRenderer->makeKnownLink(
236 SpecialPage::getTitleFor( 'LintErrors' ),
237 $context->msg( 'pageinfo-linter-moreinfo' )->text(),
238 [],
239 [ 'wpNamespaceRestrictions' => $title->getNamespace(),
240 'titlesearch' => $title->getText(), 'exactmatch' => 1 ]
241 ),
242 ];
243 }
244
245 /**
246 * Hook: ParserLogLinterData
247 *
248 * To record a lint errors.
249 *
250 * @param string $page
251 * @param int $revision
252 * @param array[] $data
253 * @return bool
254 */
255 public function onParserLogLinterData(
256 string $page, int $revision, array $data
257 ): bool {
258 $errors = [];
259 $title = Title::newFromText( $page );
260
261 if (
262 !$title || !$title->getArticleID() ||
263 $title->getLatestRevID() != $revision
264 ) {
265 return false;
266 }
267 $catCounts = [];
268 foreach ( $data as $info ) {
269 if ( $this->categoryManager->isKnownCategory( $info['type'] ) ) {
270 // NOTE: Redundant with RecordLintJob, but why even create the job
271 if ( !$this->categoryManager->isEnabled( $info['type'] ) ) {
272 // Drop lints of these types for now
273 continue;
274 }
275 $info[ 'dbid' ] = null;
276 } elseif ( !isset( $info[ 'dbid' ] ) ) {
277 continue;
278 }
279 $count = $catCounts[$info['type']] ?? 0;
280 if ( $count > Database::MAX_PER_CAT ) {
281 // Drop
282 continue;
283 }
284 $catCounts[$info['type']] = $count + 1;
285 if ( !isset( $info['dsr'] ) ) {
286 LoggerFactory::getInstance( 'Linter' )->warning(
287 'dsr for {page} @ rev {revid}, for lint: {lint} is missing',
288 [
289 'page' => $page,
290 'revid' => $revision,
291 'lint' => $info['type'],
292 ]
293 );
294 continue;
295 }
296 $info['location'] = array_slice( $info['dsr'], 0, 2 );
297 if ( !isset( $info['params'] ) ) {
298 $info['params'] = [];
299 }
300 if ( isset( $info['templateInfo'] ) && $info['templateInfo'] ) {
301 $info['params']['templateInfo'] = $info['templateInfo'];
302 }
303 $errors[] = $info;
304 }
305
306 LoggerFactory::getInstance( 'Linter' )->debug(
307 '{method}: Recording {numErrors} errors for {page}',
308 [
309 'method' => __METHOD__,
310 'numErrors' => count( $errors ),
311 'page' => $page
312 ]
313 );
314
315 $job = new RecordLintJob(
316 $title,
317 [ 'errors' => $errors, 'revision' => $revision ],
318 $this->totalsLookup,
319 $this->database,
320 $this->categoryManager
321 );
322
323 $this->jobQueueGroup->lazyPush( $job );
324
325 return true;
326 }
327
328 /**
329 * @param Title $title
330 * @param RenderedRevision $renderedRevision
331 * @param DeferrableUpdate[] &$updates
332 */
333 public function onRevisionDataUpdates( $title, $renderedRevision, &$updates ) {
334 if ( !$this->parseOnDerivedDataUpdates ) {
335 return;
336 }
337
338 if ( $renderedRevision->getOptions()->getUseParsoid() ) {
339 // Parsoid was already used for the canonical parse, nothing to do:
340 // onParserLogLinterData was already called.
341 // This will be the case when parsoid page views are enabled.
342 // Eventually, ParserLogLinterData will probably go away and we'll
343 // have the lint data in the ParserOutput. We'll then just use
344 // that data to create a RecordLintJob.
345 return;
346 }
347
348 if ( !in_array( $title->getContentModel(), self::LINTABLE_CONTENT_MODELS ) ) {
349 return;
350 }
351
352 $updates[] = new LintUpdate(
353 $this->wikiPageFactory,
354 $this->parserOutputAccess,
355 $renderedRevision,
356 );
357 }
358 }