Refactor core from Title::getLinkUrl to Title::getLinkURL to match Title's getLocalUR...
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Some internal bits split of from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin.
6 *
7 * @ingroup Skins
8 */
9 class Linker {
10
11 /**
12 * Flags for userToolLinks()
13 */
14 const TOOL_LINKS_NOBLOCK = 1;
15 const TOOL_LINKS_EMAIL = 2;
16
17 /**
18 * Get the appropriate HTML attributes to add to the "a" element of an ex-
19 * ternal link, as created by [wikisyntax].
20 *
21 * @param $class String: the contents of the class attribute; if an empty
22 * string is passed, which is the default value, defaults to 'external'.
23 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
24 */
25 static function getExternalLinkAttributes( $class = 'external' ) {
26 wfDeprecated( __METHOD__ );
27 return self::getLinkAttributesInternal( '', $class );
28 }
29
30 /**
31 * Get the appropriate HTML attributes to add to the "a" element of an in-
32 * terwiki link.
33 *
34 * @param $title String: the title text for the link, URL-encoded (???) but
35 * not HTML-escaped
36 * @param $unused String: unused
37 * @param $class String: the contents of the class attribute; if an empty
38 * string is passed, which is the default value, defaults to 'external'.
39 */
40 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
41 global $wgContLang;
42
43 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
44 # getExternalLinkAttributes, why?
45 $title = urldecode( $title );
46 $title = $wgContLang->checkTitleEncoding( $title );
47 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
48
49 return self::getLinkAttributesInternal( $title, $class );
50 }
51
52 /**
53 * Get the appropriate HTML attributes to add to the "a" element of an in-
54 * ternal link.
55 *
56 * @param $title String: the title text for the link, URL-encoded (???) but
57 * not HTML-escaped
58 * @param $unused String: unused
59 * @param $class String: the contents of the class attribute, default none
60 */
61 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
62 $title = urldecode( $title );
63 $title = str_replace( '_', ' ', $title );
64 return self::getLinkAttributesInternal( $title, $class );
65 }
66
67 /**
68 * Get the appropriate HTML attributes to add to the "a" element of an in-
69 * ternal link, given the Title object for the page we want to link to.
70 *
71 * @param $nt Title
72 * @param $unused String: unused
73 * @param $class String: the contents of the class attribute, default none
74 * @param $title Mixed: optional (unescaped) string to use in the title
75 * attribute; if false, default to the name of the page we're linking to
76 */
77 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
78 if ( $title === false ) {
79 $title = $nt->getPrefixedText();
80 }
81 return self::getLinkAttributesInternal( $title, $class );
82 }
83
84 /**
85 * Common code for getLinkAttributesX functions
86 *
87 * @param $title string
88 * @param $class string
89 *
90 * @return string
91 */
92 private static function getLinkAttributesInternal( $title, $class ) {
93 $title = htmlspecialchars( $title );
94 $class = htmlspecialchars( $class );
95 $r = '';
96 if ( $class != '' ) {
97 $r .= " class=\"$class\"";
98 }
99 if ( $title != '' ) {
100 $r .= " title=\"$title\"";
101 }
102 return $r;
103 }
104
105 /**
106 * Return the CSS colour of a known link
107 *
108 * @param $t Title object
109 * @param $threshold Integer: user defined threshold
110 * @return String: CSS class
111 */
112 public static function getLinkColour( $t, $threshold ) {
113 $colour = '';
114 if ( $t->isRedirect() ) {
115 # Page is a redirect
116 $colour = 'mw-redirect';
117 } elseif ( $threshold > 0 &&
118 $t->exists() && $t->getLength() < $threshold &&
119 $t->isContentPage() ) {
120 # Page is a stub
121 $colour = 'stub';
122 }
123 return $colour;
124 }
125
126 /**
127 * This function returns an HTML link to the given target. It serves a few
128 * purposes:
129 * 1) If $target is a Title, the correct URL to link to will be figured
130 * out automatically.
131 * 2) It automatically adds the usual classes for various types of link
132 * targets: "new" for red links, "stub" for short articles, etc.
133 * 3) It escapes all attribute values safely so there's no risk of XSS.
134 * 4) It provides a default tooltip if the target is a Title (the page
135 * name of the target).
136 * link() replaces the old functions in the makeLink() family.
137 *
138 * @param $target Title Can currently only be a Title, but this may
139 * change to support Images, literal URLs, etc.
140 * @param $html string The HTML contents of the <a> element, i.e.,
141 * the link text. This is raw HTML and will not be escaped. If null,
142 * defaults to the prefixed text of the Title; or if the Title is just a
143 * fragment, the contents of the fragment.
144 * @param $customAttribs array A key => value array of extra HTML attri-
145 * butes, such as title and class. (href is ignored.) Classes will be
146 * merged with the default classes, while other attributes will replace
147 * default attributes. All passed attribute values will be HTML-escaped.
148 * A false attribute value means to suppress that attribute.
149 * @param $query array The query string to append to the URL
150 * you're linking to, in key => value array form. Query keys and values
151 * will be URL-encoded.
152 * @param $options string|array String or array of strings:
153 * 'known': Page is known to exist, so don't check if it does.
154 * 'broken': Page is known not to exist, so don't check if it does.
155 * 'noclasses': Don't add any classes automatically (includes "new",
156 * "stub", "mw-redirect", "extiw"). Only use the class attribute
157 * provided, if any, so you get a simple blue link with no funny i-
158 * cons.
159 * 'forcearticlepath': Use the article path always, even with a querystring.
160 * Has compatibility issues on some setups, so avoid wherever possible.
161 * @return string HTML <a> attribute
162 */
163 public static function link(
164 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
165 ) {
166 wfProfileIn( __METHOD__ );
167 if ( !$target instanceof Title ) {
168 wfProfileOut( __METHOD__ );
169 return "<!-- ERROR -->$html";
170 }
171 $options = (array)$options;
172
173 $dummy = new DummyLinker; // dummy linker instance for bc on the hooks
174
175 $ret = null;
176 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
177 &$customAttribs, &$query, &$options, &$ret ) ) ) {
178 wfProfileOut( __METHOD__ );
179 return $ret;
180 }
181
182 # Normalize the Title if it's a special page
183 $target = self::normaliseSpecialPage( $target );
184
185 # If we don't know whether the page exists, let's find out.
186 wfProfileIn( __METHOD__ . '-checkPageExistence' );
187 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
188 if ( $target->isKnown() ) {
189 $options[] = 'known';
190 } else {
191 $options[] = 'broken';
192 }
193 }
194 wfProfileOut( __METHOD__ . '-checkPageExistence' );
195
196 $oldquery = array();
197 if ( in_array( "forcearticlepath", $options ) && $query ) {
198 $oldquery = $query;
199 $query = array();
200 }
201
202 # Note: we want the href attribute first, for prettiness.
203 $attribs = array( 'href' => self::linkUrl( $target, $query, $options ) );
204 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
205 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
206 }
207
208 $attribs = array_merge(
209 $attribs,
210 self::linkAttribs( $target, $customAttribs, $options )
211 );
212 if ( is_null( $html ) ) {
213 $html = self::linkText( $target );
214 }
215
216 $ret = null;
217 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
218 $ret = Html::rawElement( 'a', $attribs, $html );
219 }
220
221 wfProfileOut( __METHOD__ );
222 return $ret;
223 }
224
225 /**
226 * Identical to link(), except $options defaults to 'known'.
227 */
228 public static function linkKnown(
229 $target, $html = null, $customAttribs = array(),
230 $query = array(), $options = array( 'known', 'noclasses' ) )
231 {
232 return self::link( $target, $html, $customAttribs, $query, $options );
233 }
234
235 /**
236 * Returns the Url used to link to a Title
237 *
238 * @param $target Title
239 */
240 private static function linkUrl( $target, $query, $options ) {
241 wfProfileIn( __METHOD__ );
242 # We don't want to include fragments for broken links, because they
243 # generally make no sense.
244 if ( in_array( 'broken', $options ) && $target->mFragment !== '' ) {
245 $target = clone $target;
246 $target->mFragment = '';
247 }
248
249 # If it's a broken link, add the appropriate query pieces, unless
250 # there's already an action specified, or unless 'edit' makes no sense
251 # (i.e., for a nonexistent special page).
252 if ( in_array( 'broken', $options ) && empty( $query['action'] )
253 && !$target->isSpecialPage() ) {
254 $query['action'] = 'edit';
255 $query['redlink'] = '1';
256 }
257 $ret = $target->getLinkURL( $query );
258 wfProfileOut( __METHOD__ );
259 return $ret;
260 }
261
262 /**
263 * Returns the array of attributes used when linking to the Title $target
264 *
265 * @param $target Title
266 * @param $attribs
267 * @param $options
268 *
269 * @return array
270 */
271 private static function linkAttribs( $target, $attribs, $options ) {
272 wfProfileIn( __METHOD__ );
273 global $wgUser;
274 $defaults = array();
275
276 if ( !in_array( 'noclasses', $options ) ) {
277 wfProfileIn( __METHOD__ . '-getClasses' );
278 # Now build the classes.
279 $classes = array();
280
281 if ( in_array( 'broken', $options ) ) {
282 $classes[] = 'new';
283 }
284
285 if ( $target->isExternal() ) {
286 $classes[] = 'extiw';
287 }
288
289 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
290 $colour = self::getLinkColour( $target, $wgUser->getStubThreshold() );
291 if ( $colour !== '' ) {
292 $classes[] = $colour; # mw-redirect or stub
293 }
294 }
295 if ( $classes != array() ) {
296 $defaults['class'] = implode( ' ', $classes );
297 }
298 wfProfileOut( __METHOD__ . '-getClasses' );
299 }
300
301 # Get a default title attribute.
302 if ( $target->getPrefixedText() == '' ) {
303 # A link like [[#Foo]]. This used to mean an empty title
304 # attribute, but that's silly. Just don't output a title.
305 } elseif ( in_array( 'known', $options ) ) {
306 $defaults['title'] = $target->getPrefixedText();
307 } else {
308 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
309 }
310
311 # Finally, merge the custom attribs with the default ones, and iterate
312 # over that, deleting all "false" attributes.
313 $ret = array();
314 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
315 foreach ( $merged as $key => $val ) {
316 # A false value suppresses the attribute, and we don't want the
317 # href attribute to be overridden.
318 if ( $key != 'href' and $val !== false ) {
319 $ret[$key] = $val;
320 }
321 }
322 wfProfileOut( __METHOD__ );
323 return $ret;
324 }
325
326 /**
327 * Default text of the links to the Title $target
328 *
329 * @param $target Title
330 *
331 * @return string
332 */
333 private static function linkText( $target ) {
334 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
335 if ( !$target instanceof Title ) {
336 return '';
337 }
338
339 # If the target is just a fragment, with no title, we return the frag-
340 # ment text. Otherwise, we return the title text itself.
341 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
342 return htmlspecialchars( $target->getFragment() );
343 }
344 return htmlspecialchars( $target->getPrefixedText() );
345 }
346
347 /**
348 * Generate either a normal exists-style link or a stub link, depending
349 * on the given page size.
350 *
351 * @param $size Integer
352 * @param $nt Title object.
353 * @param $text String
354 * @param $query String
355 * @param $trail String
356 * @param $prefix String
357 * @return string HTML of link
358 * @deprecated since 1.17
359 */
360 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
361 global $wgUser;
362 wfDeprecated( __METHOD__ );
363
364 $threshold = $wgUser->getStubThreshold();
365 $colour = ( $size < $threshold ) ? 'stub' : '';
366 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
367 return self::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
368 }
369
370 /**
371 * Make appropriate markup for a link to the current article. This is currently rendered
372 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
373 * despite $query not being used.
374 *
375 * @param $nt Title
376 *
377 * @return string
378 */
379 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
380 if ( $html == '' ) {
381 $html = htmlspecialchars( $nt->getPrefixedText() );
382 }
383 list( $inside, $trail ) = self::splitTrail( $trail );
384 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
385 }
386
387 /**
388 * @param $title Title
389 * @return Title
390 */
391 static function normaliseSpecialPage( Title $title ) {
392 if ( $title->isSpecialPage() ) {
393 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
394 if ( !$name ) {
395 return $title;
396 }
397 $ret = SpecialPage::getTitleFor( $name, $subpage );
398 $ret->mFragment = $title->getFragment();
399 return $ret;
400 } else {
401 return $title;
402 }
403 }
404
405 /**
406 * Returns the filename part of an url.
407 * Used as alternative text for external images.
408 *
409 * @param $url string
410 *
411 * @return string
412 */
413 private static function fnamePart( $url ) {
414 $basename = strrchr( $url, '/' );
415 if ( false === $basename ) {
416 $basename = $url;
417 } else {
418 $basename = substr( $basename, 1 );
419 }
420 return $basename;
421 }
422
423 /**
424 * Return the code for images which were added via external links,
425 * via Parser::maybeMakeExternalImage().
426 *
427 * @param $url
428 * @param $alt
429 *
430 * @return string
431 */
432 public static function makeExternalImage( $url, $alt = '' ) {
433 if ( $alt == '' ) {
434 $alt = self::fnamePart( $url );
435 }
436 $img = '';
437 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
438 if ( !$success ) {
439 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
440 return $img;
441 }
442 return Html::element( 'img',
443 array(
444 'src' => $url,
445 'alt' => $alt ) );
446 }
447
448 /**
449 * Given parameters derived from [[Image:Foo|options...]], generate the
450 * HTML that that syntax inserts in the page.
451 *
452 * @param $title Title object
453 * @param $file File object, or false if it doesn't exist
454 * @param $frameParams Array: associative array of parameters external to the media handler.
455 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
456 * will often be false.
457 * thumbnail If present, downscale and frame
458 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
459 * framed Shows image in original size in a frame
460 * frameless Downscale but don't frame
461 * upright If present, tweak default sizes for portrait orientation
462 * upright_factor Fudge factor for "upright" tweak (default 0.75)
463 * border If present, show a border around the image
464 * align Horizontal alignment (left, right, center, none)
465 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
466 * bottom, text-bottom)
467 * alt Alternate text for image (i.e. alt attribute). Plain text.
468 * caption HTML for image caption.
469 * link-url URL to link to
470 * link-title Title object to link to
471 * link-target Value for the target attribue, only with link-url
472 * no-link Boolean, suppress description link
473 *
474 * @param $handlerParams Array: associative array of media handler parameters, to be passed
475 * to transform(). Typical keys are "width" and "page".
476 * @param $time String: timestamp of the file, set as false for current
477 * @param $query String: query params for desc url
478 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
479 * @return String: HTML for an image, with links, wrappers, etc.
480 */
481 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
482 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
483 {
484 $res = null;
485 $dummy = new DummyLinker;
486 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
487 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
488 return $res;
489 }
490
491 if ( $file && !$file->allowInlineDisplay() ) {
492 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
493 return self::link( $title );
494 }
495
496 // Shortcuts
497 $fp =& $frameParams;
498 $hp =& $handlerParams;
499
500 // Clean up parameters
501 $page = isset( $hp['page'] ) ? $hp['page'] : false;
502 if ( !isset( $fp['align'] ) ) {
503 $fp['align'] = '';
504 }
505 if ( !isset( $fp['alt'] ) ) {
506 $fp['alt'] = '';
507 }
508 if ( !isset( $fp['title'] ) ) {
509 $fp['title'] = '';
510 }
511
512 $prefix = $postfix = '';
513
514 if ( 'center' == $fp['align'] ) {
515 $prefix = '<div class="center">';
516 $postfix = '</div>';
517 $fp['align'] = 'none';
518 }
519 if ( $file && !isset( $hp['width'] ) ) {
520 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
521 // If its a vector image, and user only specifies height
522 // we don't want it to be limited by its "normal" width.
523 global $wgSVGMaxSize;
524 $hp['width'] = $wgSVGMaxSize;
525 } else {
526 $hp['width'] = $file->getWidth( $page );
527 }
528
529 if ( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) || !$hp['width'] ) {
530 global $wgThumbLimits, $wgThumbUpright;
531 if ( !isset( $widthOption ) || !isset( $wgThumbLimits[$widthOption] ) ) {
532 $widthOption = User::getDefaultOption( 'thumbsize' );
533 }
534
535 // Reduce width for upright images when parameter 'upright' is used
536 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
537 $fp['upright'] = $wgThumbUpright;
538 }
539 // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs
540 $prefWidth = isset( $fp['upright'] ) ?
541 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
542 $wgThumbLimits[$widthOption];
543
544 // Use width which is smaller: real image width or user preference width
545 // Unless image is scalable vector.
546 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
547 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
548 $hp['width'] = $prefWidth;
549 }
550 }
551 }
552
553 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
554 global $wgContLang;
555 # Create a thumbnail. Alignment depends on language
556 # writing direction, # right aligned for left-to-right-
557 # languages ("Western languages"), left-aligned
558 # for right-to-left-languages ("Semitic languages")
559 #
560 # If thumbnail width has not been provided, it is set
561 # to the default user option as specified in Language*.php
562 if ( $fp['align'] == '' ) {
563 $fp['align'] = $wgContLang->alignEnd();
564 }
565 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
566 }
567
568 if ( $file && isset( $fp['frameless'] ) ) {
569 $srcWidth = $file->getWidth( $page );
570 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
571 # This is the same behaviour as the "thumb" option does it already.
572 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
573 $hp['width'] = $srcWidth;
574 }
575 }
576
577 if ( $file && isset( $hp['width'] ) ) {
578 # Create a resized image, without the additional thumbnail features
579 $thumb = $file->transform( $hp );
580 } else {
581 $thumb = false;
582 }
583
584 if ( !$thumb ) {
585 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
586 } else {
587 $params = array(
588 'alt' => $fp['alt'],
589 'title' => $fp['title'],
590 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false ,
591 'img-class' => isset( $fp['border'] ) ? 'thumbborder' : false );
592 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
593
594 $s = $thumb->toHtml( $params );
595 }
596 if ( $fp['align'] != '' ) {
597 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
598 }
599 return str_replace( "\n", ' ', $prefix . $s . $postfix );
600 }
601
602 /**
603 * Get the link parameters for MediaTransformOutput::toHtml() from given
604 * frame parameters supplied by the Parser.
605 * @param $frameParams The frame parameters
606 * @param $query An optional query string to add to description page links
607 */
608 private static function getImageLinkMTOParams( $frameParams, $query = '' ) {
609 $mtoParams = array();
610 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
611 $mtoParams['custom-url-link'] = $frameParams['link-url'];
612 if ( isset( $frameParams['link-target'] ) ) {
613 $mtoParams['custom-target-link'] = $frameParams['link-target'];
614 }
615 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
616 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
617 } elseif ( !empty( $frameParams['no-link'] ) ) {
618 // No link
619 } else {
620 $mtoParams['desc-link'] = true;
621 $mtoParams['desc-query'] = $query;
622 }
623 return $mtoParams;
624 }
625
626 /**
627 * Make HTML for a thumbnail including image, border and caption
628 * @param $title Title object
629 * @param $file File object or false if it doesn't exist
630 * @param $label String
631 * @param $alt String
632 * @param $align String
633 * @param $params Array
634 * @param $framed Boolean
635 * @param $manualthumb String
636 */
637 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
638 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
639 {
640 $frameParams = array(
641 'alt' => $alt,
642 'caption' => $label,
643 'align' => $align
644 );
645 if ( $framed ) {
646 $frameParams['framed'] = true;
647 }
648 if ( $manualthumb ) {
649 $frameParams['manualthumb'] = $manualthumb;
650 }
651 return self::makeThumbLink2( $title, $file, $frameParams, $params );
652 }
653
654 /**
655 * @param $title Title
656 * @param $file File
657 * @param array $frameParams
658 * @param array $handlerParams
659 * @param bool $time
660 * @param string $query
661 * @return mixed
662 */
663 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
664 $handlerParams = array(), $time = false, $query = "" )
665 {
666 global $wgStylePath, $wgContLang;
667 $exists = $file && $file->exists();
668
669 # Shortcuts
670 $fp =& $frameParams;
671 $hp =& $handlerParams;
672
673 $page = isset( $hp['page'] ) ? $hp['page'] : false;
674 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
675 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
676 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
677 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
678
679 if ( empty( $hp['width'] ) ) {
680 // Reduce width for upright images when parameter 'upright' is used
681 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
682 }
683 $thumb = false;
684
685 if ( !$exists ) {
686 $outerWidth = $hp['width'] + 2;
687 } else {
688 if ( isset( $fp['manualthumb'] ) ) {
689 # Use manually specified thumbnail
690 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
691 if ( $manual_title ) {
692 $manual_img = wfFindFile( $manual_title );
693 if ( $manual_img ) {
694 $thumb = $manual_img->getUnscaledThumb( $hp );
695 } else {
696 $exists = false;
697 }
698 }
699 } elseif ( isset( $fp['framed'] ) ) {
700 // Use image dimensions, don't scale
701 $thumb = $file->getUnscaledThumb( $hp );
702 } else {
703 # Do not present an image bigger than the source, for bitmap-style images
704 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
705 $srcWidth = $file->getWidth( $page );
706 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
707 $hp['width'] = $srcWidth;
708 }
709 $thumb = $file->transform( $hp );
710 }
711
712 if ( $thumb ) {
713 $outerWidth = $thumb->getWidth() + 2;
714 } else {
715 $outerWidth = $hp['width'] + 2;
716 }
717 }
718
719 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
720 # So we don't need to pass it here in $query. However, the URL for the
721 # zoom icon still needs it, so we make a unique query for it. See bug 14771
722 $url = $title->getLocalURL( $query );
723 if ( $page ) {
724 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
725 }
726
727 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
728 if ( !$exists ) {
729 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
730 $zoomIcon = '';
731 } elseif ( !$thumb ) {
732 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
733 $zoomIcon = '';
734 } else {
735 $params = array(
736 'alt' => $fp['alt'],
737 'title' => $fp['title'],
738 'img-class' => 'thumbimage' );
739 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
740 $s .= $thumb->toHtml( $params );
741 if ( isset( $fp['framed'] ) ) {
742 $zoomIcon = "";
743 } else {
744 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
745 Html::rawElement( 'a', array(
746 'href' => $url,
747 'class' => 'internal',
748 'title' => wfMsg( 'thumbnail-more' ) ),
749 Html::element( 'img', array(
750 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
751 'width' => 15,
752 'height' => 11,
753 'alt' => "" ) ) ) );
754 }
755 }
756 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
757 return str_replace( "\n", ' ', $s );
758 }
759
760 /**
761 * Make a "broken" link to an image
762 *
763 * @param $title Title object
764 * @param $html String: link label in htmlescaped text form
765 * @param $query String: query string
766 * @param $trail String: link trail (HTML fragment)
767 * @param $prefix String: link prefix (HTML fragment)
768 * @param $time Boolean: a file of a certain timestamp was requested
769 * @return String
770 */
771 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
772 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
773 if ( ! $title instanceof Title ) {
774 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
775 }
776 wfProfileIn( __METHOD__ );
777 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
778
779 list( $inside, $trail ) = self::splitTrail( $trail );
780 if ( $html == '' )
781 $html = htmlspecialchars( $title->getPrefixedText() );
782
783 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
784 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
785
786 if ( $redir ) {
787 wfProfileOut( __METHOD__ );
788 return self::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
789 }
790
791 $href = self::getUploadUrl( $title, $query );
792
793 wfProfileOut( __METHOD__ );
794 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
795 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
796 "$prefix$html$inside</a>$trail";
797 } else {
798 wfProfileOut( __METHOD__ );
799 return self::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
800 }
801 }
802
803 /**
804 * Get the URL to upload a certain file
805 *
806 * @param $destFile Title object of the file to upload
807 * @param $query String: urlencoded query string to prepend
808 * @return String: urlencoded URL
809 */
810 protected static function getUploadUrl( $destFile, $query = '' ) {
811 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
812 $q = 'wpDestFile=' . $destFile->getPartialUrl();
813 if ( $query != '' )
814 $q .= '&' . $query;
815
816 if ( $wgUploadMissingFileUrl ) {
817 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
818 } elseif( $wgUploadNavigationUrl ) {
819 return wfAppendQuery( $wgUploadNavigationUrl, $q );
820 } else {
821 $upload = SpecialPage::getTitleFor( 'Upload' );
822 return $upload->getLocalUrl( $q );
823 }
824 }
825
826 /**
827 * Create a direct link to a given uploaded file.
828 *
829 * @param $title Title object.
830 * @param $html String: pre-sanitized HTML
831 * @param $time string: MW timestamp of file creation time
832 * @return String: HTML
833 */
834 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
835 $img = wfFindFile( $title, array( 'time' => $time ) );
836 return self::makeMediaLinkFile( $title, $img, $html );
837 }
838
839 /**
840 * Create a direct link to a given uploaded file.
841 * This will make a broken link if $file is false.
842 *
843 * @param $title Title object.
844 * @param $file File|false mixed File object or false
845 * @param $html String: pre-sanitized HTML
846 * @return String: HTML
847 *
848 * @todo Handle invalid or missing images better.
849 */
850 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
851 if ( $file && $file->exists() ) {
852 $url = $file->getURL();
853 $class = 'internal';
854 } else {
855 $url = self::getUploadUrl( $title );
856 $class = 'new';
857 }
858 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
859 if ( $html == '' ) {
860 $html = $alt;
861 }
862 $u = htmlspecialchars( $url );
863 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
864 }
865
866 /**
867 * Make a link to a special page given its name and, optionally,
868 * a message key from the link text.
869 * Usage example: Linker::specialLink( 'Recentchanges' )
870 *
871 * @return string
872 */
873 public static function specialLink( $name, $key = '' ) {
874 if ( $key == '' ) {
875 $key = strtolower( $name );
876 }
877
878 return self::linkKnown( SpecialPage::getTitleFor( $name ) , wfMsg( $key ) );
879 }
880
881 /**
882 * Make an external link
883 * @param $url String: URL to link to
884 * @param $text String: text of link
885 * @param $escape Boolean: do we escape the link text?
886 * @param $linktype String: type of external link. Gets added to the classes
887 * @param $attribs Array of extra attributes to <a>
888 */
889 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
890 $class = "external";
891 if ( $linktype ) {
892 $class .= " $linktype";
893 }
894 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
895 $class .= " {$attribs['class']}";
896 }
897 $attribs['class'] = $class;
898
899 if ( $escape ) {
900 $text = htmlspecialchars( $text );
901 }
902 $link = '';
903 $success = wfRunHooks( 'LinkerMakeExternalLink',
904 array( &$url, &$text, &$link, &$attribs, $linktype ) );
905 if ( !$success ) {
906 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
907 return $link;
908 }
909 $attribs['href'] = $url;
910 return Html::rawElement( 'a', $attribs, $text );
911 }
912
913 /**
914 * Make user link (or user contributions for unregistered users)
915 * @param $userId Integer: user id in database.
916 * @param $userText String: user name in database
917 * @return String: HTML fragment
918 */
919 public static function userLink( $userId, $userText ) {
920 if ( $userId == 0 ) {
921 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
922 } else {
923 $page = Title::makeTitle( NS_USER, $userText );
924 }
925 return self::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
926 }
927
928 /**
929 * Generate standard user tool links (talk, contributions, block link, etc.)
930 *
931 * @param $userId Integer: user identifier
932 * @param $userText String: user name or IP address
933 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
934 * red if the user has no edits?
935 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
936 * @param $edits Integer: user edit count (optional, for performance)
937 * @return String: HTML fragment
938 */
939 public static function userToolLinks(
940 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
941 ) {
942 global $wgUser, $wgDisableAnonTalk, $wgLang;
943 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
944 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
945 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
946
947 $items = array();
948 if ( $talkable ) {
949 $items[] = self::userTalkLink( $userId, $userText );
950 }
951 if ( $userId ) {
952 // check if the user has an edit
953 $attribs = array();
954 if ( $redContribsWhenNoEdits ) {
955 $count = !is_null( $edits ) ? $edits : User::edits( $userId );
956 if ( $count == 0 ) {
957 $attribs['class'] = 'new';
958 }
959 }
960 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
961
962 $items[] = self::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
963 }
964 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
965 $items[] = self::blockLink( $userId, $userText );
966 }
967
968 if ( $addEmailLink && $wgUser->canSendEmail() ) {
969 $items[] = self::emailLink( $userId, $userText );
970 }
971
972 if ( $items ) {
973 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
974 } else {
975 return '';
976 }
977 }
978
979 /**
980 * Alias for userToolLinks( $userId, $userText, true );
981 * @param $userId Integer: user identifier
982 * @param $userText String: user name or IP address
983 * @param $edits Integer: user edit count (optional, for performance)
984 */
985 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
986 return self::userToolLinks( $userId, $userText, true, 0, $edits );
987 }
988
989
990 /**
991 * @param $userId Integer: user id in database.
992 * @param $userText String: user name in database.
993 * @return String: HTML fragment with user talk link
994 */
995 public static function userTalkLink( $userId, $userText ) {
996 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
997 $userTalkLink = self::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
998 return $userTalkLink;
999 }
1000
1001 /**
1002 * @param $userId Integer: userid
1003 * @param $userText String: user name in database.
1004 * @return String: HTML fragment with block link
1005 */
1006 public static function blockLink( $userId, $userText ) {
1007 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1008 $blockLink = self::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1009 return $blockLink;
1010 }
1011
1012 /**
1013 * @param $userId Integer: userid
1014 * @param $userText String: user name in database.
1015 * @return String: HTML fragment with e-mail user link
1016 */
1017 public static function emailLink( $userId, $userText ) {
1018 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1019 $emailLink = self::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1020 return $emailLink;
1021 }
1022
1023 /**
1024 * Generate a user link if the current user is allowed to view it
1025 * @param $rev Revision object.
1026 * @param $isPublic Boolean: show only if all users can see it
1027 * @return String: HTML fragment
1028 */
1029 public static function revUserLink( $rev, $isPublic = false ) {
1030 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1031 $link = wfMsgHtml( 'rev-deleted-user' );
1032 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1033 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1034 $rev->getUserText( Revision::FOR_THIS_USER ) );
1035 } else {
1036 $link = wfMsgHtml( 'rev-deleted-user' );
1037 }
1038 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1039 return '<span class="history-deleted">' . $link . '</span>';
1040 }
1041 return $link;
1042 }
1043
1044 /**
1045 * Generate a user tool link cluster if the current user is allowed to view it
1046 * @param $rev Revision object.
1047 * @param $isPublic Boolean: show only if all users can see it
1048 * @return string HTML
1049 */
1050 public static function revUserTools( $rev, $isPublic = false ) {
1051 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1052 $link = wfMsgHtml( 'rev-deleted-user' );
1053 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1054 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1055 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1056 $link = self::userLink( $userId, $userText ) .
1057 ' ' . self::userToolLinks( $userId, $userText );
1058 } else {
1059 $link = wfMsgHtml( 'rev-deleted-user' );
1060 }
1061 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1062 return ' <span class="history-deleted">' . $link . '</span>';
1063 }
1064 return $link;
1065 }
1066
1067 /**
1068 * This function is called by all recent changes variants, by the page history,
1069 * and by the user contributions list. It is responsible for formatting edit
1070 * comments. It escapes any HTML in the comment, but adds some CSS to format
1071 * auto-generated comments (from section editing) and formats [[wikilinks]].
1072 *
1073 * @author Erik Moeller <moeller@scireview.de>
1074 *
1075 * Note: there's not always a title to pass to this function.
1076 * Since you can't set a default parameter for a reference, I've turned it
1077 * temporarily to a value pass. Should be adjusted further. --brion
1078 *
1079 * @param $comment String
1080 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1081 * @param $local Boolean: whether section links should refer to local page
1082 */
1083 public static function formatComment( $comment, $title = null, $local = false ) {
1084 wfProfileIn( __METHOD__ );
1085
1086 # Sanitize text a bit:
1087 $comment = str_replace( "\n", " ", $comment );
1088 # Allow HTML entities (for bug 13815)
1089 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1090
1091 # Render autocomments and make links:
1092 $comment = self::formatAutocomments( $comment, $title, $local );
1093 $comment = self::formatLinksInComment( $comment, $title, $local );
1094
1095 wfProfileOut( __METHOD__ );
1096 return $comment;
1097 }
1098
1099 /**
1100 * @var Title
1101 */
1102 static $autocommentTitle;
1103 static $autocommentLocal;
1104
1105 /**
1106 * The pattern for autogen comments is / * foo * /, which makes for
1107 * some nasty regex.
1108 * We look for all comments, match any text before and after the comment,
1109 * add a separator where needed and format the comment itself with CSS
1110 * Called by Linker::formatComment.
1111 *
1112 * @param $comment String: comment text
1113 * @param $title An optional title object used to links to sections
1114 * @param $local Boolean: whether section links should refer to local page
1115 * @return String: formatted comment
1116 */
1117 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1118 // Bah!
1119 self::$autocommentTitle = $title;
1120 self::$autocommentLocal = $local;
1121 $comment = preg_replace_callback(
1122 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1123 array( 'Linker', 'formatAutocommentsCallback' ),
1124 $comment );
1125 self::$autocommentTitle = null;
1126 self::$autocommentLocal = null;
1127 return $comment;
1128 }
1129
1130 /**
1131 * @param $match
1132 * @return string
1133 */
1134 private static function formatAutocommentsCallback( $match ) {
1135 $title = self::$autocommentTitle;
1136 $local = self::$autocommentLocal;
1137
1138 $pre = $match[1];
1139 $auto = $match[2];
1140 $post = $match[3];
1141 $link = '';
1142 if ( $title ) {
1143 $section = $auto;
1144
1145 # Remove links that a user may have manually put in the autosummary
1146 # This could be improved by copying as much of Parser::stripSectionName as desired.
1147 $section = str_replace( '[[:', '', $section );
1148 $section = str_replace( '[[', '', $section );
1149 $section = str_replace( ']]', '', $section );
1150
1151 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1152 if ( $local ) {
1153 $sectionTitle = Title::newFromText( '#' . $section );
1154 } else {
1155 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1156 $title->getDBkey(), $section );
1157 }
1158 if ( $sectionTitle ) {
1159 $link = self::link( $sectionTitle,
1160 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1161 'noclasses' );
1162 } else {
1163 $link = '';
1164 }
1165 }
1166 $auto = "$link$auto";
1167 if ( $pre ) {
1168 # written summary $presep autocomment (summary /* section */)
1169 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1170 }
1171 if ( $post ) {
1172 # autocomment $postsep written summary (/* section */ summary)
1173 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1174 }
1175 $auto = '<span class="autocomment">' . $auto . '</span>';
1176 $comment = $pre . $auto . $post;
1177 return $comment;
1178 }
1179
1180 /**
1181 * @var Title
1182 */
1183 static $commentContextTitle;
1184 static $commentLocal;
1185
1186 /**
1187 * Formats wiki links and media links in text; all other wiki formatting
1188 * is ignored
1189 *
1190 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1191 * @param $comment String: text to format links in
1192 * @param $title An optional title object used to links to sections
1193 * @param $local Boolean: whether section links should refer to local page
1194 * @return String
1195 */
1196 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1197 self::$commentContextTitle = $title;
1198 self::$commentLocal = $local;
1199 $html = preg_replace_callback(
1200 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1201 array( 'Linker', 'formatLinksInCommentCallback' ),
1202 $comment );
1203 self::$commentContextTitle = null;
1204 self::$commentLocal = null;
1205 return $html;
1206 }
1207
1208 /**
1209 * @param $match
1210 * @return mixed
1211 */
1212 protected static function formatLinksInCommentCallback( $match ) {
1213 global $wgContLang;
1214
1215 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1216 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1217
1218 $comment = $match[0];
1219
1220 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1221 if ( strpos( $match[1], '%' ) !== false ) {
1222 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1223 }
1224
1225 # Handle link renaming [[foo|text]] will show link as "text"
1226 if ( $match[3] != "" ) {
1227 $text = $match[3];
1228 } else {
1229 $text = $match[1];
1230 }
1231 $submatch = array();
1232 $thelink = null;
1233 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1234 # Media link; trail not supported.
1235 $linkRegexp = '/\[\[(.*?)\]\]/';
1236 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1237 if ( $title ) {
1238 $thelink = self::makeMediaLinkObj( $title, $text );
1239 }
1240 } else {
1241 # Other kind of link
1242 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1243 $trail = $submatch[1];
1244 } else {
1245 $trail = "";
1246 }
1247 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1248 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1249 $match[1] = substr( $match[1], 1 );
1250 list( $inside, $trail ) = self::splitTrail( $trail );
1251
1252 $linkText = $text;
1253 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1254 $match[1], $linkText );
1255
1256 $target = Title::newFromText( $linkTarget );
1257 if ( $target ) {
1258 if ( $target->getText() == '' && $target->getInterwiki() === ''
1259 && !self::$commentLocal && self::$commentContextTitle )
1260 {
1261 $newTarget = clone ( self::$commentContextTitle );
1262 $newTarget->setFragment( '#' . $target->getFragment() );
1263 $target = $newTarget;
1264 }
1265 $thelink = self::link(
1266 $target,
1267 $linkText . $inside
1268 ) . $trail;
1269 }
1270 }
1271 if ( $thelink ) {
1272 // If the link is still valid, go ahead and replace it in!
1273 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1274 }
1275
1276 return $comment;
1277 }
1278
1279 /**
1280 * @param $contextTitle Title
1281 * @param $target
1282 * @param $text
1283 * @return string
1284 */
1285 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1286 # Valid link forms:
1287 # Foobar -- normal
1288 # :Foobar -- override special treatment of prefix (images, language links)
1289 # /Foobar -- convert to CurrentPage/Foobar
1290 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1291 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1292 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1293
1294 wfProfileIn( __METHOD__ );
1295 $ret = $target; # default return value is no change
1296
1297 # Some namespaces don't allow subpages,
1298 # so only perform processing if subpages are allowed
1299 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1300 $hash = strpos( $target, '#' );
1301 if ( $hash !== false ) {
1302 $suffix = substr( $target, $hash );
1303 $target = substr( $target, 0, $hash );
1304 } else {
1305 $suffix = '';
1306 }
1307 # bug 7425
1308 $target = trim( $target );
1309 # Look at the first character
1310 if ( $target != '' && $target[0] === '/' ) {
1311 # / at end means we don't want the slash to be shown
1312 $m = array();
1313 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1314 if ( $trailingSlashes ) {
1315 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1316 } else {
1317 $noslash = substr( $target, 1 );
1318 }
1319
1320 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1321 if ( $text === '' ) {
1322 $text = $target . $suffix;
1323 } # this might be changed for ugliness reasons
1324 } else {
1325 # check for .. subpage backlinks
1326 $dotdotcount = 0;
1327 $nodotdot = $target;
1328 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1329 ++$dotdotcount;
1330 $nodotdot = substr( $nodotdot, 3 );
1331 }
1332 if ( $dotdotcount > 0 ) {
1333 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1334 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1335 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1336 # / at the end means don't show full path
1337 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1338 $nodotdot = substr( $nodotdot, 0, -1 );
1339 if ( $text === '' ) {
1340 $text = $nodotdot . $suffix;
1341 }
1342 }
1343 $nodotdot = trim( $nodotdot );
1344 if ( $nodotdot != '' ) {
1345 $ret .= '/' . $nodotdot;
1346 }
1347 $ret .= $suffix;
1348 }
1349 }
1350 }
1351 }
1352
1353 wfProfileOut( __METHOD__ );
1354 return $ret;
1355 }
1356
1357 /**
1358 * Wrap a comment in standard punctuation and formatting if
1359 * it's non-empty, otherwise return empty string.
1360 *
1361 * @param $comment String
1362 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1363 * @param $local Boolean: whether section links should refer to local page
1364 *
1365 * @return string
1366 */
1367 public static function commentBlock( $comment, $title = null, $local = false ) {
1368 // '*' used to be the comment inserted by the software way back
1369 // in antiquity in case none was provided, here for backwards
1370 // compatability, acc. to brion -ævar
1371 if ( $comment == '' || $comment == '*' ) {
1372 return '';
1373 } else {
1374 $formatted = self::formatComment( $comment, $title, $local );
1375 return " <span class=\"comment\" dir=\"auto\">($formatted)</span>";
1376 }
1377 }
1378
1379 /**
1380 * Wrap and format the given revision's comment block, if the current
1381 * user is allowed to view it.
1382 *
1383 * @param $rev Revision object
1384 * @param $local Boolean: whether section links should refer to local page
1385 * @param $isPublic Boolean: show only if all users can see it
1386 * @return String: HTML fragment
1387 */
1388 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1389 if ( $rev->getRawComment() == "" ) {
1390 return "";
1391 }
1392 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1393 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1394 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1395 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1396 $rev->getTitle(), $local );
1397 } else {
1398 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1399 }
1400 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1401 return " <span class=\"history-deleted\">$block</span>";
1402 }
1403 return $block;
1404 }
1405
1406 /**
1407 * @param $size
1408 * @return string
1409 */
1410 public static function formatRevisionSize( $size ) {
1411 if ( $size == 0 ) {
1412 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1413 } else {
1414 global $wgLang;
1415 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1416 $stxt = "($stxt)";
1417 }
1418 $stxt = htmlspecialchars( $stxt );
1419 return "<span class=\"history-size\">$stxt</span>";
1420 }
1421
1422 /**
1423 * Add another level to the Table of Contents
1424 *
1425 * @return string
1426 */
1427 public static function tocIndent() {
1428 return "\n<ul>";
1429 }
1430
1431 /**
1432 * Finish one or more sublevels on the Table of Contents
1433 *
1434 * @return string
1435 */
1436 public static function tocUnindent( $level ) {
1437 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1438 }
1439
1440 /**
1441 * parameter level defines if we are on an indentation level
1442 *
1443 * @return string
1444 */
1445 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1446 $classes = "toclevel-$level";
1447 if ( $sectionIndex !== false ) {
1448 $classes .= " tocsection-$sectionIndex";
1449 }
1450 return "\n<li class=\"$classes\"><a href=\"#" .
1451 $anchor . '"><span class="tocnumber">' .
1452 $tocnumber . '</span> <span class="toctext">' .
1453 $tocline . '</span></a>';
1454 }
1455
1456 /**
1457 * End a Table Of Contents line.
1458 * tocUnindent() will be used instead if we're ending a line below
1459 * the new level.
1460 */
1461 public static function tocLineEnd() {
1462 return "</li>\n";
1463 }
1464
1465 /**
1466 * Wraps the TOC in a table and provides the hide/collapse javascript.
1467 *
1468 * @param $toc String: html of the Table Of Contents
1469 * @param $lang mixed: Language code for the toc title
1470 * @return String: full html of the TOC
1471 */
1472 public static function tocList( $toc, $lang = false ) {
1473 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1474 return
1475 '<table id="toc" class="toc"><tr><td>'
1476 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1477 . $toc
1478 . "</ul>\n</td></tr></table>\n";
1479 }
1480
1481 /**
1482 * Generate a table of contents from a section tree
1483 * Currently unused.
1484 *
1485 * @param $tree Return value of ParserOutput::getSections()
1486 * @return String: HTML fragment
1487 */
1488 public static function generateTOC( $tree ) {
1489 $toc = '';
1490 $lastLevel = 0;
1491 foreach ( $tree as $section ) {
1492 if ( $section['toclevel'] > $lastLevel )
1493 $toc .= self::tocIndent();
1494 elseif ( $section['toclevel'] < $lastLevel )
1495 $toc .= self::tocUnindent(
1496 $lastLevel - $section['toclevel'] );
1497 else
1498 $toc .= self::tocLineEnd();
1499
1500 $toc .= self::tocLine( $section['anchor'],
1501 $section['line'], $section['number'],
1502 $section['toclevel'], $section['index'] );
1503 $lastLevel = $section['toclevel'];
1504 }
1505 $toc .= self::tocLineEnd();
1506 return self::tocList( $toc );
1507 }
1508
1509 /**
1510 * Create a headline for content
1511 *
1512 * @param $level Integer: the level of the headline (1-6)
1513 * @param $attribs String: any attributes for the headline, starting with
1514 * a space and ending with '>'
1515 * This *must* be at least '>' for no attribs
1516 * @param $anchor String: the anchor to give the headline (the bit after the #)
1517 * @param $html String: html for the text of the header
1518 * @param $link String: HTML to add for the section edit link
1519 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1520 * backward compatibility (false to omit)
1521 *
1522 * @return String: HTML headline
1523 */
1524 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1525 $ret = "<h$level$attribs"
1526 . $link
1527 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1528 . "</h$level>";
1529 if ( $legacyAnchor !== false ) {
1530 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1531 }
1532 return $ret;
1533 }
1534
1535 /**
1536 * Split a link trail, return the "inside" portion and the remainder of the trail
1537 * as a two-element array
1538 */
1539 static function splitTrail( $trail ) {
1540 global $wgContLang;
1541 $regex = $wgContLang->linkTrail();
1542 $inside = '';
1543 if ( $trail !== '' ) {
1544 $m = array();
1545 if ( preg_match( $regex, $trail, $m ) ) {
1546 $inside = $m[1];
1547 $trail = $m[2];
1548 }
1549 }
1550 return array( $inside, $trail );
1551 }
1552
1553 /**
1554 * Generate a rollback link for a given revision. Currently it's the
1555 * caller's responsibility to ensure that the revision is the top one. If
1556 * it's not, of course, the user will get an error message.
1557 *
1558 * If the calling page is called with the parameter &bot=1, all rollback
1559 * links also get that parameter. It causes the edit itself and the rollback
1560 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1561 * changes, so this allows sysops to combat a busy vandal without bothering
1562 * other users.
1563 *
1564 * @param $rev Revision object
1565 */
1566 public static function generateRollback( $rev ) {
1567 return '<span class="mw-rollback-link">['
1568 . self::buildRollbackLink( $rev )
1569 . ']</span>';
1570 }
1571
1572 /**
1573 * Build a raw rollback link, useful for collections of "tool" links
1574 *
1575 * @param $rev Revision object
1576 * @return String: HTML fragment
1577 */
1578 public static function buildRollbackLink( $rev ) {
1579 global $wgRequest, $wgUser;
1580 $title = $rev->getTitle();
1581 $query = array(
1582 'action' => 'rollback',
1583 'from' => $rev->getUserText(),
1584 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1585 );
1586 if ( $wgRequest->getBool( 'bot' ) ) {
1587 $query['bot'] = '1';
1588 $query['hidediff'] = '1'; // bug 15999
1589 }
1590 return self::link(
1591 $title,
1592 wfMsgHtml( 'rollbacklink' ),
1593 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1594 $query,
1595 array( 'known', 'noclasses' )
1596 );
1597 }
1598
1599 /**
1600 * Returns HTML for the "templates used on this page" list.
1601 *
1602 * @param $templates Array of templates from Article::getUsedTemplate
1603 * or similar
1604 * @param $preview Boolean: whether this is for a preview
1605 * @param $section Boolean: whether this is for a section edit
1606 * @return String: HTML output
1607 */
1608 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1609 wfProfileIn( __METHOD__ );
1610
1611 $outText = '';
1612 if ( count( $templates ) > 0 ) {
1613 # Do a batch existence check
1614 $batch = new LinkBatch;
1615 foreach ( $templates as $title ) {
1616 $batch->addObj( $title );
1617 }
1618 $batch->execute();
1619
1620 # Construct the HTML
1621 $outText = '<div class="mw-templatesUsedExplanation">';
1622 if ( $preview ) {
1623 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1624 } elseif ( $section ) {
1625 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1626 } else {
1627 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1628 }
1629 $outText .= "</div><ul>\n";
1630
1631 usort( $templates, array( 'Title', 'compare' ) );
1632 foreach ( $templates as $titleObj ) {
1633 $r = $titleObj->getRestrictions( 'edit' );
1634 if ( in_array( 'sysop', $r ) ) {
1635 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1636 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1637 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1638 } else {
1639 $protected = '';
1640 }
1641 if ( $titleObj->quickUserCan( 'edit' ) ) {
1642 $editLink = self::link(
1643 $titleObj,
1644 wfMsg( 'editlink' ),
1645 array(),
1646 array( 'action' => 'edit' )
1647 );
1648 } else {
1649 $editLink = self::link(
1650 $titleObj,
1651 wfMsg( 'viewsourcelink' ),
1652 array(),
1653 array( 'action' => 'edit' )
1654 );
1655 }
1656 $outText .= '<li>' . self::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1657 }
1658 $outText .= '</ul>';
1659 }
1660 wfProfileOut( __METHOD__ );
1661 return $outText;
1662 }
1663
1664 /**
1665 * Returns HTML for the "hidden categories on this page" list.
1666 *
1667 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1668 * or similar
1669 * @return String: HTML output
1670 */
1671 public static function formatHiddenCategories( $hiddencats ) {
1672 global $wgLang;
1673 wfProfileIn( __METHOD__ );
1674
1675 $outText = '';
1676 if ( count( $hiddencats ) > 0 ) {
1677 # Construct the HTML
1678 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1679 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1680 $outText .= "</div><ul>\n";
1681
1682 foreach ( $hiddencats as $titleObj ) {
1683 $outText .= '<li>' . self::link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1684 }
1685 $outText .= '</ul>';
1686 }
1687 wfProfileOut( __METHOD__ );
1688 return $outText;
1689 }
1690
1691 /**
1692 * Format a size in bytes for output, using an appropriate
1693 * unit (B, KB, MB or GB) according to the magnitude in question
1694 *
1695 * @param $size Size to format
1696 * @return String
1697 */
1698 public static function formatSize( $size ) {
1699 global $wgLang;
1700 return htmlspecialchars( $wgLang->formatSize( $size ) );
1701 }
1702
1703 /**
1704 * Given the id of an interface element, constructs the appropriate title
1705 * attribute from the system messages. (Note, this is usually the id but
1706 * isn't always, because sometimes the accesskey needs to go on a different
1707 * element than the id, for reverse-compatibility, etc.)
1708 *
1709 * @param $name String: id of the element, minus prefixes.
1710 * @param $options Mixed: null or the string 'withaccess' to add an access-
1711 * key hint
1712 * @return String: contents of the title attribute (which you must HTML-
1713 * escape), or false for no title attribute
1714 */
1715 public static function titleAttrib( $name, $options = null ) {
1716 global $wgEnableTooltipsAndAccesskeys;
1717 if ( !$wgEnableTooltipsAndAccesskeys )
1718 return false;
1719
1720 wfProfileIn( __METHOD__ );
1721
1722 $message = wfMessage( "tooltip-$name" );
1723
1724 if ( !$message->exists() ) {
1725 $tooltip = false;
1726 } else {
1727 $tooltip = $message->text();
1728 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1729 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1730 # Message equal to '-' means suppress it.
1731 if ( $tooltip == '-' ) {
1732 $tooltip = false;
1733 }
1734 }
1735
1736 if ( $options == 'withaccess' ) {
1737 $accesskey = self::accesskey( $name );
1738 if ( $accesskey !== false ) {
1739 if ( $tooltip === false || $tooltip === '' ) {
1740 $tooltip = "[$accesskey]";
1741 } else {
1742 $tooltip .= " [$accesskey]";
1743 }
1744 }
1745 }
1746
1747 wfProfileOut( __METHOD__ );
1748 return $tooltip;
1749 }
1750
1751 static $accesskeycache;
1752
1753 /**
1754 * Given the id of an interface element, constructs the appropriate
1755 * accesskey attribute from the system messages. (Note, this is usually
1756 * the id but isn't always, because sometimes the accesskey needs to go on
1757 * a different element than the id, for reverse-compatibility, etc.)
1758 *
1759 * @param $name String: id of the element, minus prefixes.
1760 * @return String: contents of the accesskey attribute (which you must HTML-
1761 * escape), or false for no accesskey attribute
1762 */
1763 public static function accesskey( $name ) {
1764 if ( isset( self::$accesskeycache[$name] ) ) {
1765 return self::$accesskeycache[$name];
1766 }
1767 wfProfileIn( __METHOD__ );
1768
1769 $message = wfMessage( "accesskey-$name" );
1770
1771 if ( !$message->exists() ) {
1772 $accesskey = false;
1773 } else {
1774 $accesskey = $message->plain();
1775 if ( $accesskey === '' || $accesskey === '-' ) {
1776 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1777 # attribute, but this is broken for accesskey: that might be a useful
1778 # value.
1779 $accesskey = false;
1780 }
1781 }
1782
1783 wfProfileOut( __METHOD__ );
1784 return self::$accesskeycache[$name] = $accesskey;
1785 }
1786
1787 /**
1788 * Get a revision-deletion link, or disabled link, or nothing, depending
1789 * on user permissions & the settings on the revision.
1790 *
1791 * Will use forward-compatible revision ID in the Special:RevDelete link
1792 * if possible, otherwise the timestamp-based ID which may break after
1793 * undeletion.
1794 *
1795 * @param User $user
1796 * @param Revision $rev
1797 * @param Revision $title
1798 * @return string HTML fragment
1799 */
1800 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
1801 $canHide = $user->isAllowed( 'deleterevision' );
1802 if ( $canHide || ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1803 if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
1804 $revdlink = Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1805 } else {
1806 if ( $rev->getId() ) {
1807 // RevDelete links using revision ID are stable across
1808 // page deletion and undeletion; use when possible.
1809 $query = array(
1810 'type' => 'revision',
1811 'target' => $title->getPrefixedDBkey(),
1812 'ids' => $rev->getId()
1813 );
1814 } else {
1815 // Older deleted entries didn't save a revision ID.
1816 // We have to refer to these by timestamp, ick!
1817 $query = array(
1818 'type' => 'archive',
1819 'target' => $title->getPrefixedDBkey(),
1820 'ids' => $rev->getTimestamp()
1821 );
1822 }
1823 return Linker::revDeleteLink( $query,
1824 $rev->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1825 }
1826 }
1827 return '';
1828 }
1829
1830 /**
1831 * Creates a (show/hide) link for deleting revisions/log entries
1832 *
1833 * @param $query Array: query parameters to be passed to link()
1834 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1835 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1836 *
1837 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1838 * span to allow for customization of appearance with CSS
1839 */
1840 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1841 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1842 $html = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1843 $tag = $restricted ? 'strong' : 'span';
1844 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1845 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1846 }
1847
1848 /**
1849 * Creates a dead (show/hide) link for deleting revisions/log entries
1850 *
1851 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1852 *
1853 * @return string HTML text wrapped in a span to allow for customization
1854 * of appearance with CSS
1855 */
1856 public static function revDeleteLinkDisabled( $delete = true ) {
1857 $html = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1858 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($html)" );
1859 }
1860
1861 /* Deprecated methods */
1862
1863 /**
1864 * @deprecated since 1.16 Use link()
1865 *
1866 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1867 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1868 *
1869 * @param $title String: The text of the title
1870 * @param $text String: Link text
1871 * @param $query String: Optional query part
1872 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1873 * be included in the link text. Other characters will be appended after
1874 * the end of the link.
1875 */
1876 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1877 $nt = Title::newFromText( $title );
1878 if ( $nt instanceof Title ) {
1879 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
1880 } else {
1881 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1882 return $text == '' ? $title : $text;
1883 }
1884 }
1885
1886 /**
1887 * @deprecated since 1.16 Use link()
1888 *
1889 * Make a link for a title which may or may not be in the database. If you need to
1890 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1891 * call to this will result in a DB query.
1892 *
1893 * @param $nt Title: the title object to make the link from, e.g. from
1894 * Title::newFromText.
1895 * @param $text String: link text
1896 * @param $query String: optional query part
1897 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1898 * be included in the link text. Other characters will be appended after
1899 * the end of the link.
1900 * @param $prefix String: optional prefix. As trail, only before instead of after.
1901 */
1902 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1903 wfProfileIn( __METHOD__ );
1904 $query = wfCgiToArray( $query );
1905 list( $inside, $trail ) = self::splitTrail( $trail );
1906 if ( $text === '' ) {
1907 $text = self::linkText( $nt );
1908 }
1909
1910 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1911
1912 wfProfileOut( __METHOD__ );
1913 return $ret;
1914 }
1915
1916 /**
1917 * @deprecated since 1.16 Use link()
1918 *
1919 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1920 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1921 * pages.
1922 *
1923 * @param $title Title object of target page
1924 * @param $text String: text to replace the title
1925 * @param $query String: link target
1926 * @param $trail String: text after link
1927 * @param $prefix String: text before link text
1928 * @param $aprops String: extra attributes to the a-element
1929 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1930 * @return the a-element
1931 */
1932 static function makeKnownLinkObj(
1933 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1934 ) {
1935 wfProfileIn( __METHOD__ );
1936
1937 if ( $text == '' ) {
1938 $text = self::linkText( $title );
1939 }
1940 $attribs = Sanitizer::mergeAttributes(
1941 Sanitizer::decodeTagAttributes( $aprops ),
1942 Sanitizer::decodeTagAttributes( $style )
1943 );
1944 $query = wfCgiToArray( $query );
1945 list( $inside, $trail ) = self::splitTrail( $trail );
1946
1947 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
1948 array( 'known', 'noclasses' ) ) . $trail;
1949
1950 wfProfileOut( __METHOD__ );
1951 return $ret;
1952 }
1953
1954 /**
1955 * @deprecated since 1.16 Use link()
1956 *
1957 * Make a red link to the edit page of a given title.
1958 *
1959 * @param $title Title object of the target page
1960 * @param $text String: Link text
1961 * @param $query String: Optional query part
1962 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1963 * be included in the link text. Other characters will be appended after
1964 * the end of the link.
1965 * @param $prefix String: Optional prefix
1966 */
1967 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1968 wfProfileIn( __METHOD__ );
1969
1970 list( $inside, $trail ) = self::splitTrail( $trail );
1971 if ( $text === '' ) {
1972 $text = self::linkText( $title );
1973 }
1974
1975 $ret = self::link( $title, "$prefix$text$inside", array(),
1976 wfCgiToArray( $query ), 'broken' ) . $trail;
1977
1978 wfProfileOut( __METHOD__ );
1979 return $ret;
1980 }
1981
1982 /**
1983 * @deprecated since 1.16 Use link()
1984 *
1985 * Make a coloured link.
1986 *
1987 * @param $nt Title object of the target page
1988 * @param $colour Integer: colour of the link
1989 * @param $text String: link text
1990 * @param $query String: optional query part
1991 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1992 * be included in the link text. Other characters will be appended after
1993 * the end of the link.
1994 * @param $prefix String: Optional prefix
1995 */
1996 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1997 if ( $colour != '' ) {
1998 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
1999 } else {
2000 $style = '';
2001 }
2002 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2003 }
2004
2005 /**
2006 * Returns the attributes for the tooltip and access key.
2007 */
2008 public static function tooltipAndAccesskeyAttribs( $name ) {
2009 global $wgEnableTooltipsAndAccesskeys;
2010 if ( !$wgEnableTooltipsAndAccesskeys )
2011 return array();
2012 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2013 # no attribute" instead of "output '' as value for attribute", this
2014 # would be three lines.
2015 $attribs = array(
2016 'title' => self::titleAttrib( $name, 'withaccess' ),
2017 'accesskey' => self::accesskey( $name )
2018 );
2019 if ( $attribs['title'] === false ) {
2020 unset( $attribs['title'] );
2021 }
2022 if ( $attribs['accesskey'] === false ) {
2023 unset( $attribs['accesskey'] );
2024 }
2025 return $attribs;
2026 }
2027
2028 /**
2029 * @deprecated since 1.14
2030 * Returns raw bits of HTML, use titleAttrib()
2031 */
2032 public static function tooltip( $name, $options = null ) {
2033 global $wgEnableTooltipsAndAccesskeys;
2034 if ( !$wgEnableTooltipsAndAccesskeys )
2035 return '';
2036 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2037 # no attribute" instead of "output '' as value for attribute", this
2038 # would be two lines.
2039 $tooltip = self::titleAttrib( $name, $options );
2040 if ( $tooltip === false ) {
2041 return '';
2042 }
2043 return Xml::expandAttributes( array(
2044 'title' => $tooltip
2045 ) );
2046 }
2047 }
2048
2049 /**
2050 * @since 1.18
2051 */
2052 class DummyLinker {
2053
2054 /**
2055 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2056 * into static calls to the new Linker for backwards compatibility.
2057 *
2058 * @param $fname String Name of called method
2059 * @param $args Array Arguments to the method
2060 */
2061 public function __call( $fname, $args ) {
2062 return call_user_func_array( array( 'Linker', $fname ), $args );
2063 }
2064 }