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