MediaWiki  1.30.0
LinkRenderer.php
Go to the documentation of this file.
1 <?php
22 namespace MediaWiki\Linker;
23 
25 use Hooks;
26 use Html;
29 use Linker;
32 use Sanitizer;
33 use Title;
35 
42 class LinkRenderer {
43 
49  private $forceArticlePath = false;
50 
56  private $expandUrls = false;
57 
61  private $stubThreshold = 0;
62 
66  private $titleFormatter;
67 
71  private $linkCache;
72 
78  private $runLegacyBeginHook = true;
79 
85  $this->titleFormatter = $titleFormatter;
86  $this->linkCache = $linkCache;
87  }
88 
92  public function setForceArticlePath( $force ) {
93  $this->forceArticlePath = $force;
94  }
95 
99  public function getForceArticlePath() {
101  }
102 
106  public function setExpandURLs( $expand ) {
107  $this->expandUrls = $expand;
108  }
109 
113  public function getExpandURLs() {
114  return $this->expandUrls;
115  }
116 
120  public function setStubThreshold( $threshold ) {
121  $this->stubThreshold = $threshold;
122  }
123 
127  public function getStubThreshold() {
128  return $this->stubThreshold;
129  }
130 
134  public function setRunLegacyBeginHook( $run ) {
135  $this->runLegacyBeginHook = $run;
136  }
137 
145  public function makeLink(
146  LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
147  ) {
148  $title = Title::newFromLinkTarget( $target );
149  if ( $title->isKnown() ) {
150  return $this->makeKnownLink( $target, $text, $extraAttribs, $query );
151  } else {
152  return $this->makeBrokenLink( $target, $text, $extraAttribs, $query );
153  }
154  }
155 
162  private function getLegacyOptions( $isKnown ) {
163  $options = [ 'stubThreshold' => $this->stubThreshold ];
164  if ( $this->forceArticlePath ) {
165  $options[] = 'forcearticlepath';
166  }
167  if ( $this->expandUrls === PROTO_HTTP ) {
168  $options[] = 'http';
169  } elseif ( $this->expandUrls === PROTO_HTTPS ) {
170  $options[] = 'https';
171  }
172 
173  $options[] = $isKnown ? 'known' : 'broken';
174 
175  return $options;
176  }
177 
178  private function runBeginHook( LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown ) {
179  $ret = null;
180  if ( !Hooks::run( 'HtmlPageLinkRendererBegin',
181  [ $this, $target, &$text, &$extraAttribs, &$query, &$ret ] )
182  ) {
183  return $ret;
184  }
185 
186  // Now run the legacy hook
187  return $this->runLegacyBeginHook( $target, $text, $extraAttribs, $query, $isKnown );
188  }
189 
190  private function runLegacyBeginHook( LinkTarget $target, &$text, &$extraAttribs, &$query,
191  $isKnown
192  ) {
193  if ( !$this->runLegacyBeginHook || !Hooks::isRegistered( 'LinkBegin' ) ) {
194  // Disabled, or nothing registered
195  return null;
196  }
197 
198  $realOptions = $options = $this->getLegacyOptions( $isKnown );
199  $ret = null;
200  $dummy = new DummyLinker();
201  $title = Title::newFromLinkTarget( $target );
202  if ( $text !== null ) {
203  $realHtml = $html = HtmlArmor::getHtml( $text );
204  } else {
205  $realHtml = $html = null;
206  }
207  if ( !Hooks::run( 'LinkBegin',
208  [ $dummy, $title, &$html, &$extraAttribs, &$query, &$options, &$ret ] )
209  ) {
210  return $ret;
211  }
212 
213  if ( $html !== null && $html !== $realHtml ) {
214  // &$html was modified, so re-armor it as $text
215  $text = new HtmlArmor( $html );
216  }
217 
218  // Check if they changed any of the options, hopefully not!
219  if ( $options !== $realOptions ) {
220  $factory = MediaWikiServices::getInstance()->getLinkRendererFactory();
221  // They did, so create a separate instance and have that take over the rest
222  $newRenderer = $factory->createFromLegacyOptions( $options );
223  // Don't recurse the hook...
224  $newRenderer->setRunLegacyBeginHook( false );
225  if ( in_array( 'known', $options, true ) ) {
226  return $newRenderer->makeKnownLink( $title, $text, $extraAttribs, $query );
227  } elseif ( in_array( 'broken', $options, true ) ) {
228  return $newRenderer->makeBrokenLink( $title, $text, $extraAttribs, $query );
229  } else {
230  return $newRenderer->makeLink( $title, $text, $extraAttribs, $query );
231  }
232  }
233 
234  return null;
235  }
236 
248  public function makePreloadedLink(
249  LinkTarget $target, $text = null, $classes, array $extraAttribs = [], array $query = []
250  ) {
251  // Run begin hook
252  $ret = $this->runBeginHook( $target, $text, $extraAttribs, $query, true );
253  if ( $ret !== null ) {
254  return $ret;
255  }
256  $target = $this->normalizeTarget( $target );
257  $url = $this->getLinkURL( $target, $query );
258  $attribs = [ 'class' => $classes ];
259  $prefixedText = $this->titleFormatter->getPrefixedText( $target );
260  if ( $prefixedText !== '' ) {
261  $attribs['title'] = $prefixedText;
262  }
263 
264  $attribs = [
265  'href' => $url,
266  ] + $this->mergeAttribs( $attribs, $extraAttribs );
267 
268  if ( $text === null ) {
269  $text = $this->getLinkText( $target );
270  }
271 
272  return $this->buildAElement( $target, $text, $attribs, true );
273  }
274 
282  public function makeKnownLink(
283  LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
284  ) {
285  $classes = [];
286  if ( $target->isExternal() ) {
287  $classes[] = 'extiw';
288  }
289  $colour = $this->getLinkClasses( $target );
290  if ( $colour !== '' ) {
291  $classes[] = $colour;
292  }
293 
294  return $this->makePreloadedLink(
295  $target,
296  $text,
297  $classes ? implode( ' ', $classes ) : '',
298  $extraAttribs,
299  $query
300  );
301  }
302 
310  public function makeBrokenLink(
311  LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
312  ) {
313  // Run legacy hook
314  $ret = $this->runBeginHook( $target, $text, $extraAttribs, $query, false );
315  if ( $ret !== null ) {
316  return $ret;
317  }
318 
319  # We don't want to include fragments for broken links, because they
320  # generally make no sense.
321  if ( $target->hasFragment() ) {
322  $target = $target->createFragmentTarget( '' );
323  }
324  $target = $this->normalizeTarget( $target );
325 
326  if ( !isset( $query['action'] ) && $target->getNamespace() !== NS_SPECIAL ) {
327  $query['action'] = 'edit';
328  $query['redlink'] = '1';
329  }
330 
331  $url = $this->getLinkURL( $target, $query );
332  $attribs = [ 'class' => 'new' ];
333  $prefixedText = $this->titleFormatter->getPrefixedText( $target );
334  if ( $prefixedText !== '' ) {
335  // This ends up in parser cache!
336  $attribs['title'] = wfMessage( 'red-link-title', $prefixedText )
337  ->inContentLanguage()
338  ->text();
339  }
340 
341  $attribs = [
342  'href' => $url,
343  ] + $this->mergeAttribs( $attribs, $extraAttribs );
344 
345  if ( $text === null ) {
346  $text = $this->getLinkText( $target );
347  }
348 
349  return $this->buildAElement( $target, $text, $attribs, false );
350  }
351 
361  private function buildAElement( LinkTarget $target, $text, array $attribs, $isKnown ) {
362  $ret = null;
363  if ( !Hooks::run( 'HtmlPageLinkRendererEnd',
364  [ $this, $target, $isKnown, &$text, &$attribs, &$ret ] )
365  ) {
366  return $ret;
367  }
368 
369  $html = HtmlArmor::getHtml( $text );
370 
371  // Run legacy hook
372  if ( Hooks::isRegistered( 'LinkEnd' ) ) {
373  $dummy = new DummyLinker();
374  $title = Title::newFromLinkTarget( $target );
375  $options = $this->getLegacyOptions( $isKnown );
376  if ( !Hooks::run( 'LinkEnd',
377  [ $dummy, $title, $options, &$html, &$attribs, &$ret ] )
378  ) {
379  return $ret;
380  }
381  }
382 
383  return Html::rawElement( 'a', $attribs, $html );
384  }
385 
390  private function getLinkText( LinkTarget $target ) {
391  $prefixedText = $this->titleFormatter->getPrefixedText( $target );
392  // If the target is just a fragment, with no title, we return the fragment
393  // text. Otherwise, we return the title text itself.
394  if ( $prefixedText === '' && $target->hasFragment() ) {
395  return $target->getFragment();
396  }
397 
398  return $prefixedText;
399  }
400 
401  private function getLinkURL( LinkTarget $target, array $query = [] ) {
402  // TODO: Use a LinkTargetResolver service instead of Title
403  $title = Title::newFromLinkTarget( $target );
404  if ( $this->forceArticlePath ) {
405  $realQuery = $query;
406  $query = [];
407  } else {
408  $realQuery = [];
409  }
410  $url = $title->getLinkURL( $query, false, $this->expandUrls );
411 
412  if ( $this->forceArticlePath && $realQuery ) {
413  $url = wfAppendQuery( $url, $realQuery );
414  }
415 
416  return $url;
417  }
418 
426  private function normalizeTarget( LinkTarget $target ) {
427  return Linker::normaliseSpecialPage( $target );
428  }
429 
438  private function mergeAttribs( $defaults, $attribs ) {
439  if ( !$attribs ) {
440  return $defaults;
441  }
442  # Merge the custom attribs with the default ones, and iterate
443  # over that, deleting all "false" attributes.
444  $ret = [];
445  $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
446  foreach ( $merged as $key => $val ) {
447  # A false value suppresses the attribute
448  if ( $val !== false ) {
449  $ret[$key] = $val;
450  }
451  }
452  return $ret;
453  }
454 
461  public function getLinkClasses( LinkTarget $target ) {
462  // Make sure the target is in the cache
463  $id = $this->linkCache->addLinkObj( $target );
464  if ( $id == 0 ) {
465  // Doesn't exist
466  return '';
467  }
468 
469  if ( $this->linkCache->getGoodLinkFieldObj( $target, 'redirect' ) ) {
470  # Page is a redirect
471  return 'mw-redirect';
472  } elseif ( $this->stubThreshold > 0 && MWNamespace::isContent( $target->getNamespace() )
473  && $this->linkCache->getGoodLinkFieldObj( $target, 'length' ) < $this->stubThreshold
474  ) {
475  # Page is a stub
476  return 'stub';
477  }
478 
479  return '';
480  }
481 }
MediaWiki\Linker\LinkRenderer\$titleFormatter
TitleFormatter $titleFormatter
Definition: LinkRenderer.php:66
LinkCache
Cache for article titles (prefixed DB keys) and ids linked from one source.
Definition: LinkCache.php:34
MediaWiki\Linker\LinkRenderer\$stubThreshold
int $stubThreshold
Definition: LinkRenderer.php:61
HtmlArmor
Marks HTML that shouldn't be escaped.
Definition: HtmlArmor.php:28
Linker
Some internal bits split of from Skin.php.
Definition: Linker.php:34
MediaWiki\Linker\LinkRenderer\getLinkText
getLinkText(LinkTarget $target)
Definition: LinkRenderer.php:390
MediaWiki\Linker\LinkRenderer\mergeAttribs
mergeAttribs( $defaults, $attribs)
Merges two sets of attributes.
Definition: LinkRenderer.php:438
MediaWiki\Linker\LinkRenderer\normalizeTarget
normalizeTarget(LinkTarget $target)
Normalizes the provided target.
Definition: LinkRenderer.php:426
MediaWiki\Linker\LinkRenderer\$linkCache
LinkCache $linkCache
Definition: LinkRenderer.php:71
MediaWiki\Linker\LinkRenderer\__construct
__construct(TitleFormatter $titleFormatter, LinkCache $linkCache)
Definition: LinkRenderer.php:84
MediaWiki\Linker\LinkRenderer\getLegacyOptions
getLegacyOptions( $isKnown)
Get the options in the legacy format.
Definition: LinkRenderer.php:162
MediaWiki\Linker\LinkRenderer\setRunLegacyBeginHook
setRunLegacyBeginHook( $run)
Definition: LinkRenderer.php:134
MediaWiki\Linker\LinkTarget\createFragmentTarget
createFragmentTarget( $fragment)
Creates a new LinkTarget for a different fragment of the same page.
MediaWiki\Linker\LinkRenderer
Class that generates HTML links for pages.
Definition: LinkRenderer.php:42
MediaWiki\Linker\LinkRenderer\buildAElement
buildAElement(LinkTarget $target, $text, array $attribs, $isKnown)
Builds the final element.
Definition: LinkRenderer.php:361
MediaWiki\Linker\LinkRenderer\setStubThreshold
setStubThreshold( $threshold)
Definition: LinkRenderer.php:120
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MediaWiki\Linker\LinkRenderer\getLinkClasses
getLinkClasses(LinkTarget $target)
Return the CSS classes of a known link.
Definition: LinkRenderer.php:461
MediaWiki\Linker\LinkRenderer\$expandUrls
string bool int $expandUrls
A PROTO_* constant or false.
Definition: LinkRenderer.php:56
MediaWiki\Linker\LinkTarget\isExternal
isExternal()
Whether this LinkTarget has an interwiki component.
MediaWiki\Linker\LinkRenderer\getForceArticlePath
getForceArticlePath()
Definition: LinkRenderer.php:99
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:534
MediaWiki\Linker\LinkRenderer\getExpandURLs
getExpandURLs()
Definition: LinkRenderer.php:113
$query
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1581
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:54
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
$expand
if(! $dbr->tableExists( 'profiling')) $expand
Definition: profileinfo.php:164
$html
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1965
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:932
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
Definition: Title.php:239
HtmlArmor\getHtml
static getHtml( $input)
Provide a string or HtmlArmor object and get safe HTML back.
Definition: HtmlArmor.php:50
MediaWiki\Linker
Definition: LinkRenderer.php:22
MediaWiki\Linker\LinkRenderer\$forceArticlePath
bool $forceArticlePath
Whether to force the pretty article path.
Definition: LinkRenderer.php:49
$attribs
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1965
MWNamespace\isContent
static isContent( $index)
Does this namespace contain content, for the purposes of calculating statistics, etc?
Definition: MWNamespace.php:311
MWNamespace
This is a utility class with only static functions for dealing with namespaces that encodes all the "...
Definition: MWNamespace.php:32
MediaWiki\Linker\LinkRenderer\setExpandURLs
setExpandURLs( $expand)
Definition: LinkRenderer.php:106
PROTO_HTTPS
const PROTO_HTTPS
Definition: Defines.php:221
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:99
MediaWiki\Linker\LinkRenderer\setForceArticlePath
setForceArticlePath( $force)
Definition: LinkRenderer.php:92
Linker\normaliseSpecialPage
static normaliseSpecialPage(LinkTarget $target)
Definition: Linker.php:230
MediaWiki\Linker\LinkRenderer\runBeginHook
runBeginHook(LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown)
Definition: LinkRenderer.php:178
MediaWiki\Linker\LinkRenderer\$runLegacyBeginHook
bool $runLegacyBeginHook
Whether to run the legacy Linker hooks.
Definition: LinkRenderer.php:78
MediaWiki\Linker\LinkTarget\getFragment
getFragment()
Get the link fragment (i.e.
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:220
MediaWiki\Linker\LinkRenderer\runLegacyBeginHook
runLegacyBeginHook(LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown)
Definition: LinkRenderer.php:190
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1965
DummyLinker
Definition: DummyLinker.php:6
MediaWiki\Linker\LinkRenderer\makePreloadedLink
makePreloadedLink(LinkTarget $target, $text=null, $classes, array $extraAttribs=[], array $query=[])
If you have already looked up the proper CSS classes using LinkRenderer::getLinkClasses() or some oth...
Definition: LinkRenderer.php:248
Hooks\isRegistered
static isRegistered( $name)
Returns true if a hook has a function registered to it.
Definition: Hooks.php:83
Title
Represents a title within MediaWiki.
Definition: Title.php:39
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1965
MediaWiki\Linker\LinkRenderer\makeKnownLink
makeKnownLink(LinkTarget $target, $text=null, array $extraAttribs=[], array $query=[])
Definition: LinkRenderer.php:282
TitleFormatter
A title formatter service for MediaWiki.
Definition: TitleFormatter.php:35
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
$run
$run
Definition: checkDupeMessages.php:28
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
MediaWiki\Linker\LinkRenderer\getLinkURL
getLinkURL(LinkTarget $target, array $query=[])
Definition: LinkRenderer.php:401
MediaWiki\Linker\LinkRenderer\getStubThreshold
getStubThreshold()
Definition: LinkRenderer.php:127
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:27
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
MediaWiki\Linker\LinkRenderer\makeLink
makeLink(LinkTarget $target, $text=null, array $extraAttribs=[], array $query=[])
Definition: LinkRenderer.php:145
MediaWiki\Linker\LinkTarget\hasFragment
hasFragment()
Whether the link target has a fragment.
MediaWiki\Linker\LinkRenderer\makeBrokenLink
makeBrokenLink(LinkTarget $target, $text=null, array $extraAttribs=[], array $query=[])
Definition: LinkRenderer.php:310
Hooks
Hooks class.
Definition: Hooks.php:34
array
the array() calling protocol came about after MediaWiki 1.4rc1.
Html
This class is a collection of static functions that serve two purposes:
Definition: Html.php:48