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