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