Merge "Add LinkRenderer (rewrite of Linker::link())"
[lhc/web/wiklou.git] / includes / linker / LinkRenderer.php
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 * @license GPL-2.0+
20 * @author Kunal Mehta <legoktm@member.fsf.org>
21 */
22 namespace MediaWiki\Linker;
23
24 use DummyLinker;
25 use Hooks;
26 use Html;
27 use HtmlArmor;
28 use Linker;
29 use MediaWiki\MediaWikiServices;
30 use Sanitizer;
31 use Title;
32 use TitleFormatter;
33
34 /**
35 * Class that generates HTML <a> links for pages.
36 *
37 * @since 1.28
38 */
39 class LinkRenderer {
40
41 /**
42 * Whether to force the pretty article path
43 *
44 * @var bool
45 */
46 private $forceArticlePath = false;
47
48 /**
49 * A PROTO_* constant or false
50 *
51 * @var string|bool|int
52 */
53 private $expandUrls = false;
54
55 /**
56 * Whether extra classes should be added
57 *
58 * @var bool
59 */
60 private $noClasses = false;
61
62 /**
63 * @var int
64 */
65 private $stubThreshold = 0;
66
67 /**
68 * @var TitleFormatter
69 */
70 private $titleFormatter;
71
72 /**
73 * Whether to run the legacy Linker hooks
74 *
75 * @var bool
76 */
77 private $runLegacyBeginHook = true;
78
79 /**
80 * @param TitleFormatter $titleFormatter
81 */
82 public function __construct( TitleFormatter $titleFormatter ) {
83 $this->titleFormatter = $titleFormatter;
84 }
85
86 /**
87 * @param bool $force
88 */
89 public function setForceArticlePath( $force ) {
90 $this->forceArticlePath = $force;
91 }
92
93 /**
94 * @return bool
95 */
96 public function getForceArticlePath() {
97 return $this->forceArticlePath;
98 }
99
100 /**
101 * @param string|bool|int $expand A PROTO_* constant or false
102 */
103 public function setExpandURLs( $expand ) {
104 $this->expandUrls = $expand;
105 }
106
107 /**
108 * @return string|bool|int a PROTO_* constant or false
109 */
110 public function getExpandURLs() {
111 return $this->expandUrls;
112 }
113
114 /**
115 * @param bool $no
116 */
117 public function setNoClasses( $no ) {
118 $this->noClasses = $no;
119 }
120
121 /**
122 * @return bool
123 */
124 public function getNoClasses() {
125 return $this->noClasses;
126 }
127
128 /**
129 * @param int $threshold
130 */
131 public function setStubThreshold( $threshold ) {
132 $this->stubThreshold = $threshold;
133 }
134
135 /**
136 * @return int
137 */
138 public function getStubThreshold() {
139 return $this->stubThreshold;
140 }
141
142 /**
143 * @param bool $run
144 */
145 public function setRunLegacyBeginHook( $run ) {
146 $this->runLegacyBeginHook = $run;
147 }
148
149 /**
150 * @param LinkTarget $target
151 * @param string|HtmlArmor|null $text
152 * @param array $extraAttribs
153 * @param array $query
154 * @return string
155 */
156 public function makeLink(
157 LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
158 ) {
159 $title = Title::newFromLinkTarget( $target );
160 if ( $title->isKnown() ) {
161 return $this->makeKnownLink( $target, $text, $extraAttribs, $query );
162 } else {
163 return $this->makeBrokenLink( $target, $text, $extraAttribs, $query );
164 }
165 }
166
167 /**
168 * Get the options in the legacy format
169 *
170 * @param bool $isKnown Whether the link is known or broken
171 * @return array
172 */
173 private function getLegacyOptions( $isKnown ) {
174 $options = [ 'stubThreshold' => $this->stubThreshold ];
175 if ( $this->noClasses ) {
176 $options[] = 'noclasses';
177 }
178 if ( $this->forceArticlePath ) {
179 $options[] = 'forcearticlepath';
180 }
181 if ( $this->expandUrls === PROTO_HTTP ) {
182 $options[] = 'http';
183 } elseif ( $this->expandUrls === PROTO_HTTPS ) {
184 $options[] = 'https';
185 }
186
187 $options[] = $isKnown ? 'known' : 'broken';
188
189 return $options;
190 }
191
192 private function runBeginHook( LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown ) {
193 $ret = null;
194 if ( !Hooks::run( 'HtmlPageLinkRendererBegin',
195 [ $this, $target, &$text, &$extraAttribs, &$query, &$ret ] )
196 ) {
197 return $ret;
198 }
199
200 // Now run the legacy hook
201 return $this->runLegacyBeginHook( $target, $text, $extraAttribs, $query, $isKnown );
202 }
203
204 private function runLegacyBeginHook( LinkTarget $target, &$text, &$extraAttribs, &$query,
205 $isKnown
206 ) {
207 if ( !$this->runLegacyBeginHook || !Hooks::isRegistered( 'LinkBegin' ) ) {
208 // Disabled, or nothing registered
209 return null;
210 }
211
212 $realOptions = $options = $this->getLegacyOptions( $isKnown );
213 $ret = null;
214 $dummy = new DummyLinker();
215 $title = Title::newFromLinkTarget( $target );
216 $realHtml = $html = HtmlArmor::getHtml( $text );
217 if ( !Hooks::run( 'LinkBegin',
218 [ $dummy, $title, &$html, &$extraAttribs, &$query, &$options, &$ret ] )
219 ) {
220 return $ret;
221 }
222
223 if ( $html !== null && $html !== $realHtml ) {
224 // &$html was modified, so re-armor it as $text
225 $text = new HtmlArmor( $html );
226 }
227
228 // Check if they changed any of the options, hopefully not!
229 if ( $options !== $realOptions ) {
230 $factory = MediaWikiServices::getInstance()->getLinkRendererFactory();
231 // They did, so create a separate instance and have that take over the rest
232 $newRenderer = $factory->createFromLegacyOptions( $options );
233 // Don't recurse the hook...
234 $newRenderer->setRunLegacyBeginHook( false );
235 if ( in_array( 'known', $options, true ) ) {
236 return $newRenderer->makeKnownLink( $title, $text, $extraAttribs, $query );
237 } elseif ( in_array( 'broken', $options, true ) ) {
238 return $newRenderer->makeBrokenLink( $title, $text, $extraAttribs, $query );
239 } else {
240 return $newRenderer->makeLink( $title, $text, $extraAttribs, $query );
241 }
242 }
243
244 return null;
245 }
246
247 /**
248 * @param LinkTarget $target
249 * @param string|HtmlArmor|null $text
250 * @param array $extraAttribs
251 * @param array $query
252 * @return string
253 */
254 public function makeKnownLink(
255 LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
256 ) {
257 // Run begin hook
258 $ret = $this->runBeginHook( $target, $text, $extraAttribs, $query, true );
259 if ( $ret !== null ) {
260 return $ret;
261 }
262 $target = $this->normalizeTarget( $target );
263 $url = $this->getLinkURL( $target, $query );
264 $attribs = [];
265 if ( !$this->noClasses ) {
266 $classes = [];
267 if ( $target->isExternal() ) {
268 $classes[] = 'extiw';
269 }
270 $title = Title::newFromLinkTarget( $target );
271 $colour = Linker::getLinkColour( $title, $this->stubThreshold );
272 if ( $colour !== '' ) {
273 $classes[] = $colour;
274 }
275 if ( $classes ) {
276 $attribs['class'] = implode( ' ', $classes );
277 }
278 }
279
280 $prefixedText = $this->titleFormatter->getPrefixedText( $target );
281 if ( $prefixedText !== '' ) {
282 $attribs['title'] = $prefixedText;
283 }
284
285 $attribs = [
286 'href' => $url,
287 ] + $this->mergeAttribs( $attribs, $extraAttribs );
288
289 if ( $text === null ) {
290 $text = $this->getLinkText( $target );
291 }
292
293 return $this->buildAElement( $target, $text, $attribs, true );
294 }
295
296 /**
297 * @param LinkTarget $target
298 * @param string|HtmlArmor|null $text
299 * @param array $extraAttribs
300 * @param array $query
301 * @return string
302 */
303 public function makeBrokenLink(
304 LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
305 ) {
306 // Run legacy hook
307 $ret = $this->runBeginHook( $target, $text, $extraAttribs, $query, false );
308 if ( $ret !== null ) {
309 return $ret;
310 }
311
312 # We don't want to include fragments for broken links, because they
313 # generally make no sense.
314 if ( $target->hasFragment() ) {
315 $target = $target->createFragmentTarget( '' );
316 }
317 $target = $this->normalizeTarget( $target );
318
319 if ( !isset( $query['action'] ) && $target->getNamespace() !== NS_SPECIAL ) {
320 $query['action'] = 'edit';
321 $query['redlink'] = '1';
322 }
323
324 $url = $this->getLinkURL( $target, $query );
325 $attribs = $this->noClasses ? [] : [ 'class' => 'new' ];
326 $prefixedText = $this->titleFormatter->getPrefixedText( $target );
327 if ( $prefixedText !== '' ) {
328 // This ends up in parser cache!
329 $attribs['title'] = wfMessage( 'red-link-title', $prefixedText )
330 ->inContentLanguage()
331 ->text();
332 }
333
334 $attribs = [
335 'href' => $url,
336 ] + $this->mergeAttribs( $attribs, $extraAttribs );
337
338 if ( $text === null ) {
339 $text = $this->getLinkText( $target );
340 }
341
342 return $this->buildAElement( $target, $text, $attribs, false );
343 }
344
345 /**
346 * Builds the final <a> element
347 *
348 * @param LinkTarget $target
349 * @param string|HtmlArmor $text
350 * @param array $attribs
351 * @param bool $isKnown
352 * @return null|string
353 */
354 private function buildAElement( LinkTarget $target, $text, array $attribs, $isKnown ) {
355 $ret = null;
356 if ( !Hooks::run( 'HtmlPageLinkRendererEnd',
357 [ $this, $target, $isKnown, &$text, &$attribs, &$ret ] )
358 ) {
359 return $ret;
360 }
361
362 $html = HtmlArmor::getHtml( $text );
363
364 // Run legacy hook
365 if ( Hooks::isRegistered( 'LinkEnd' ) ) {
366 $dummy = new DummyLinker();
367 $title = Title::newFromLinkTarget( $target );
368 $options = $this->getLegacyOptions( $isKnown );
369 if ( !Hooks::run( 'LinkEnd',
370 [ $dummy, $title, $options, &$html, &$attribs, &$ret ] )
371 ) {
372 return $ret;
373 }
374 }
375
376 return Html::rawElement( 'a', $attribs, $html );
377 }
378
379 /**
380 * @param LinkTarget $target
381 * @return string non-escaped text
382 */
383 private function getLinkText( LinkTarget $target ) {
384 $prefixedText = $this->titleFormatter->getPrefixedText( $target );
385 // If the target is just a fragment, with no title, we return the fragment
386 // text. Otherwise, we return the title text itself.
387 if ( $prefixedText === '' && $target->hasFragment() ) {
388 return $target->getFragment();
389 }
390
391 return $prefixedText;
392 }
393
394 private function getLinkURL( LinkTarget $target, array $query = [] ) {
395 // TODO: Use a LinkTargetResolver service instead of Title
396 $title = Title::newFromLinkTarget( $target );
397 $proto = $this->expandUrls !== false
398 ? $this->expandUrls
399 : PROTO_RELATIVE;
400 if ( $this->forceArticlePath ) {
401 $realQuery = $query;
402 $query = [];
403 } else {
404 $realQuery = [];
405 }
406 $url = $title->getLinkURL( $query, false, $proto );
407
408 if ( $this->forceArticlePath && $realQuery ) {
409 $url = wfAppendQuery( $url, $realQuery );
410 }
411
412 return $url;
413 }
414
415 /**
416 * Normalizes the provided target
417 *
418 * @todo move the code from Linker actually here
419 * @param LinkTarget $target
420 * @return LinkTarget
421 */
422 private function normalizeTarget( LinkTarget $target ) {
423 return Linker::normaliseSpecialPage( $target );
424 }
425
426 /**
427 * Merges two sets of attributes
428 *
429 * @param array $defaults
430 * @param array $attribs
431 *
432 * @return array
433 */
434 private function mergeAttribs( $defaults, $attribs ) {
435 if ( !$attribs ) {
436 return $defaults;
437 }
438 # Merge the custom attribs with the default ones, and iterate
439 # over that, deleting all "false" attributes.
440 $ret = [];
441 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
442 foreach ( $merged as $key => $val ) {
443 # A false value suppresses the attribute
444 if ( $val !== false ) {
445 $ret[$key] = $val;
446 }
447 }
448 return $ret;
449 }
450
451 }