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