MediaWiki  master
LinkRenderer.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Linker;
22 
24 use Hooks;
25 use Html;
28 use Linker;
32 use Title;
34 
41 class LinkRenderer {
42 
48  private $forceArticlePath = false;
49 
55  private $expandUrls = false;
56 
60  private $stubThreshold = 0;
61 
65  private $titleFormatter;
66 
70  private $linkCache;
71 
77  private $runLegacyBeginHook = true;
78 
84  $this->titleFormatter = $titleFormatter;
85  $this->linkCache = $linkCache;
86  }
87 
91  public function setForceArticlePath( $force ) {
92  $this->forceArticlePath = $force;
93  }
94 
98  public function getForceArticlePath() {
100  }
101 
105  public function setExpandURLs( $expand ) {
106  $this->expandUrls = $expand;
107  }
108 
112  public function getExpandURLs() {
113  return $this->expandUrls;
114  }
115 
119  public function setStubThreshold( $threshold ) {
120  $this->stubThreshold = $threshold;
121  }
122 
126  public function getStubThreshold() {
127  return $this->stubThreshold;
128  }
129 
133  public function setRunLegacyBeginHook( $run ) {
134  $this->runLegacyBeginHook = $run;
135  }
136 
144  public function makeLink(
145  LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
146  ) {
147  $title = Title::newFromLinkTarget( $target );
148  if ( $title->isKnown() ) {
149  return $this->makeKnownLink( $target, $text, $extraAttribs, $query );
150  } else {
151  return $this->makeBrokenLink( $target, $text, $extraAttribs, $query );
152  }
153  }
154 
161  private function getLegacyOptions( $isKnown ) {
162  $options = [ 'stubThreshold' => $this->stubThreshold ];
163  if ( $this->forceArticlePath ) {
164  $options[] = 'forcearticlepath';
165  }
166  if ( $this->expandUrls === PROTO_HTTP ) {
167  $options[] = 'http';
168  } elseif ( $this->expandUrls === PROTO_HTTPS ) {
169  $options[] = 'https';
170  }
171 
172  $options[] = $isKnown ? 'known' : 'broken';
173 
174  return $options;
175  }
176 
177  private function runBeginHook( LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown ) {
178  $ret = null;
179  if ( !Hooks::run( 'HtmlPageLinkRendererBegin',
180  [ $this, $target, &$text, &$extraAttribs, &$query, &$ret ] )
181  ) {
182  return $ret;
183  }
184 
185  // Now run the legacy hook
186  return $this->runLegacyBeginHook( $target, $text, $extraAttribs, $query, $isKnown );
187  }
188 
189  private function runLegacyBeginHook( LinkTarget $target, &$text, &$extraAttribs, &$query,
190  $isKnown
191  ) {
192  if ( !$this->runLegacyBeginHook || !Hooks::isRegistered( 'LinkBegin' ) ) {
193  // Disabled, or nothing registered
194  return null;
195  }
196 
197  $realOptions = $options = $this->getLegacyOptions( $isKnown );
198  $ret = null;
199  $dummy = new DummyLinker();
200  $title = Title::newFromLinkTarget( $target );
201  if ( $text !== null ) {
202  $realHtml = $html = HtmlArmor::getHtml( $text );
203  } else {
204  $realHtml = $html = null;
205  }
206  if ( !Hooks::run( 'LinkBegin',
207  [ $dummy, $title, &$html, &$extraAttribs, &$query, &$options, &$ret ], '1.28' )
208  ) {
209  return $ret;
210  }
211 
212  if ( $html !== null && $html !== $realHtml ) {
213  // &$html was modified, so re-armor it as $text
214  $text = new HtmlArmor( $html );
215  }
216 
217  // Check if they changed any of the options, hopefully not!
218  if ( $options !== $realOptions ) {
219  $factory = MediaWikiServices::getInstance()->getLinkRendererFactory();
220  // They did, so create a separate instance and have that take over the rest
221  $newRenderer = $factory->createFromLegacyOptions( $options );
222  // Don't recurse the hook...
223  $newRenderer->setRunLegacyBeginHook( false );
224  if ( in_array( 'known', $options, true ) ) {
225  return $newRenderer->makeKnownLink( $title, $text, $extraAttribs, $query );
226  } elseif ( in_array( 'broken', $options, true ) ) {
227  return $newRenderer->makeBrokenLink( $title, $text, $extraAttribs, $query );
228  } else {
229  return $newRenderer->makeLink( $title, $text, $extraAttribs, $query );
230  }
231  }
232 
233  return null;
234  }
235 
247  public function makePreloadedLink(
248  LinkTarget $target, $text = null, $classes = '', array $extraAttribs = [], array $query = []
249  ) {
250  // Run begin hook
251  $ret = $this->runBeginHook( $target, $text, $extraAttribs, $query, true );
252  if ( $ret !== null ) {
253  return $ret;
254  }
255  $target = $this->normalizeTarget( $target );
256  $url = $this->getLinkURL( $target, $query );
257  $attribs = [ 'class' => $classes ];
258  $prefixedText = $this->titleFormatter->getPrefixedText( $target );
259  if ( $prefixedText !== '' ) {
260  $attribs['title'] = $prefixedText;
261  }
262 
263  $attribs = [
264  'href' => $url,
265  ] + $this->mergeAttribs( $attribs, $extraAttribs );
266 
267  if ( $text === null ) {
268  $text = $this->getLinkText( $target );
269  }
270 
271  return $this->buildAElement( $target, $text, $attribs, true );
272  }
273 
281  public function makeKnownLink(
282  LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
283  ) {
284  $classes = [];
285  if ( $target->isExternal() ) {
286  $classes[] = 'extiw';
287  }
288  $colour = $this->getLinkClasses( $target );
289  if ( $colour !== '' ) {
290  $classes[] = $colour;
291  }
292 
293  return $this->makePreloadedLink(
294  $target,
295  $text,
296  $classes ? implode( ' ', $classes ) : '',
297  $extraAttribs,
298  $query
299  );
300  }
301 
309  public function makeBrokenLink(
310  LinkTarget $target, $text = null, array $extraAttribs = [], array $query = []
311  ) {
312  // Run legacy hook
313  $ret = $this->runBeginHook( $target, $text, $extraAttribs, $query, false );
314  if ( $ret !== null ) {
315  return $ret;
316  }
317 
318  # We don't want to include fragments for broken links, because they
319  # generally make no sense.
320  if ( $target->hasFragment() ) {
321  $target = $target->createFragmentTarget( '' );
322  }
323  $target = $this->normalizeTarget( $target );
324 
325  if ( !isset( $query['action'] ) && $target->getNamespace() !== NS_SPECIAL ) {
326  $query['action'] = 'edit';
327  $query['redlink'] = '1';
328  }
329 
330  $url = $this->getLinkURL( $target, $query );
331  $attribs = [ 'class' => 'new' ];
332  $prefixedText = $this->titleFormatter->getPrefixedText( $target );
333  if ( $prefixedText !== '' ) {
334  // This ends up in parser cache!
335  $attribs['title'] = wfMessage( 'red-link-title', $prefixedText )
336  ->inContentLanguage()
337  ->text();
338  }
339 
340  $attribs = [
341  'href' => $url,
342  ] + $this->mergeAttribs( $attribs, $extraAttribs );
343 
344  if ( $text === null ) {
345  $text = $this->getLinkText( $target );
346  }
347 
348  return $this->buildAElement( $target, $text, $attribs, false );
349  }
350 
360  private function buildAElement( LinkTarget $target, $text, array $attribs, $isKnown ) {
361  $ret = null;
362  if ( !Hooks::run( 'HtmlPageLinkRendererEnd',
363  [ $this, $target, $isKnown, &$text, &$attribs, &$ret ] )
364  ) {
365  return $ret;
366  }
367 
368  $html = HtmlArmor::getHtml( $text );
369 
370  // Run legacy hook
371  if ( Hooks::isRegistered( 'LinkEnd' ) ) {
372  $dummy = new DummyLinker();
373  $title = Title::newFromLinkTarget( $target );
374  $options = $this->getLegacyOptions( $isKnown );
375  if ( !Hooks::run( 'LinkEnd',
376  [ $dummy, $title, $options, &$html, &$attribs, &$ret ], '1.28' )
377  ) {
378  return $ret;
379  }
380  }
381 
382  return Html::rawElement( 'a', $attribs, $html );
383  }
384 
389  private function getLinkText( LinkTarget $target ) {
390  $prefixedText = $this->titleFormatter->getPrefixedText( $target );
391  // If the target is just a fragment, with no title, we return the fragment
392  // text. Otherwise, we return the title text itself.
393  if ( $prefixedText === '' && $target->hasFragment() ) {
394  return $target->getFragment();
395  }
396 
397  return $prefixedText;
398  }
399 
400  private function getLinkURL( LinkTarget $target, array $query = [] ) {
401  // TODO: Use a LinkTargetResolver service instead of Title
402  $title = Title::newFromLinkTarget( $target );
403  if ( $this->forceArticlePath ) {
404  $realQuery = $query;
405  $query = [];
406  } else {
407  $realQuery = [];
408  }
409  $url = $title->getLinkURL( $query, false, $this->expandUrls );
410 
411  if ( $this->forceArticlePath && $realQuery ) {
412  $url = wfAppendQuery( $url, $realQuery );
413  }
414 
415  return $url;
416  }
417 
425  private function normalizeTarget( LinkTarget $target ) {
426  return Linker::normaliseSpecialPage( $target );
427  }
428 
437  private function mergeAttribs( $defaults, $attribs ) {
438  if ( !$attribs ) {
439  return $defaults;
440  }
441  # Merge the custom attribs with the default ones, and iterate
442  # over that, deleting all "false" attributes.
443  $ret = [];
444  $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
445  foreach ( $merged as $key => $val ) {
446  # A false value suppresses the attribute
447  if ( $val !== false ) {
448  $ret[$key] = $val;
449  }
450  }
451  return $ret;
452  }
453 
460  public function getLinkClasses( LinkTarget $target ) {
461  // Make sure the target is in the cache
462  $id = $this->linkCache->addLinkObj( $target );
463  if ( $id == 0 ) {
464  // Doesn't exist
465  return '';
466  }
467 
468  if ( $this->linkCache->getGoodLinkFieldObj( $target, 'redirect' ) ) {
469  # Page is a redirect
470  return 'mw-redirect';
471  } elseif ( $this->stubThreshold > 0 && MWNamespace::isContent( $target->getNamespace() )
472  && $this->linkCache->getGoodLinkFieldObj( $target, 'length' ) < $this->stubThreshold
473  ) {
474  # Page is a stub
475  return 'stub';
476  }
477 
478  return '';
479  }
480 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
buildAElement(LinkTarget $target, $text, array $attribs, $isKnown)
Builds the final element.
string bool int $expandUrls
A PROTO_* constant or false.
getLinkURL(LinkTarget $target, array $query=[])
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:1982
getLinkClasses(LinkTarget $target)
Return the CSS classes of a known link.
null for the local 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:1585
hasFragment()
Whether the link target has a fragment.
static getHtml( $input)
Provide a string or HtmlArmor object and get safe HTML back.
Definition: HtmlArmor.php:50
createFragmentTarget( $fragment)
Creates a new LinkTarget for a different fragment of the same page.
makeBrokenLink(LinkTarget $target, $text=null, array $extraAttribs=[], array $query=[])
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:1982
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
static normaliseSpecialPage(LinkTarget $target)
Definition: Linker.php:212
const NS_SPECIAL
Definition: Defines.php:53
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
getLinkText(LinkTarget $target)
mergeAttribs( $defaults, $attribs)
Merges two sets of attributes.
normalizeTarget(LinkTarget $target)
Normalizes the provided target.
static getInstance()
Returns the global default instance of the top level service locator.
__construct(TitleFormatter $titleFormatter, LinkCache $linkCache)
getNamespace()
Get the namespace index.
static isContent( $index)
Does this namespace contain content, for the purposes of calculating statistics, etc?
getFragment()
Get the link fragment (i.e.
isExternal()
Whether this LinkTarget has an interwiki component.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
const PROTO_HTTPS
Definition: Defines.php:220
Class that generates HTML links for pages.
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 use $formDescriptor instead 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
Some internal bits split of from Skin.php.
Definition: Linker.php:34
if(! $dbr->tableExists( 'profiling')) $expand
static mergeAttributes( $a, $b)
Merge two sets of HTML attributes.
Definition: Sanitizer.php:929
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:1982
makeKnownLink(LinkTarget $target, $text=null, array $extraAttribs=[], array $query=[])
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:1982
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
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
const PROTO_HTTP
Definition: Defines.php:219
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:271
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
static isRegistered( $name)
Returns true if a hook has a function registered to it.
Definition: Hooks.php:80
bool $forceArticlePath
Whether to force the pretty article path.
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...
runBeginHook(LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown)
makeLink(LinkTarget $target, $text=null, array $extraAttribs=[], array $query=[])
getLegacyOptions( $isKnown)
Get the options in the legacy format.
bool $runLegacyBeginHook
Whether to run the legacy Linker hooks.
runLegacyBeginHook(LinkTarget $target, &$text, &$extraAttribs, &$query, $isKnown)
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200