Debian Codegraph @

includes/preferences/SignatureValidator.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\Preferences;
22
23 use MediaWiki\Config\ServiceOptions;
24 use MediaWiki\Html\Html;
25 use MediaWiki\MainConfigNames;
26 use MediaWiki\Parser\ParserFactory;
27 use MediaWiki\Parser\ParserOptions;
28 use MediaWiki\Parser\ParserOutputFlags;
29 use MediaWiki\Parser\Parsoid\LintErrorChecker;
30 use MediaWiki\SpecialPage\SpecialPage;
31 use MediaWiki\SpecialPage\SpecialPageFactory;
32 use MediaWiki\Title\TitleFactory;
33 use MediaWiki\User\UserIdentity;
34 use MessageLocalizer;
35 use OOUI\ButtonWidget;
36
37 /**
38 * @since 1.35
39 */
40 class SignatureValidator {
41
42 /** @var array Made public for use in services */
43 public const CONSTRUCTOR_OPTIONS = [
44 MainConfigNames::SignatureAllowedLintErrors,
45 MainConfigNames::VirtualRestConfig,
46 ];
47
48 /** @var UserIdentity */
49 private $user;
50 /** @var MessageLocalizer|null */
51 private $localizer;
52 /** @var ParserOptions */
53 private $popts;
54 /** @var ParserFactory */
55 private $parserFactory;
56 private LintErrorChecker $lintErrorChecker;
57 /** @var ServiceOptions */
58 private $serviceOptions;
59 /** @var SpecialPageFactory */
60 private $specialPageFactory;
61 /** @var TitleFactory */
62 private $titleFactory;
63
64 /**
65 * @param ServiceOptions $options
66 * @param UserIdentity $user
67 * @param ?MessageLocalizer $localizer
68 * @param ParserOptions $popts
69 * @param ParserFactory $parserFactory
70 * @param LintErrorChecker $lintErrorChecker
71 * @param SpecialPageFactory $specialPageFactory
72 * @param TitleFactory $titleFactory
73 */
74 public function __construct(
75 ServiceOptions $options,
76 UserIdentity $user,
77 ?MessageLocalizer $localizer,
78 ParserOptions $popts,
79 ParserFactory $parserFactory,
80 LintErrorChecker $lintErrorChecker,
81 SpecialPageFactory $specialPageFactory,
82 TitleFactory $titleFactory
83 ) {
84 $this->user = $user;
85 $this->localizer = $localizer;
86 $this->popts = $popts;
87 $this->parserFactory = $parserFactory;
88 $this->lintErrorChecker = $lintErrorChecker;
89 // Configuration
90 $this->serviceOptions = $options;
91 $this->serviceOptions->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
92 // TODO SpecialPage::getTitleFor should also be available via SpecialPageFactory
93 $this->specialPageFactory = $specialPageFactory;
94 $this->titleFactory = $titleFactory;
95 }
96
97 /**
98 * @param string $signature Signature before PST
99 * @return string[]|bool If localizer is defined: List of errors, as HTML (empty array for no errors)
100 * If localizer is not defined: True if there are errors, false if there are no errors
101 */
102 public function validateSignature( string $signature ) {
103 $pstSignature = $this->applyPreSaveTransform( $signature );
104 if ( $pstSignature === false ) {
105 // Return early because the rest of the validation uses wikitext parsing, which requires
106 // the pre-save transform to be applied first, and we just found out that the result of the
107 // pre-save transform would require *another* pre-save transform, which is crazy
108 if ( $this->localizer ) {
109 return [ $this->localizer->msg( 'badsigsubst' )->parse() ];
110 }
111 return true;
112 }
113
114 $pstWasApplied = false;
115 if ( $pstSignature !== $signature ) {
116 $pstWasApplied = true;
117 $signature = $pstSignature;
118 }
119
120 $errors = $this->localizer ? [] : false;
121
122 $lintErrors = $this->checkLintErrors( $signature );
123 if ( $lintErrors ) {
124 $messages = '';
125
126 foreach ( $lintErrors as $error ) {
127 if ( !$this->localizer ) {
128 $errors = true;
129 break;
130 }
131
132 $details = $this->getLintErrorDetails( $error );
133 $location = $this->getLintErrorLocation( $error );
134 // THESE MESSAGE IDS SHOULD BE KEPT IN SYNC WITH
135 // those declared in Extension:Linter -- in particular
136 // there should be a linterror-<cat> declared here for every
137 // linter-pager-<cat>-details declared in Linter's qqq.json.
138 // T360809: this redundancy should be eventually eliminated
139
140 // Messages used here:
141 // * linterror-bogus-image-options
142 // * linterror-deletable-table-tag
143 // * linterror-fostered
144 // * linterror-html5-misnesting
145 // * linterror-inline-media-caption
146 // * linterror-large-tables
147 // * linterror-misc-tidy-replacement-issues
148 // * linterror-misnested-tag
149 // * linterror-missing-end-tag
150 // * linterror-missing-end-tag-in-heading
151 // * linterror-missing-image-alt-text
152 // * linterror-multi-colon-escape
153 // * linterror-multiline-html-table-in-list
154 // * linterror-multiple-unclosed-formatting-tags
155 // * linterror-night-mode-unaware-background-color
156 // * linterror-obsolete-tag
157 // * linterror-pwrap-bug-workaround
158 // * linterror-self-closed-tag
159 // * linterror-stripped-tag
160 // * linterror-tidy-font-bug
161 // * linterror-tidy-whitespace-bug
162 // * linterror-unclosed-quotes-in-heading
163 // * linterror-wikilink-in-extlink
164 $label = $this->localizer->msg( "linterror-{$error['type']}" )->parse();
165 $docsLink = new ButtonWidget( [
166 'href' =>
167 "https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Lint_errors/{$error['type']}",
168 'target' => '_blank',
169 'label' => $this->localizer->msg( 'prefs-signature-error-details' )->text(),
170 ] );
171
172 // If pre-save transform was applied (i.e., the signature has 'subst:' syntax),
173 // error locations will be incorrect, because Parsoid can't expand templates.
174 // Don't display them.
175 $encLocation = $pstWasApplied ? null : json_encode( $location );
176
177 $messages .= Html::rawElement(
178 'li',
179 [ 'data-mw-lint-error-location' => $encLocation ],
180 $label . $this->localizer->msg( 'colon-separator' )->escaped() .
181 $details . ' ' . $docsLink
182 );
183 }
184
185 if ( $messages && $this->localizer ) {
186 $errors[] = $this->localizer->msg( 'badsightml' )->parse() .
187 Html::rawElement( 'ol', [], $messages );
188 }
189 }
190
191 if ( !$this->checkUserLinks( $signature ) ) {
192 if ( $this->localizer ) {
193 $userText = wfEscapeWikiText( $this->user->getName() );
194 $linkWikitext = $this->localizer->msg( 'signature', $userText, $userText )->inContentLanguage()->text();
195 $errors[] = $this->localizer->msg( 'badsiglinks', wfEscapeWikiText( $linkWikitext ) )->parse();
196 } else {
197 $errors = true;
198 }
199 }
200
201 if ( !$this->checkLineBreaks( $signature ) ) {
202 if ( $this->localizer ) {
203 $errors[] = $this->localizer->msg( 'badsiglinebreak' )->parse();
204 } else {
205 $errors = true;
206 }
207 }
208
209 return $errors;
210 }
211
212 /**
213 * @param string $signature Signature before PST
214 * @return string|false Signature with PST applied, or false if applying PST yields wikitext that
215 * would change if PST was applied again
216 */
217 protected function applyPreSaveTransform( string $signature ) {
218 // This may be called by the Parser when it's displaying a signature, so we need a new instance
219 $parser = $this->parserFactory->getInstance();
220
221 $pstSignature = $parser->preSaveTransform(
222 $signature,
223 SpecialPage::getTitleFor( 'Preferences' ),
224 $this->user,
225 $this->popts
226 );
227
228 // The signature wikitext contains another '~~~~' or similar (T230652)
229 if ( $parser->getOutput()->getOutputFlag( ParserOutputFlags::USER_SIGNATURE ) ) {
230 return false;
231 }
232
233 // The signature wikitext contains '{{subst:...}}' markup that produces another subst (T230652)
234 $pstPstSignature = $parser->preSaveTransform(
235 $pstSignature,
236 SpecialPage::getTitleFor( 'Preferences' ),
237 $this->user,
238 $this->popts
239 );
240 if ( $pstPstSignature !== $pstSignature ) {
241 return false;
242 }
243
244 return $pstSignature;
245 }
246
247 /**
248 * @param string $signature Signature after PST
249 * @return array Array of error objects returned by Parsoid's lint API (empty array for no errors)
250 */
251 protected function checkLintErrors( string $signature ): array {
252 // Real check for mismatched HTML tags in the *output*.
253 // This has to use Parsoid because PHP Parser doesn't produce this information,
254 // it just fixes up the result quietly.
255
256 $disabled = array_merge(
257 [
258 // Always appears with 'missing-end-tag', we can ignore it to
259 // simplify the error message
260 'multiple-unclosed-formatting-tags',
261 ],
262 $this->serviceOptions->get(
263 MainConfigNames::SignatureAllowedLintErrors
264 )
265 );
266 return $this->lintErrorChecker->checkSome( $signature, $disabled );
267 }
268
269 /**
270 * @param string $signature Signature after PST
271 * @return bool Whether signature contains required links
272 */
273 protected function checkUserLinks( string $signature ): bool {
274 // This may be called by the Parser when it's displaying a signature, so we need a new instance
275 $parser = $this->parserFactory->getInstance();
276
277 // Check for required links. This one's easier to do with the PHP Parser.
278 $pout = $parser->parse(
279 $signature,
280 SpecialPage::getTitleFor( 'Preferences' ),
281 $this->popts
282 );
283
284 // Checking user or talk links is easy
285 $links = $pout->getLinks();
286 $username = $this->user->getName();
287 if (
288 isset( $links[ NS_USER ][ strtr( $username, ' ', '_' ) ] ) ||
289 isset( $links[ NS_USER_TALK ][ strtr( $username, ' ', '_' ) ] )
290 ) {
291 return true;
292 }
293
294 // Checking the contributions link is harder, because the special page name and the username in
295 // the "subpage parameter" are not normalized for us.
296 $splinks = $pout->getLinksSpecial();
297 foreach ( $splinks as $dbkey => $unused ) {
298 [ $name, $subpage ] = $this->specialPageFactory->resolveAlias( $dbkey );
299 if ( $name === 'Contributions' && $subpage ) {
300 $userTitle = $this->titleFactory->makeTitleSafe( NS_USER, $subpage );
301 if ( $userTitle && $userTitle->getText() === $username ) {
302 return true;
303 }
304 }
305 }
306
307 return false;
308 }
309
310 /**
311 * @param string $signature Signature after PST
312 * @return bool Whether signature contains no line breaks
313 */
314 protected function checkLineBreaks( string $signature ): bool {
315 return !preg_match( "/[\r\n]/", $signature );
316 }
317
318 // Adapted from the Linter extension
319 private function getLintErrorLocation( array $lintError ): array {
320 return array_slice( $lintError['dsr'], 0, 2 );
321 }
322
323 // Adapted from the Linter extension
324 private function getLintErrorDetails( array $lintError ): string {
325 [ 'type' => $type, 'params' => $params ] = $lintError;
326
327 if ( $type === 'bogus-image-options' && isset( $params['items'] ) ) {
328 $list = array_map( static function ( $in ) {
329 return Html::element( 'code', [], $in );
330 }, $params['items'] );
331 return implode(
332 $this->localizer->msg( 'comma-separator' )->escaped(),
333 $list
334 );
335 } elseif ( $type === 'pwrap-bug-workaround' &&
336 isset( $params['root'] ) &&
337 isset( $params['child'] ) ) {
338 return Html::element( 'code', [],
339 $params['root'] . " > " . $params['child'] );
340 } elseif ( $type === 'tidy-whitespace-bug' &&
341 isset( $params['node'] ) &&
342 isset( $params['sibling'] ) ) {
343 return Html::element( 'code', [],
344 $params['node'] . " + " . $params['sibling'] );
345 } elseif ( $type === 'multi-colon-escape' &&
346 isset( $params['href'] ) ) {
347 return Html::element( 'code', [], $params['href'] );
348 } elseif ( $type === 'multiline-html-table-in-list' ) {
349 /* ancestor and name will be set */
350 return Html::element( 'code', [],
351 $params['ancestorName'] . " > " . $params['name'] );
352 } elseif ( $type === 'misc-tidy-replacement-issues' ) {
353 /* There will be a 'subtype' param to disambiguate */
354 return Html::element( 'code', [], $params['subtype'] );
355 } elseif ( $type === 'missing-end-tag' ) {
356 return Html::element( 'code', [], '</' . $params['name'] . '>' );
357 } elseif ( isset( $params['name'] ) ) {
358 return Html::element( 'code', [], $params['name'] );
359 }
360
361 return '';
362 }
363
364 }