Debian Codegraph @

extensions/Cite/src/Cite.php

raw symbols SCIP
1 <?php
2
3 /**
4 * A parser extension that adds two tags, <ref> and <references> for adding
5 * citations to pages
6 *
7 * @ingroup Extensions
8 *
9 * Documentation
10 * @link https://www.mediawiki.org/wiki/Extension:Cite/Cite.php
11 *
12 * <cite> definition in HTML
13 * @link http://www.w3.org/TR/html4/struct/text.html#edef-CITE
14 *
15 * <cite> definition in XHTML 2.0
16 * @link http://www.w3.org/TR/2005/WD-xhtml2-20050527/mod-text.html#edef_text_cite
17 *
18 * @bug https://phabricator.wikimedia.org/T6579
19 *
20 * @author Ævar Arnfjörð Bjarmason <[email protected]om>
21 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason
22 * @license GPL-2.0-or-later
23 */
24
25 namespace Cite;
26
27 use LogicException;
28 use MediaWiki\Config\Config;
29 use MediaWiki\Html\Html;
30 use MediaWiki\Parser\Parser;
31 use MediaWiki\Parser\Sanitizer;
32 use StatusValue;
33
34 /**
35 * @license GPL-2.0-or-later
36 */
37 class Cite {
38
39 public const DEFAULT_GROUP = '';
40
41 /** Attribute name for the sub-referencing feature in <ref …> */
42 public const SUBREF_ATTRIBUTE = 'extends';
43
44 /**
45 * Message key for the (localized) tracking category for pages using the `extends` attribute.
46 */
47 public const EXTENDS_TRACKING_CATEGORY = 'cite-tracking-category-ref-extends';
48
49 private bool $isSectionPreview;
50 private FootnoteMarkFormatter $footnoteMarkFormatter;
51 private ReferenceListFormatter $referenceListFormatter;
52 private ErrorReporter $errorReporter;
53
54 /**
55 * True when a <ref> tag is being processed.
56 * Used to avoid infinite recursion
57 */
58 private bool $inRefTag = false;
59
60 /**
61 * @var null|string The current group name while parsing nested <ref> in <references>. Null when
62 * parsing <ref> outside of <references>. Warning, an empty string is a valid group name!
63 */
64 private ?string $inReferencesGroup = null;
65
66 /**
67 * Error stack used when defining refs in <references>
68 */
69 private StatusValue $mReferencesErrors;
70 private ReferenceStack $referenceStack;
71 private Config $config;
72
73 public function __construct( Parser $parser, Config $config ) {
74 $this->isSectionPreview = $parser->getOptions()->getIsSectionPreview();
75 $messageLocalizer = new ReferenceMessageLocalizer( $parser->getContentLanguage() );
76 $this->errorReporter = new ErrorReporter( $messageLocalizer );
77 $this->mReferencesErrors = StatusValue::newGood();
78 $this->referenceStack = new ReferenceStack();
79 $anchorFormatter = new AnchorFormatter();
80 $this->footnoteMarkFormatter = new FootnoteMarkFormatter(
81 $this->errorReporter,
82 $anchorFormatter,
83 $messageLocalizer
84 );
85 $this->referenceListFormatter = new ReferenceListFormatter(
86 $this->errorReporter,
87 $anchorFormatter,
88 $messageLocalizer
89 );
90 $this->config = $config;
91 }
92
93 /**
94 * Callback function for <ref>
95 *
96 * @param Parser $parser
97 * @param ?string $text Raw, untrimmed wikitext content of the <ref> tag, if any
98 * @param string[] $argv Arguments as given in <ref name=…>, already trimmed
99 *
100 * @return string|null Null in case a <ref> tag is not allowed in the current context
101 */
102 public function ref( Parser $parser, ?string $text, array $argv ): ?string {
103 if ( $this->inRefTag ) {
104 return null;
105 }
106
107 $this->inRefTag = true;
108 $ret = $this->guardedRef( $parser, $text, $argv );
109 $this->inRefTag = false;
110
111 return $ret;
112 }
113
114 /**
115 * @param Parser $parser
116 * @param ?string $text Raw, untrimmed wikitext content of the <ref> tag, if any
117 * @param string[] $argv Arguments as given in <ref name=…>, already trimmed
118 *
119 * @return string HTML
120 */
121 private function guardedRef(
122 Parser $parser,
123 ?string $text,
124 array $argv
125 ): string {
126 // Tag every page where sub-referencing has been used, whether or not the ref tag is valid.
127 // TODO: Remove this generic usage tracking once the feature is stable. See T237531.
128 if ( array_key_exists( self::SUBREF_ATTRIBUTE, $argv ) ) {
129 $parser->addTrackingCategory( self::EXTENDS_TRACKING_CATEGORY );
130 }
131
132 $status = $this->parseArguments(
133 $argv,
134 [ 'group', 'name', self::SUBREF_ATTRIBUTE, 'follow', 'dir' ]
135 );
136 $arguments = $status->getValue();
137 // Use the default group, or the references group when inside one.
138 $arguments['group'] ??= $this->inReferencesGroup ?? self::DEFAULT_GROUP;
139
140 $validator = new Validator(
141 $this->referenceStack,
142 $this->inReferencesGroup,
143 $this->isSectionPreview,
144 $this->config->get( 'CiteBookReferencing' )
145 );
146 // @phan-suppress-next-line PhanParamTooFewUnpack No good way to document it.
147 $status->merge( $validator->validateRef( $text, ...array_values( $arguments ) ) );
148
149 // Validation cares about the difference between null and empty, but from here on we don't
150 if ( $text !== null && trim( $text ) === '' ) {
151 $text = null;
152 }
153
154 if ( $this->inReferencesGroup !== null ) {
155 if ( !$status->isGood() ) {
156 // We know we are in the middle of a <references> tag and can't display errors in place
157 $this->mReferencesErrors->merge( $status );
158 } elseif ( $text !== null ) {
159 // Validation made sure we always have group and name while in <references>
160 $this->referenceStack->listDefinedRef( $arguments['group'], $arguments['name'], $text );
161 }
162 return '';
163 }
164
165 if ( !$status->isGood() ) {
166 $this->referenceStack->pushInvalidRef();
167
168 // FIXME: If we ever have multiple errors, these must all be presented to the user,
169 // so they know what to correct.
170 // TODO: Make this nicer, see T238061
171 return $this->errorReporter->firstError( $parser, $status );
172 }
173
174 // @phan-suppress-next-line PhanParamTooFewUnpack No good way to document it.
175 $ref = $this->referenceStack->pushRef(
176 $parser->getStripState(), $text, $argv, ...array_values( $arguments ) );
177 if ( !$ref ) {
178 // Rare edge-cases like follow="…" don't render a footnote marker in-place
179 return '';
180 }
181
182 return $this->footnoteMarkFormatter->linkRef( $parser, $ref );
183 }
184
185 /**
186 * @param string[] $argv The argument vector
187 * @param string[] $allowedAttributes Allowed attribute names
188 *
189 * @return StatusValue Either an error, or has a value with the dictionary of field names and
190 * parsed or default values. Missing attributes will be `null`.
191 */
192 private function parseArguments( array $argv, array $allowedAttributes ): StatusValue {
193 $expected = count( $allowedAttributes );
194 $allValues = array_merge( array_fill_keys( $allowedAttributes, null ), $argv );
195 if ( isset( $allValues['dir'] ) ) {
196 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
197 $allValues['dir'] = strtolower( $allValues['dir'] );
198 }
199
200 $status = StatusValue::newGood( array_slice( $allValues, 0, $expected ) );
201
202 if ( count( $allValues ) > $expected ) {
203 // A <ref> must have a name (can be null), but <references> can't have one
204 $status->fatal( in_array( 'name', $allowedAttributes, true )
205 ? 'cite_error_ref_too_many_keys'
206 : 'cite_error_references_invalid_parameters'
207 );
208 }
209
210 return $status;
211 }
212
213 /**
214 * Callback function for <references>
215 *
216 * @param Parser $parser
217 * @param ?string $text Raw, untrimmed wikitext content of the <references> tag, if any
218 * @param string[] $argv Arguments as given in <references …>, already trimmed
219 *
220 * @return string|null Null in case a <references> tag is not allowed in the current context
221 */
222 public function references( Parser $parser, ?string $text, array $argv ): ?string {
223 if ( $this->inRefTag || $this->inReferencesGroup !== null ) {
224 return null;
225 }
226
227 $status = $this->parseArguments( $argv, [ 'group', 'responsive' ] );
228 $arguments = $status->getValue();
229
230 $this->inReferencesGroup = $arguments['group'] ?? self::DEFAULT_GROUP;
231
232 $status->merge( $this->parseReferencesTagContent( $parser, $text ) );
233 if ( !$status->isGood() ) {
234 $ret = $this->errorReporter->firstError( $parser, $status );
235 } else {
236 $responsive = $arguments['responsive'];
237 $ret = $this->formatReferences( $parser, $this->inReferencesGroup, $responsive );
238 // Append errors collected while {@see parseReferencesTagContent} processed <ref> tags
239 // in <references>
240 $ret .= $this->formatReferencesErrors( $parser );
241 }
242
243 $this->inReferencesGroup = null;
244
245 return $ret;
246 }
247
248 /**
249 * @param Parser $parser
250 * @param ?string $text Raw, untrimmed wikitext content of the <references> tag, if any
251 *
252 * @return StatusValue
253 */
254 private function parseReferencesTagContent( Parser $parser, ?string $text ): StatusValue {
255 // Nothing to parse in an empty <references /> tag
256 if ( $text === null || trim( $text ) === '' ) {
257 return StatusValue::newGood();
258 }
259
260 if ( preg_match( '{' . preg_quote( Parser::MARKER_PREFIX ) . '-(?i:references)-}', $text ) ) {
261 return StatusValue::newFatal( 'cite_error_included_references' );
262 }
263
264 // Detect whether we were sent already rendered <ref>s. Mostly a side effect of using
265 // {{#tag:references}}. The following assumes that the parsed <ref>s sent within the
266 // <references> block were the most recent calls to <ref>. This assumption is true for
267 // all known use cases, but not strictly enforced by the parser. It is possible that
268 // some unusual combination of #tag, <references> and conditional parser functions could
269 // be created that would lead to malformed references here.
270 preg_match_all( '{' . preg_quote( Parser::MARKER_PREFIX ) . '-(?i:ref)-}', $text, $matches );
271 $count = count( $matches[0] );
272
273 // Undo effects of calling <ref> while unaware of being contained in <references>
274 foreach ( $this->referenceStack->rollbackRefs( $count ) as $call ) {
275 // Rerun <ref> call with the <references> context now being known
276 $this->guardedRef( $parser, ...$call );
277 }
278
279 // Parse the <references> content to process any unparsed <ref> tags, but drop the resulting
280 // HTML
281 $parser->recursiveTagParse( $text );
282
283 return StatusValue::newGood();
284 }
285
286 private function formatReferencesErrors( Parser $parser ): string {
287 $html = '';
288 foreach ( $this->mReferencesErrors->getErrors() as $error ) {
289 if ( $html ) {
290 $html .= "<br />\n";
291 }
292 $html .= $this->errorReporter->halfParsed( $parser, $error['message'], ...$error['params'] );
293 }
294 $this->mReferencesErrors = StatusValue::newGood();
295 return $html ? "\n$html" : '';
296 }
297
298 /**
299 * @param Parser $parser
300 * @param string $group
301 * @param string|null $responsive Defaults to $wgCiteResponsiveReferences when not set
302 *
303 * @return string HTML
304 */
305 private function formatReferences(
306 Parser $parser,
307 string $group,
308 ?string $responsive = null
309 ): string {
310 $responsiveReferences = $this->config->get( 'CiteResponsiveReferences' );
311
312 return $this->referenceListFormatter->formatReferences(
313 $parser,
314 $this->referenceStack->popGroup( $group ),
315 $responsive !== null ? $responsive !== '0' : $responsiveReferences,
316 $this->isSectionPreview
317 );
318 }
319
320 /**
321 * Called at the end of page processing to append a default references
322 * section, if refs were used without a main references tag. If there are references
323 * in a custom group, and there is no references tag for it, show an error
324 * message for that group.
325 * If we are processing a section preview, this adds the missing
326 * references tags and does not add the errors.
327 *
328 * @param Parser $parser
329 * @param bool $isSectionPreview
330 *
331 * @return string HTML
332 */
333 public function checkRefsNoReferences( Parser $parser, bool $isSectionPreview ): string {
334 $s = '';
335 foreach ( $this->referenceStack->getGroups() as $group ) {
336 if ( $group === self::DEFAULT_GROUP || $isSectionPreview ) {
337 $s .= $this->formatReferences( $parser, $group );
338 } else {
339 $s .= '<br />' . $this->errorReporter->halfParsed(
340 $parser,
341 'cite_error_group_refs_without_references',
342 Sanitizer::safeEncodeAttribute( $group )
343 );
344 }
345 }
346 if ( $isSectionPreview && $s !== '' ) {
347 $headerMsg = wfMessage( 'cite_section_preview_references' );
348 if ( !$headerMsg->isDisabled() ) {
349 $s = Html::element(
350 'h2',
351 [ 'id' => 'mw-ext-cite-cite_section_preview_references_header' ],
352 $headerMsg->text()
353 ) . $s;
354 }
355 // provide a preview of references in its own section
356 $s = Html::rawElement(
357 'div',
358 [ 'class' => 'mw-ext-cite-cite_section_preview_references' ],
359 $s
360 );
361 }
362 return $s !== '' ? "\n" . $s : '';
363 }
364
365 /**
366 * @see https://phabricator.wikimedia.org/T240248
367 * @return never
368 */
369 public function __clone() {
370 throw new LogicException( 'Create a new instance please' );
371 }
372
373 }