Debian Codegraph @

extensions/Cite/src/ReferenceListFormatter.php

raw symbols SCIP
1 <?php
2
3 namespace Cite;
4
5 use MediaWiki\Html\Html;
6 use MediaWiki\Parser\Parser;
7
8 /**
9 * Renderer for the actual list of references in place of the <references /> tag at the end of an
10 * article.
11 *
12 * @license GPL-2.0-or-later
13 */
14 class ReferenceListFormatter {
15
16 /**
17 * The backlinks, in order, to pass as $3 to
18 * 'cite_references_link_many_format', defined in
19 * 'cite_references_link_many_format_backlink_labels
20 *
21 * @var string[]|null
22 */
23 private ?array $backlinkLabels = null;
24 private ErrorReporter $errorReporter;
25 private AnchorFormatter $anchorFormatter;
26 private ReferenceMessageLocalizer $messageLocalizer;
27
28 public function __construct(
29 ErrorReporter $errorReporter,
30 AnchorFormatter $anchorFormatter,
31 ReferenceMessageLocalizer $messageLocalizer
32 ) {
33 $this->errorReporter = $errorReporter;
34 $this->anchorFormatter = $anchorFormatter;
35 $this->messageLocalizer = $messageLocalizer;
36 }
37
38 /**
39 * @param Parser $parser
40 * @param array<string|int,ReferenceStackItem> $groupRefs
41 * @param bool $responsive
42 * @param bool $isSectionPreview
43 *
44 * @return string HTML
45 */
46 public function formatReferences(
47 Parser $parser,
48 array $groupRefs,
49 bool $responsive,
50 bool $isSectionPreview
51 ): string {
52 if ( !$groupRefs ) {
53 return '';
54 }
55
56 $wikitext = $this->formatRefsList( $parser, $groupRefs, $isSectionPreview );
57 $html = $parser->recursiveTagParse( $wikitext );
58 $html = Html::rawElement( 'ol', [ 'class' => 'references' ], $html );
59
60 if ( $responsive ) {
61 $wrapClasses = [ 'mw-references-wrap' ];
62 if ( count( $groupRefs ) > 10 ) {
63 $wrapClasses[] = 'mw-references-columns';
64 }
65 // Use a DIV wrap because column-count on a list directly is broken in Chrome.
66 // See https://bugs.chromium.org/p/chromium/issues/detail?id=498730.
67 return Html::rawElement( 'div', [ 'class' => $wrapClasses ], $html );
68 }
69
70 return $html;
71 }
72
73 /**
74 * @param Parser $parser
75 * @param array<string|int,ReferenceStackItem> $groupRefs
76 * @param bool $isSectionPreview
77 *
78 * @return string Wikitext
79 */
80 private function formatRefsList(
81 Parser $parser,
82 array $groupRefs,
83 bool $isSectionPreview
84 ): string {
85 // After sorting the list, we can assume that references are in the same order as their
86 // numbering. Subreferences will come immediately after their parent.
87 uasort(
88 $groupRefs,
89 static function ( ReferenceStackItem $a, ReferenceStackItem $b ): int {
90 $cmp = ( $a->number ?? 0 ) - ( $b->number ?? 0 );
91 return $cmp ?: ( $a->extendsIndex ?? 0 ) - ( $b->extendsIndex ?? 0 );
92 }
93 );
94
95 // Add new lines between the list items (ref entries) to avoid confusing tidy (T15073).
96 // Note: This builds a string of wikitext, not html.
97 $parserInput = "\n";
98 /** @var string|bool $indented */
99 $indented = false;
100 foreach ( $groupRefs as $key => &$ref ) {
101 // Make sure the parent is not a subreference.
102 // FIXME: Move to a validation function.
103 $extends =& $ref->extends;
104 if ( $extends !== null && isset( $groupRefs[$extends]->extends ) ) {
105 $ref->warnings[] = [ 'cite_error_ref_nested_extends',
106 $extends, $groupRefs[$extends]->extends ];
107 }
108
109 if ( !$indented && $extends !== null ) {
110 // The nested <ol> must be inside the parent's <li>
111 if ( preg_match( '#</li>\s*$#D', $parserInput, $matches, PREG_OFFSET_CAPTURE ) ) {
112 $parserInput = substr( $parserInput, 0, $matches[0][1] );
113 }
114 $parserInput .= Html::openElement( 'ol', [ 'class' => 'mw-extended-references' ] );
115 $indented = $matches[0][0] ?? true;
116 } elseif ( $indented && $extends === null ) {
117 $parserInput .= $this->closeIndention( $indented );
118 $indented = false;
119 }
120 $parserInput .= $this->formatListItem( $parser, $key, $ref, $isSectionPreview ) . "\n";
121 }
122 $parserInput .= $this->closeIndention( $indented );
123 return $parserInput;
124 }
125
126 /**
127 * @param string|bool $closingLi
128 *
129 * @return string
130 */
131 private function closeIndention( $closingLi ): string {
132 if ( !$closingLi ) {
133 return '';
134 }
135
136 return Html::closeElement( 'ol' ) . ( is_string( $closingLi ) ? $closingLi : '' );
137 }
138
139 /**
140 * @param Parser $parser
141 * @param string|int $key The key of the reference
142 * @param ReferenceStackItem $ref
143 * @param bool $isSectionPreview
144 *
145 * @return string Wikitext, wrapped in a single <li> element
146 */
147 private function formatListItem(
148 Parser $parser, $key, ReferenceStackItem $ref, bool $isSectionPreview
149 ): string {
150 $text = $this->renderTextAndWarnings( $parser, $key, $ref, $isSectionPreview );
151
152 // Special case for an incomplete follow="…". This is valid e.g. in the Page:… namespace on
153 // Wikisource. Note this returns a <p>, not an <li> as expected!
154 if ( $ref->follow !== null ) {
155 return '<p id="' . $this->anchorFormatter->jumpLinkTarget( $ref->follow ) . '">' . $text . '</p>';
156 }
157
158 // Parameter $4 in the cite_references_link_one and cite_references_link_many messages
159 $extraAttributes = '';
160 if ( $ref->dir !== null ) {
161 // The following classes are generated here:
162 // * mw-cite-dir-ltr
163 // * mw-cite-dir-rtl
164 $extraAttributes = Html::expandAttributes( [ 'class' => 'mw-cite-dir-' . $ref->dir ] );
165 }
166
167 if ( $ref->count === 1 ) {
168 if ( $ref->name === null ) {
169 $id = $ref->key;
170 $backlinkId = $this->anchorFormatter->backLink( $ref->key );
171 } else {
172 $id = $key . '-' . $ref->key;
173 // TODO: Use count without decrementing.
174 $backlinkId = $this->anchorFormatter->backLink( $key, $ref->key . '-' . ( $ref->count - 1 ) );
175 }
176 return $this->messageLocalizer->msg(
177 'cite_references_link_one',
178 $this->anchorFormatter->jumpLinkTarget( $id ),
179 $backlinkId,
180 $text,
181 $extraAttributes
182 )->plain();
183 }
184
185 $backlinks = [];
186 for ( $i = 0; $i < $ref->count; $i++ ) {
187 $numericLabel = $this->referencesFormatEntryNumericBacklinkLabel(
188 $ref->number . ( $ref->extendsIndex ? '.' . $ref->extendsIndex : '' ),
189 $i,
190 $ref->count
191 );
192 $backlinks[] = $this->messageLocalizer->msg(
193 'cite_references_link_many_format',
194 $this->anchorFormatter->backLink( $key, $ref->key . '-' . $i ),
195 $numericLabel,
196 $this->referencesFormatEntryAlternateBacklinkLabel( $parser, $i ) ?? $numericLabel
197 )->plain();
198 }
199
200 // The parent of a subref might actually be unused and therefor have zero backlinks
201 $linkTargetId = $ref->count > 0 ?
202 $this->anchorFormatter->jumpLinkTarget( $key . '-' . $ref->key ) : '';
203 return $this->messageLocalizer->msg(
204 'cite_references_link_many',
205 $linkTargetId,
206 $this->listToText( $backlinks ),
207 $text,
208 $extraAttributes
209 )->plain();
210 }
211
212 /**
213 * @param Parser $parser
214 * @param string|int $key
215 * @param ReferenceStackItem $ref
216 * @param bool $isSectionPreview
217 *
218 * @return string Wikitext
219 */
220 private function renderTextAndWarnings(
221 Parser $parser, $key, ReferenceStackItem $ref, bool $isSectionPreview
222 ): string {
223 if ( $ref->text === null ) {
224 return $this->errorReporter->plain( $parser,
225 $isSectionPreview
226 ? 'cite_warning_sectionpreview_no_text'
227 : 'cite_error_references_no_text', $key );
228 }
229
230 $text = $ref->text ?? '';
231 foreach ( $ref->warnings as $warning ) {
232 // @phan-suppress-next-line PhanParamTooFewUnpack
233 $text .= ' ' . $this->errorReporter->plain( $parser, ...$warning );
234 // FIXME: We could use a StatusValue object to get rid of duplicates
235 break;
236 }
237
238 return '<span class="reference-text">' . rtrim( $text, "\n" ) . "</span>\n";
239 }
240
241 /**
242 * Generate a numeric backlink given a base number and an
243 * offset, e.g. $base = 1, $offset = 2; = 1.2
244 * Since bug #5525, it correctly does 1.9 -> 1.10 as well as 1.099 -> 1.100
245 *
246 * @param string $base
247 * @param int $offset
248 * @param int $max Maximum value expected.
249 *
250 * @return string
251 */
252 private function referencesFormatEntryNumericBacklinkLabel(
253 string $base,
254 int $offset,
255 int $max
256 ): string {
257 return $this->messageLocalizer->localizeDigits( $base ) .
258 $this->messageLocalizer->localizeSeparators( '.' ) .
259 $this->messageLocalizer->localizeDigits(
260 str_pad( (string)$offset, strlen( (string)$max ), '0', STR_PAD_LEFT )
261 );
262 }
263
264 /**
265 * Generate a custom format backlink given an offset, e.g.
266 * $offset = 2; = c if $this->mBacklinkLabels = [ 'a',
267 * 'b', 'c', ...]. Return an error if the offset > the # of
268 * array items
269 */
270 private function referencesFormatEntryAlternateBacklinkLabel(
271 Parser $parser, int $offset
272 ): ?string {
273 if ( $this->backlinkLabels === null ) {
274 $msg = $this->messageLocalizer->msg( 'cite_references_link_many_format_backlink_labels' );
275 $this->backlinkLabels = $msg->isDisabled() ? [] : preg_split( '/\s+/', $msg->plain() );
276 }
277
278 // Disabling the message just disables the feature
279 if ( !$this->backlinkLabels ) {
280 return null;
281 }
282
283 return $this->backlinkLabels[$offset]
284 ?? $this->errorReporter->plain( $parser, 'cite_error_references_no_backlink_label' );
285 }
286
287 /**
288 * This does approximately the same thing as
289 * Language::listToText() but due to this being used for a
290 * slightly different purpose (people might not want , as the
291 * first separator and not 'and' as the second, and this has to
292 * use messages from the content language) I'm rolling my own.
293 *
294 * @param string[] $arr The array to format
295 *
296 * @return string Wikitext
297 */
298 private function listToText( array $arr ): string {
299 $lastElement = array_pop( $arr );
300
301 if ( $arr === [] ) {
302 return (string)$lastElement;
303 }
304
305 $sep = $this->messageLocalizer->msg( 'cite_references_link_many_sep' )->plain();
306 $and = $this->messageLocalizer->msg( 'cite_references_link_many_and' )->plain();
307 return implode( $sep, $arr ) . $and . $lastElement;
308 }
309
310 }