Debian Codegraph @

extensions/Linter/includes/SpecialLintErrors.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 MediaWiki\Cache\LinkCache;
24 use MediaWiki\Html\Html;
25 use MediaWiki\HTMLForm\HTMLForm;
26 use MediaWiki\Output\OutputPage;
27 use MediaWiki\Permissions\PermissionManager;
28 use MediaWiki\Request\WebRequest;
29 use MediaWiki\SpecialPage\SpecialPage;
30 use MediaWiki\Title\MalformedTitleException;
31 use MediaWiki\Title\NamespaceInfo;
32 use MediaWiki\Title\TitleParser;
33
34 class SpecialLintErrors extends SpecialPage {
35
36 private NamespaceInfo $namespaceInfo;
37 private TitleParser $titleParser;
38 private LinkCache $linkCache;
39 private PermissionManager $permissionManager;
40 private CategoryManager $categoryManager;
41 private TotalsLookup $totalsLookup;
42
43 /**
44 * @var string|null
45 */
46 private $category;
47
48 /**
49 * @param NamespaceInfo $namespaceInfo
50 * @param TitleParser $titleParser
51 * @param LinkCache $linkCache
52 * @param PermissionManager $permissionManager
53 * @param CategoryManager $categoryManager
54 * @param TotalsLookup $totalsLookup
55 */
56 public function __construct(
57 NamespaceInfo $namespaceInfo,
58 TitleParser $titleParser,
59 LinkCache $linkCache,
60 PermissionManager $permissionManager,
61 CategoryManager $categoryManager,
62 TotalsLookup $totalsLookup
63 ) {
64 parent::__construct( 'LintErrors' );
65 $this->namespaceInfo = $namespaceInfo;
66 $this->titleParser = $titleParser;
67 $this->linkCache = $linkCache;
68 $this->permissionManager = $permissionManager;
69 $this->categoryManager = $categoryManager;
70 $this->totalsLookup = $totalsLookup;
71 }
72
73 /**
74 * @param string $titleLabel
75 */
76 protected function showFilterForm( $titleLabel ) {
77 $selectOptions = [
78 (string)$this->msg( 'linter-form-exact-match' )->escaped() => true,
79 (string)$this->msg( 'linter-form-prefix-match' )->escaped() => false,
80 ];
81 $namespaces = $this->getContext()->getRequest()->getVal( "wpNamespaceRestrictions" );
82 $fields = [
83 'NamespaceRestrictions' => [
84 'type' => 'namespacesmultiselect',
85 'label' => $this->msg( 'linter-form-namespace' )->text(),
86 'exists' => true,
87 'cssclass' => 'mw-block-partial-restriction',
88 'default' => $namespaces,
89 'input' => [ 'autocomplete' => false ]
90 ],
91 'titlefield' => [
92 'type' => 'title',
93 'name' => $titleLabel,
94 'label-message' => 'linter-form-title-prefix',
95 'exists' => true,
96 'required' => false
97 ],
98 'exactmatchradio' => [
99 'type' => 'radio',
100 'name' => 'exactmatch',
101 'options' => $selectOptions,
102 'label-message' => 'linter-form-exact-or-prefix',
103 'default' => true
104 ]
105 ];
106
107 $selectTemplateOptions = [
108 (string)$this->msg( 'linter-form-template-option-all' )->escaped() => 'all',
109 (string)$this->msg( 'linter-form-template-option-with' )->escaped() => 'with',
110 (string)$this->msg( 'linter-form-template-option-without' )->escaped() => 'without',
111 ];
112 $htmlTags = new HtmlTags( $this );
113 $tagAndTemplateFields = [
114 'tag' => [
115 'type' => 'select',
116 'name' => 'tag',
117 'label-message' => 'linter-form-tag',
118 'options' => $htmlTags->getAllowedHTMLTags()
119 ],
120 'template' => [
121 'type' => 'select',
122 'name' => 'template',
123 'label-message' => 'linter-form-template',
124 'options' => $selectTemplateOptions
125 ]
126 ];
127 $fields = array_merge( $fields, $tagAndTemplateFields );
128
129 $form = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
130 $form->setWrapperLegend( true );
131 if ( $this->category !== null ) {
132 $form->addHeaderHtml( $this->msg( "linter-category-{$this->category}-desc" )->parse() );
133 }
134 $form->setMethod( 'get' );
135 $form->prepareForm()->displayForm( false );
136 }
137
138 /**
139 * cleanTitle parses a title and handles a malformed titles, namespaces that are mismatched
140 * and exact title searches that find no matching records, and produce appropriate error messages
141 *
142 * @param string $title
143 * @param array $namespaces
144 * @return array
145 */
146 public function cleanTitle( string $title, $namespaces ): array {
147 // Check all titles for malformation regardless of exact match or prefix match
148 try {
149 $titleElements = $this->titleParser->parseTitle( $title );
150 } catch ( MalformedTitleException $e ) {
151 return [ 'titlefield' => null, 'error' => 'linter-invalid-title' ];
152 }
153
154 // The drop-down namespace defaults to 'all' which is returned as a null, indicating match all namespaces.
155 // If 'main' is selected in the drop-down, int 0 is returned. Other namespaces are returned as int values > 0.
156 //
157 // If the user does not specify a namespace in the title text box, parseTitle sets it to int 0 as the default.
158 // If the user entered ':' (main) namespace as the namespace prefix of a title such as ":MyPageTitle",
159 // parseTitle will also return int 0 as the namespace. Other valid system namespaces entered as prefixes
160 // in the title text box are returned by parseTitle as int values > 0.
161 // To determine if the user entered the ':' (main) namespace when int 0 is returned, a separate check for
162 // the substring ':' at offset 0 must be performed.
163
164 $titleNamespace = $titleElements->getNamespace();
165 // Determine if the user entered ':' (resolves to main) as the namespace part of the title,
166 // or was it was set by default by parseTitle() to 0, but the user intended to search across 'all' namespaces.
167 if ( $titleNamespace === 0 && $title[0] !== ':' ) {
168 $titleNamespace = null;
169 }
170
171 if ( $namespaces && $titleNamespace !== null && !in_array( $titleNamespace, $namespaces ) ) {
172 // Show the namespace mismatch error if the namespaces specified in drop-down and title text do not match.
173 return [ 'titlefield' => null, 'error' => 'linter-namespace-mismatch' ];
174 }
175
176 // If no namespaces are selected (null), return the namespace from the title text
177 $namespaces = $namespaces ?: [ $titleNamespace ];
178
179 return [ 'titlefield' => $titleElements->getDBkey(), 'namespace' => $namespaces ];
180 }
181
182 /**
183 * @param OutputPage $out
184 * @param string|null $message
185 */
186 private function displayError( $out, $message ) {
187 $out->addHTML(
188 Html::element( 'span', [ 'class' => 'error' ],
189 $this->msg( $message )->text() )
190 );
191 }
192
193 /**
194 * Extract namespace settings from the request object,
195 * returning an array of namespace id numbers
196 *
197 * @param WebRequest $request
198 * @return array
199 */
200 protected function findNamespaces( $request ) {
201 $namespaceRequestValues = $request->getRawVal( 'wpNamespaceRestrictions' ) ?? '';
202 if ( $namespaceRequestValues === '' ) {
203 return [];
204 }
205
206 // Security measure: only allow active namespace IDs to reach the query
207 return array_values(
208 array_intersect(
209 // Remove -2 = "media" and -1 = "Special" namespace elements
210 array_filter(
211 array_keys(
212 $this->namespaceInfo->getCanonicalNamespaces()
213 ),
214 static function ( $x ) {
215 return $x >= 0;
216 }
217 ),
218 array_map( 'intval', explode( "\n", $namespaceRequestValues ) )
219 )
220 );
221 }
222
223 /**
224 * @param string|null $subPage
225 */
226 public function execute( $subPage ) {
227 $request = $this->getRequest();
228 $out = $this->getOutput();
229
230 $params = $request->getQueryValues();
231
232 $this->setHeaders();
233 $this->outputHeader( $subPage || isset( $params[ 'titlesearch' ] ) ? 'disable-summary' : '' );
234
235 $namespaces = $this->findNamespaces( $request );
236
237 $exactMatch = $request->getBool( 'exactmatch', true );
238 $tagName = $this->getRequest()->getText( 'tag' );
239 // map command line tag name through an associative array to protect request from an SQL injection security risk
240 $htmlTags = new HtmlTags( $this );
241 $allowedHtmlTags = $htmlTags->getAllowedHTMLTags();
242 $tag = $allowedHtmlTags[ $tagName ] ?? 'all';
243 $template = $this->getRequest()->getText( 'template' );
244
245 // If the request contains a 'titlesearch' parameter, then the user entered a page title
246 // or just the first few characters of the title. They also may have entered the first few characters
247 // of a custom namespace (just the text before a ':') to search for and pressed the associated Submit button.
248 // Added the pageback parameter to inform the code that the '<- Special:LintErrors' link had been used to allow
249 // the UI to redisplay with previous form values, instead of just resubmitting the query.
250 if ( $subPage === null && isset( $params[ 'titlesearch' ] ) && !isset( $params[ 'pageback'] ) ) {
251 unset( $params[ 'title' ] );
252 $params = array_merge( [ 'pageback' => true ], $params );
253 $out->addBacklinkSubtitle( $this->getPageTitle(), $params );
254
255 $title = $request->getText( 'titlesearch' );
256 $titleSearch = $this->cleanTitle( $title, $namespaces );
257
258 if ( $titleSearch[ 'titlefield' ] !== null ) {
259 $out->setPageTitleMsg( $this->msg( 'linter-prefix-search-subpage', $titleSearch[ 'titlefield' ] ) );
260
261 $pager = new LintErrorsPager(
262 $this->getContext(),
263 $this->categoryManager,
264 $this->linkCache,
265 $this->getLinkRenderer(),
266 $this->permissionManager,
267 null,
268 $namespaces,
269 $exactMatch, $titleSearch[ 'titlefield' ], $template, $tag
270 );
271 $out->addParserOutput( $pager->getFullOutput() );
272 } else {
273 $this->displayError( $out, $titleSearch[ 'error' ] );
274 }
275 return;
276 }
277
278 if ( in_array( $subPage, array_merge(
279 $this->categoryManager->getVisibleCategories(),
280 $this->categoryManager->getInvisibleCategories()
281 ) ) ) {
282 $this->category = $subPage;
283 }
284
285 if ( !$this->category ) {
286 $this->addHelpLink( 'Help:Extension:Linter' );
287 $this->showCategoryListings();
288 } else {
289 $this->addHelpLink( "Help:Lint_errors/{$this->category}" );
290 $out->setPageTitleMsg(
291 $this->msg( 'linterrors-subpage',
292 $this->msg( "linter-category-{$this->category}" )->text()
293 )
294 );
295 $out->addBacklinkSubtitle( $this->getPageTitle() );
296
297 $title = $request->getText( 'titlecategorysearch' );
298 // For category-based searches, allow an undefined title to display all records
299 if ( $title === '' ) {
300 $titleCategorySearch = [ 'titlefield' => '', 'namespace' => $namespaces, 'pageid' => null ];
301 } else {
302 $titleCategorySearch = $this->cleanTitle( $title, $namespaces );
303 }
304
305 if ( $titleCategorySearch[ 'titlefield' ] !== null ) {
306 $this->showFilterForm( 'titlecategorysearch' );
307 $pager = new LintErrorsPager(
308 $this->getContext(),
309 $this->categoryManager,
310 $this->linkCache,
311 $this->getLinkRenderer(),
312 $this->permissionManager,
313 $this->category,
314 $namespaces,
315 $exactMatch, $titleCategorySearch[ 'titlefield' ], $template, $tag
316 );
317 $out->addParserOutput( $pager->getFullOutput() );
318 } else {
319 $this->displayError( $out, $titleCategorySearch[ 'error' ] );
320 }
321 }
322 }
323
324 /**
325 * @param string $priority
326 * @param int[] $totals name => count
327 * @param string[] $categories
328 */
329 private function displayList( $priority, $totals, array $categories ) {
330 $out = $this->getOutput();
331 $msgName = 'linter-heading-' . $priority . '-priority';
332 $out->addHTML( Html::element( 'h2', [], $this->msg( $msgName )->text() ) );
333 $out->addHTML( $this->buildCategoryList( $categories, $totals ) );
334 }
335
336 /**
337 */
338 private function displaySearchPage() {
339 $out = $this->getOutput();
340 $out->addHTML( Html::element( 'h2', [],
341 $this->msg( "linter-lints-prefix-search-page-desc" )->text() ) );
342 $this->showFilterForm( 'titlesearch' );
343 }
344
345 private function showCategoryListings() {
346 $totals = $this->totalsLookup->getTotals();
347
348 // Display lint issues by priority
349 $this->displayList( 'high', $totals, $this->categoryManager->getHighPriority() );
350 $this->displayList( 'medium', $totals, $this->categoryManager->getMediumPriority() );
351 $this->displayList( 'low', $totals, $this->categoryManager->getLowPriority() );
352
353 $this->displaySearchPage();
354 }
355
356 /**
357 * @param string[] $cats
358 * @param int[] $totals name => count
359 * @return string
360 */
361 private function buildCategoryList( array $cats, array $totals ) {
362 $linkRenderer = $this->getLinkRenderer();
363 $html = Html::openElement( 'ul' ) . "\n";
364 foreach ( $cats as $cat ) {
365 $html .= Html::rawElement( 'li', [], $linkRenderer->makeKnownLink(
366 $this->getPageTitle( $cat ),
367 $this->msg( "linter-category-$cat" )->text()
368 ) . ' ' . Html::element( 'bdi', [],
369 $this->msg( "linter-numerrors" )->numParams( $totals[$cat] )->text()
370 ) ) . "\n";
371 }
372 $html .= Html::closeElement( 'ul' );
373
374 return $html;
375 }
376
377 /** @inheritDoc */
378 public function getGroupName() {
379 return 'maintenance';
380 }
381
382 /**
383 * @return string[]
384 */
385 protected function getSubpagesForPrefixSearch() {
386 return $this->categoryManager->getVisibleCategories();
387 }
388
389 }