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