Add constant Linker::TOOL_LINKS_EMAIL to allow adding a "send e-mail" link from Linker::
[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 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->getNamespace() != NS_SPECIAL ) {
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 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->getNamespace() == NS_SPECIAL ) {
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 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 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 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 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 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 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: $skin->specialLink( 'recentchanges' )
870 *
871 * @return string
872 */
873 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 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
890 $class = "external";
891 if ( isset($linktype) && $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 * @private
919 */
920 static function userLink( $userId, $userText ) {
921 if ( $userId == 0 ) {
922 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
923 } else {
924 $page = Title::makeTitle( NS_USER, $userText );
925 }
926 return self::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
927 }
928
929 /**
930 * Generate standard user tool links (talk, contributions, block link, etc.)
931 *
932 * @param $userId Integer: user identifier
933 * @param $userText String: user name or IP address
934 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
935 * red if the user has no edits?
936 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
937 * @param $edits Integer: user edit count (optional, for performance)
938 * @return String: HTML fragment
939 */
940 public static function userToolLinks(
941 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
942 ) {
943 global $wgUser, $wgDisableAnonTalk, $wgLang;
944 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
945 $blockable = !$flags & self::TOOL_LINKS_NOBLOCK;
946 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL;
947
948 $items = array();
949 if ( $talkable ) {
950 $items[] = self::userTalkLink( $userId, $userText );
951 }
952 if ( $userId ) {
953 // check if the user has an edit
954 $attribs = array();
955 if ( $redContribsWhenNoEdits ) {
956 $count = !is_null( $edits ) ? $edits : User::edits( $userId );
957 if ( $count == 0 ) {
958 $attribs['class'] = 'new';
959 }
960 }
961 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
962
963 $items[] = self::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
964 }
965 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
966 $items[] = self::blockLink( $userId, $userText );
967 }
968
969 if ( $addEmailLink && $wgUser->canSendEmail() ) {
970 $items[] = self::emailLink( $userId, $userText );
971 }
972
973 if ( $items ) {
974 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
975 } else {
976 return '';
977 }
978 }
979
980 /**
981 * Alias for userToolLinks( $userId, $userText, true );
982 * @param $userId Integer: user identifier
983 * @param $userText String: user name or IP address
984 * @param $edits Integer: user edit count (optional, for performance)
985 */
986 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
987 return self::userToolLinks( $userId, $userText, true, 0, $edits );
988 }
989
990
991 /**
992 * @param $userId Integer: user id in database.
993 * @param $userText String: user name in database.
994 * @return String: HTML fragment with user talk link
995 * @private
996 */
997 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 * @private
1008 */
1009 static function blockLink( $userId, $userText ) {
1010 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1011 $blockLink = self::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1012 return $blockLink;
1013 }
1014
1015 /**
1016 * @param $userId Integer: userid
1017 * @param $userText String: user name in database.
1018 * @return String: HTML fragment with e-mail user link
1019 * @private
1020 */
1021 static function emailLink( $userId, $userText ) {
1022 $emailPage = SpecialPage::getTitleFor( 'EmailUser', $userText );
1023 $emailLink = self::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1024 return $emailLink;
1025 }
1026
1027 /**
1028 * Generate a user link if the current user is allowed to view it
1029 * @param $rev Revision object.
1030 * @param $isPublic Boolean: show only if all users can see it
1031 * @return String: HTML fragment
1032 */
1033 static function revUserLink( $rev, $isPublic = false ) {
1034 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1035 $link = wfMsgHtml( 'rev-deleted-user' );
1036 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1037 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1038 $rev->getUserText( Revision::FOR_THIS_USER ) );
1039 } else {
1040 $link = wfMsgHtml( 'rev-deleted-user' );
1041 }
1042 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1043 return '<span class="history-deleted">' . $link . '</span>';
1044 }
1045 return $link;
1046 }
1047
1048 /**
1049 * Generate a user tool link cluster if the current user is allowed to view it
1050 * @param $rev Revision object.
1051 * @param $isPublic Boolean: show only if all users can see it
1052 * @return string HTML
1053 */
1054 static function revUserTools( $rev, $isPublic = false ) {
1055 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1056 $link = wfMsgHtml( 'rev-deleted-user' );
1057 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1058 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1059 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1060 $link = self::userLink( $userId, $userText ) .
1061 ' ' . self::userToolLinks( $userId, $userText );
1062 } else {
1063 $link = wfMsgHtml( 'rev-deleted-user' );
1064 }
1065 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1066 return ' <span class="history-deleted">' . $link . '</span>';
1067 }
1068 return $link;
1069 }
1070
1071 /**
1072 * This function is called by all recent changes variants, by the page history,
1073 * and by the user contributions list. It is responsible for formatting edit
1074 * comments. It escapes any HTML in the comment, but adds some CSS to format
1075 * auto-generated comments (from section editing) and formats [[wikilinks]].
1076 *
1077 * @author Erik Moeller <moeller@scireview.de>
1078 *
1079 * Note: there's not always a title to pass to this function.
1080 * Since you can't set a default parameter for a reference, I've turned it
1081 * temporarily to a value pass. Should be adjusted further. --brion
1082 *
1083 * @param $comment String
1084 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1085 * @param $local Boolean: whether section links should refer to local page
1086 */
1087 static function formatComment( $comment, $title = null, $local = false ) {
1088 wfProfileIn( __METHOD__ );
1089
1090 # Sanitize text a bit:
1091 $comment = str_replace( "\n", " ", $comment );
1092 # Allow HTML entities (for bug 13815)
1093 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1094
1095 # Render autocomments and make links:
1096 $comment = self::formatAutocomments( $comment, $title, $local );
1097 $comment = self::formatLinksInComment( $comment, $title, $local );
1098
1099 wfProfileOut( __METHOD__ );
1100 return $comment;
1101 }
1102
1103 /**
1104 * @var Title
1105 */
1106 static $autocommentTitle;
1107 static $autocommentLocal;
1108
1109 /**
1110 * The pattern for autogen comments is / * foo * /, which makes for
1111 * some nasty regex.
1112 * We look for all comments, match any text before and after the comment,
1113 * add a separator where needed and format the comment itself with CSS
1114 * Called by Linker::formatComment.
1115 *
1116 * @param $comment String: comment text
1117 * @param $title An optional title object used to links to sections
1118 * @param $local Boolean: whether section links should refer to local page
1119 * @return String: formatted comment
1120 */
1121 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1122 // Bah!
1123 self::$autocommentTitle = $title;
1124 self::$autocommentLocal = $local;
1125 $comment = preg_replace_callback(
1126 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1127 array( 'Linker', 'formatAutocommentsCallback' ),
1128 $comment );
1129 self::$autocommentTitle = null;
1130 self::$autocommentLocal = null;
1131 return $comment;
1132 }
1133
1134 /**
1135 * @param $match
1136 * @return string
1137 */
1138 private static function formatAutocommentsCallback( $match ) {
1139 $title = self::$autocommentTitle;
1140 $local = self::$autocommentLocal;
1141
1142 $pre = $match[1];
1143 $auto = $match[2];
1144 $post = $match[3];
1145 $link = '';
1146 if ( $title ) {
1147 $section = $auto;
1148
1149 # Remove links that a user may have manually put in the autosummary
1150 # This could be improved by copying as much of Parser::stripSectionName as desired.
1151 $section = str_replace( '[[:', '', $section );
1152 $section = str_replace( '[[', '', $section );
1153 $section = str_replace( ']]', '', $section );
1154
1155 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1156 if ( $local ) {
1157 $sectionTitle = Title::newFromText( '#' . $section );
1158 } else {
1159 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1160 $title->getDBkey(), $section );
1161 }
1162 if ( $sectionTitle ) {
1163 $link = self::link( $sectionTitle,
1164 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1165 'noclasses' );
1166 } else {
1167 $link = '';
1168 }
1169 }
1170 $auto = "$link$auto";
1171 if ( $pre ) {
1172 # written summary $presep autocomment (summary /* section */)
1173 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1174 }
1175 if ( $post ) {
1176 # autocomment $postsep written summary (/* section */ summary)
1177 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1178 }
1179 $auto = '<span class="autocomment">' . $auto . '</span>';
1180 $comment = $pre . $auto . $post;
1181 return $comment;
1182 }
1183
1184 /**
1185 * @var Title
1186 */
1187 static $commentContextTitle;
1188 static $commentLocal;
1189
1190 /**
1191 * Formats wiki links and media links in text; all other wiki formatting
1192 * is ignored
1193 *
1194 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1195 * @param $comment String: text to format links in
1196 * @param $title An optional title object used to links to sections
1197 * @param $local Boolean: whether section links should refer to local page
1198 * @return String
1199 */
1200 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1201 self::$commentContextTitle = $title;
1202 self::$commentLocal = $local;
1203 $html = preg_replace_callback(
1204 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1205 array( 'Linker', 'formatLinksInCommentCallback' ),
1206 $comment );
1207 self::$commentContextTitle = null;
1208 self::$commentLocal = null;
1209 return $html;
1210 }
1211
1212 /**
1213 * @param $match
1214 * @return mixed
1215 */
1216 protected static function formatLinksInCommentCallback( $match ) {
1217 global $wgContLang;
1218
1219 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1220 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1221
1222 $comment = $match[0];
1223
1224 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1225 if ( strpos( $match[1], '%' ) !== false ) {
1226 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1227 }
1228
1229 # Handle link renaming [[foo|text]] will show link as "text"
1230 if ( $match[3] != "" ) {
1231 $text = $match[3];
1232 } else {
1233 $text = $match[1];
1234 }
1235 $submatch = array();
1236 $thelink = null;
1237 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1238 # Media link; trail not supported.
1239 $linkRegexp = '/\[\[(.*?)\]\]/';
1240 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1241 $thelink = self::makeMediaLinkObj( $title, $text );
1242 } else {
1243 # Other kind of link
1244 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1245 $trail = $submatch[1];
1246 } else {
1247 $trail = "";
1248 }
1249 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1250 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1251 $match[1] = substr( $match[1], 1 );
1252 list( $inside, $trail ) = self::splitTrail( $trail );
1253
1254 $linkText = $text;
1255 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1256 $match[1], $linkText );
1257
1258 $target = Title::newFromText( $linkTarget );
1259 if ( $target ) {
1260 if ( $target->getText() == '' && $target->getInterwiki() === ''
1261 && !self::$commentLocal && self::$commentContextTitle )
1262 {
1263 $newTarget = clone ( self::$commentContextTitle );
1264 $newTarget->setFragment( '#' . $target->getFragment() );
1265 $target = $newTarget;
1266 }
1267 $thelink = self::link(
1268 $target,
1269 $linkText . $inside
1270 ) . $trail;
1271 }
1272 }
1273 if ( $thelink ) {
1274 // If the link is still valid, go ahead and replace it in!
1275 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1276 }
1277
1278 return $comment;
1279 }
1280
1281 /**
1282 * @param $contextTitle Title
1283 * @param $target
1284 * @param $text
1285 * @return string
1286 */
1287 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1288 # Valid link forms:
1289 # Foobar -- normal
1290 # :Foobar -- override special treatment of prefix (images, language links)
1291 # /Foobar -- convert to CurrentPage/Foobar
1292 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1293 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1294 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1295
1296 wfProfileIn( __METHOD__ );
1297 $ret = $target; # default return value is no change
1298
1299 # Some namespaces don't allow subpages,
1300 # so only perform processing if subpages are allowed
1301 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1302 $hash = strpos( $target, '#' );
1303 if ( $hash !== false ) {
1304 $suffix = substr( $target, $hash );
1305 $target = substr( $target, 0, $hash );
1306 } else {
1307 $suffix = '';
1308 }
1309 # bug 7425
1310 $target = trim( $target );
1311 # Look at the first character
1312 if ( $target != '' && $target { 0 } === '/' ) {
1313 # / at end means we don't want the slash to be shown
1314 $m = array();
1315 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1316 if ( $trailingSlashes ) {
1317 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1318 } else {
1319 $noslash = substr( $target, 1 );
1320 }
1321
1322 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1323 if ( $text === '' ) {
1324 $text = $target . $suffix;
1325 } # this might be changed for ugliness reasons
1326 } else {
1327 # check for .. subpage backlinks
1328 $dotdotcount = 0;
1329 $nodotdot = $target;
1330 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1331 ++$dotdotcount;
1332 $nodotdot = substr( $nodotdot, 3 );
1333 }
1334 if ( $dotdotcount > 0 ) {
1335 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1336 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1337 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1338 # / at the end means don't show full path
1339 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1340 $nodotdot = substr( $nodotdot, 0, -1 );
1341 if ( $text === '' ) {
1342 $text = $nodotdot . $suffix;
1343 }
1344 }
1345 $nodotdot = trim( $nodotdot );
1346 if ( $nodotdot != '' ) {
1347 $ret .= '/' . $nodotdot;
1348 }
1349 $ret .= $suffix;
1350 }
1351 }
1352 }
1353 }
1354
1355 wfProfileOut( __METHOD__ );
1356 return $ret;
1357 }
1358
1359 /**
1360 * Wrap a comment in standard punctuation and formatting if
1361 * it's non-empty, otherwise return empty string.
1362 *
1363 * @param $comment String
1364 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1365 * @param $local Boolean: whether section links should refer to local page
1366 *
1367 * @return string
1368 */
1369 static function commentBlock( $comment, $title = null, $local = false ) {
1370 // '*' used to be the comment inserted by the software way back
1371 // in antiquity in case none was provided, here for backwards
1372 // compatability, acc. to brion -ævar
1373 if ( $comment == '' || $comment == '*' ) {
1374 return '';
1375 } else {
1376 $formatted = self::formatComment( $comment, $title, $local );
1377 return " <span class=\"comment\">($formatted)</span>";
1378 }
1379 }
1380
1381 /**
1382 * Wrap and format the given revision's comment block, if the current
1383 * user is allowed to view it.
1384 *
1385 * @param $rev Revision object
1386 * @param $local Boolean: whether section links should refer to local page
1387 * @param $isPublic Boolean: show only if all users can see it
1388 * @return String: HTML fragment
1389 */
1390 static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1391 if ( $rev->getRawComment() == "" ) {
1392 return "";
1393 }
1394 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1395 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1396 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1397 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1398 $rev->getTitle(), $local );
1399 } else {
1400 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1401 }
1402 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1403 return " <span class=\"history-deleted\">$block</span>";
1404 }
1405 return $block;
1406 }
1407
1408 /**
1409 * @param $size
1410 * @return string
1411 */
1412 public static function formatRevisionSize( $size ) {
1413 if ( $size == 0 ) {
1414 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1415 } else {
1416 global $wgLang;
1417 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1418 $stxt = "($stxt)";
1419 }
1420 $stxt = htmlspecialchars( $stxt );
1421 return "<span class=\"history-size\">$stxt</span>";
1422 }
1423
1424 /**
1425 * Add another level to the Table of Contents
1426 *
1427 * @return string
1428 */
1429 static function tocIndent() {
1430 return "\n<ul>";
1431 }
1432
1433 /**
1434 * Finish one or more sublevels on the Table of Contents
1435 *
1436 * @return string
1437 */
1438 static function tocUnindent( $level ) {
1439 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1440 }
1441
1442 /**
1443 * parameter level defines if we are on an indentation level
1444 *
1445 * @return string
1446 */
1447 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1448 $classes = "toclevel-$level";
1449 if ( $sectionIndex !== false ) {
1450 $classes .= " tocsection-$sectionIndex";
1451 }
1452 return "\n<li class=\"$classes\"><a href=\"#" .
1453 $anchor . '"><span class="tocnumber">' .
1454 $tocnumber . '</span> <span class="toctext">' .
1455 $tocline . '</span></a>';
1456 }
1457
1458 /**
1459 * End a Table Of Contents line.
1460 * tocUnindent() will be used instead if we're ending a line below
1461 * the new level.
1462 */
1463 static function tocLineEnd() {
1464 return "</li>\n";
1465 }
1466
1467 /**
1468 * Wraps the TOC in a table and provides the hide/collapse javascript.
1469 *
1470 * @param $toc String: html of the Table Of Contents
1471 * @param $lang mixed: Language code for the toc title
1472 * @return String: full html of the TOC
1473 */
1474 static function tocList( $toc, $lang = false ) {
1475 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1476 return
1477 '<table id="toc" class="toc"><tr><td>'
1478 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1479 . $toc
1480 . "</ul>\n</td></tr></table>\n";
1481 }
1482
1483 /**
1484 * Generate a table of contents from a section tree
1485 * Currently unused.
1486 *
1487 * @param $tree Return value of ParserOutput::getSections()
1488 * @return String: HTML fragment
1489 */
1490 public static function generateTOC( $tree ) {
1491 $toc = '';
1492 $lastLevel = 0;
1493 foreach ( $tree as $section ) {
1494 if ( $section['toclevel'] > $lastLevel )
1495 $toc .= self::tocIndent();
1496 elseif ( $section['toclevel'] < $lastLevel )
1497 $toc .= self::tocUnindent(
1498 $lastLevel - $section['toclevel'] );
1499 else
1500 $toc .= self::tocLineEnd();
1501
1502 $toc .= self::tocLine( $section['anchor'],
1503 $section['line'], $section['number'],
1504 $section['toclevel'], $section['index'] );
1505 $lastLevel = $section['toclevel'];
1506 }
1507 $toc .= self::tocLineEnd();
1508 return self::tocList( $toc );
1509 }
1510
1511 /**
1512 * Create a headline for content
1513 *
1514 * @param $level Integer: the level of the headline (1-6)
1515 * @param $attribs String: any attributes for the headline, starting with
1516 * a space and ending with '>'
1517 * This *must* be at least '>' for no attribs
1518 * @param $anchor String: the anchor to give the headline (the bit after the #)
1519 * @param $html String: html for the text of the header
1520 * @param $link String: HTML to add for the section edit link
1521 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1522 * backward compatibility (false to omit)
1523 *
1524 * @return String: HTML headline
1525 */
1526 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1527 $ret = "<h$level$attribs"
1528 . $link
1529 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1530 . "</h$level>";
1531 if ( $legacyAnchor !== false ) {
1532 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1533 }
1534 return $ret;
1535 }
1536
1537 /**
1538 * Split a link trail, return the "inside" portion and the remainder of the trail
1539 * as a two-element array
1540 */
1541 static function splitTrail( $trail ) {
1542 global $wgContLang;
1543 $regex = $wgContLang->linkTrail();
1544 $inside = '';
1545 if ( $trail !== '' ) {
1546 $m = array();
1547 if ( preg_match( $regex, $trail, $m ) ) {
1548 $inside = $m[1];
1549 $trail = $m[2];
1550 }
1551 }
1552 return array( $inside, $trail );
1553 }
1554
1555 /**
1556 * Generate a rollback link for a given revision. Currently it's the
1557 * caller's responsibility to ensure that the revision is the top one. If
1558 * it's not, of course, the user will get an error message.
1559 *
1560 * If the calling page is called with the parameter &bot=1, all rollback
1561 * links also get that parameter. It causes the edit itself and the rollback
1562 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1563 * changes, so this allows sysops to combat a busy vandal without bothering
1564 * other users.
1565 *
1566 * @param $rev Revision object
1567 */
1568 static function generateRollback( $rev ) {
1569 return '<span class="mw-rollback-link">['
1570 . self::buildRollbackLink( $rev )
1571 . ']</span>';
1572 }
1573
1574 /**
1575 * Build a raw rollback link, useful for collections of "tool" links
1576 *
1577 * @param $rev Revision object
1578 * @return String: HTML fragment
1579 */
1580 public static function buildRollbackLink( $rev ) {
1581 global $wgRequest, $wgUser;
1582 $title = $rev->getTitle();
1583 $query = array(
1584 'action' => 'rollback',
1585 'from' => $rev->getUserText(),
1586 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1587 );
1588 if ( $wgRequest->getBool( 'bot' ) ) {
1589 $query['bot'] = '1';
1590 $query['hidediff'] = '1'; // bug 15999
1591 }
1592 return self::link(
1593 $title,
1594 wfMsgHtml( 'rollbacklink' ),
1595 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1596 $query,
1597 array( 'known', 'noclasses' )
1598 );
1599 }
1600
1601 /**
1602 * Returns HTML for the "templates used on this page" list.
1603 *
1604 * @param $templates Array of templates from Article::getUsedTemplate
1605 * or similar
1606 * @param $preview Boolean: whether this is for a preview
1607 * @param $section Boolean: whether this is for a section edit
1608 * @return String: HTML output
1609 */
1610 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1611 wfProfileIn( __METHOD__ );
1612
1613 $outText = '';
1614 if ( count( $templates ) > 0 ) {
1615 # Do a batch existence check
1616 $batch = new LinkBatch;
1617 foreach ( $templates as $title ) {
1618 $batch->addObj( $title );
1619 }
1620 $batch->execute();
1621
1622 # Construct the HTML
1623 $outText = '<div class="mw-templatesUsedExplanation">';
1624 if ( $preview ) {
1625 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1626 } elseif ( $section ) {
1627 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1628 } else {
1629 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1630 }
1631 $outText .= "</div><ul>\n";
1632
1633 usort( $templates, array( 'Title', 'compare' ) );
1634 foreach ( $templates as $titleObj ) {
1635 $r = $titleObj->getRestrictions( 'edit' );
1636 if ( in_array( 'sysop', $r ) ) {
1637 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1638 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1639 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1640 } else {
1641 $protected = '';
1642 }
1643 if ( $titleObj->quickUserCan( 'edit' ) ) {
1644 $editLink = self::link(
1645 $titleObj,
1646 wfMsg( 'editlink' ),
1647 array(),
1648 array( 'action' => 'edit' )
1649 );
1650 } else {
1651 $editLink = self::link(
1652 $titleObj,
1653 wfMsg( 'viewsourcelink' ),
1654 array(),
1655 array( 'action' => 'edit' )
1656 );
1657 }
1658 $outText .= '<li>' . self::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1659 }
1660 $outText .= '</ul>';
1661 }
1662 wfProfileOut( __METHOD__ );
1663 return $outText;
1664 }
1665
1666 /**
1667 * Returns HTML for the "templates used on this page" list.
1668 *
1669 * @param $templates Array of templates from Article::getUsedTemplate
1670 * or similar
1671 * @param $preview Boolean: whether this is for a preview
1672 * @param $section Boolean: whether this is for a section edit
1673 * @return String: HTML output
1674 */
1675 public static function formatDistantTemplates( $templates, $preview = false, $section = false ) {
1676 wfProfileIn( __METHOD__ );
1677
1678 $outText = '';
1679 if ( count( $templates ) > 0 ) {
1680
1681 # Construct the HTML
1682 $outText = '<div class="mw-templatesUsedExplanation">';
1683 if ( $preview ) {
1684 $outText .= wfMsgExt( 'distanttemplatesusedpreview', array( 'parse' ), count( $templates ) );
1685 } elseif ( $section ) {
1686 $outText .= wfMsgExt( 'distanttemplatesusedsection', array( 'parse' ), count( $templates ) );
1687 } else {
1688 $outText .= wfMsgExt( 'distanttemplatesused', array( 'parse' ), count( $templates ) );
1689 }
1690 $outText .= "</div><ul>\n";
1691
1692 usort( $templates, array( 'Title', 'compare' ) );
1693 foreach ( $templates as $titleObj ) {
1694 $outText .= '<li>' . self::link( $titleObj ) . '</li>';
1695 }
1696 $outText .= '</ul>';
1697 }
1698 wfProfileOut( __METHOD__ );
1699 return $outText;
1700 }
1701
1702 /**
1703 * Returns HTML for the "hidden categories on this page" list.
1704 *
1705 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1706 * or similar
1707 * @return String: HTML output
1708 */
1709 public static function formatHiddenCategories( $hiddencats ) {
1710 global $wgLang;
1711 wfProfileIn( __METHOD__ );
1712
1713 $outText = '';
1714 if ( count( $hiddencats ) > 0 ) {
1715 # Construct the HTML
1716 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1717 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1718 $outText .= "</div><ul>\n";
1719
1720 foreach ( $hiddencats as $titleObj ) {
1721 $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
1722 }
1723 $outText .= '</ul>';
1724 }
1725 wfProfileOut( __METHOD__ );
1726 return $outText;
1727 }
1728
1729 /**
1730 * Format a size in bytes for output, using an appropriate
1731 * unit (B, KB, MB or GB) according to the magnitude in question
1732 *
1733 * @param $size Size to format
1734 * @return String
1735 */
1736 public static function formatSize( $size ) {
1737 global $wgLang;
1738 return htmlspecialchars( $wgLang->formatSize( $size ) );
1739 }
1740
1741 /**
1742 * Given the id of an interface element, constructs the appropriate title
1743 * attribute from the system messages. (Note, this is usually the id but
1744 * isn't always, because sometimes the accesskey needs to go on a different
1745 * element than the id, for reverse-compatibility, etc.)
1746 *
1747 * @param $name String: id of the element, minus prefixes.
1748 * @param $options Mixed: null or the string 'withaccess' to add an access-
1749 * key hint
1750 * @return String: contents of the title attribute (which you must HTML-
1751 * escape), or false for no title attribute
1752 */
1753 public static function titleAttrib( $name, $options = null ) {
1754 global $wgEnableTooltipsAndAccesskeys;
1755 if ( !$wgEnableTooltipsAndAccesskeys )
1756 return false;
1757
1758 wfProfileIn( __METHOD__ );
1759
1760 $message = wfMessage( "tooltip-$name" );
1761
1762 if ( !$message->exists() ) {
1763 $tooltip = false;
1764 } else {
1765 $tooltip = $message->text();
1766 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1767 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1768 # Message equal to '-' means suppress it.
1769 if ( $tooltip == '-' ) {
1770 $tooltip = false;
1771 }
1772 }
1773
1774 if ( $options == 'withaccess' ) {
1775 $accesskey = self::accesskey( $name );
1776 if ( $accesskey !== false ) {
1777 if ( $tooltip === false || $tooltip === '' ) {
1778 $tooltip = "[$accesskey]";
1779 } else {
1780 $tooltip .= " [$accesskey]";
1781 }
1782 }
1783 }
1784
1785 wfProfileOut( __METHOD__ );
1786 return $tooltip;
1787 }
1788
1789 static $accesskeycache;
1790
1791 /**
1792 * Given the id of an interface element, constructs the appropriate
1793 * accesskey attribute from the system messages. (Note, this is usually
1794 * the id but isn't always, because sometimes the accesskey needs to go on
1795 * a different element than the id, for reverse-compatibility, etc.)
1796 *
1797 * @param $name String: id of the element, minus prefixes.
1798 * @return String: contents of the accesskey attribute (which you must HTML-
1799 * escape), or false for no accesskey attribute
1800 */
1801 public static function accesskey( $name ) {
1802 if ( isset( self::$accesskeycache[$name] ) ) {
1803 return self::$accesskeycache[$name];
1804 }
1805 wfProfileIn( __METHOD__ );
1806
1807 $message = wfMessage( "accesskey-$name" );
1808
1809 if ( !$message->exists() ) {
1810 $accesskey = false;
1811 } else {
1812 $accesskey = $message->plain();
1813 if ( $accesskey === '' || $accesskey === '-' ) {
1814 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1815 # attribute, but this is broken for accesskey: that might be a useful
1816 # value.
1817 $accesskey = false;
1818 }
1819 }
1820
1821 wfProfileOut( __METHOD__ );
1822 return self::$accesskeycache[$name] = $accesskey;
1823 }
1824
1825 /**
1826 * Get a revision-deletion link, or disabled link, or nothing, depending
1827 * on user permissions & the settings on the revision.
1828 *
1829 * Will use forward-compatible revision ID in the Special:RevDelete link
1830 * if possible, otherwise the timestamp-based ID which may break after
1831 * undeletion.
1832 *
1833 * @param User $user
1834 * @param Revision $rev
1835 * @param Revision $title
1836 * @return string HTML fragment
1837 */
1838 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
1839 $canHide = $user->isAllowed( 'deleterevision' );
1840 if ( $canHide || ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1841 if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
1842 $revdlink = Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1843 } else {
1844 if ( $rev->getId() ) {
1845 // RevDelete links using revision ID are stable across
1846 // page deletion and undeletion; use when possible.
1847 $query = array(
1848 'type' => 'revision',
1849 'target' => $title->getPrefixedDBkey(),
1850 'ids' => $rev->getId()
1851 );
1852 } else {
1853 // Older deleted entries didn't save a revision ID.
1854 // We have to refer to these by timestamp, ick!
1855 $query = array(
1856 'type' => 'archive',
1857 'target' => $title->getPrefixedDBkey(),
1858 'ids' => $rev->getTimestamp()
1859 );
1860 }
1861 return Linker::revDeleteLink( $query,
1862 $rev->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1863 }
1864 } else {
1865 return '';
1866 }
1867 }
1868
1869 /**
1870 * Creates a (show/hide) link for deleting revisions/log entries
1871 *
1872 * @param $query Array: query parameters to be passed to link()
1873 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1874 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1875 *
1876 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1877 * span to allow for customization of appearance with CSS
1878 */
1879 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1880 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1881 $html = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1882 $tag = $restricted ? 'strong' : 'span';
1883 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1884 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1885 }
1886
1887 /**
1888 * Creates a dead (show/hide) link for deleting revisions/log entries
1889 *
1890 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1891 *
1892 * @return string HTML text wrapped in a span to allow for customization
1893 * of appearance with CSS
1894 */
1895 public static function revDeleteLinkDisabled( $delete = true ) {
1896 $html = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1897 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($html)" );
1898 }
1899
1900 /* Deprecated methods */
1901
1902 /**
1903 * @deprecated since 1.16 Use link()
1904 *
1905 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1906 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1907 *
1908 * @param $title String: The text of the title
1909 * @param $text String: Link text
1910 * @param $query String: Optional query part
1911 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1912 * be included in the link text. Other characters will be appended after
1913 * the end of the link.
1914 */
1915 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1916 $nt = Title::newFromText( $title );
1917 if ( $nt instanceof Title ) {
1918 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
1919 } else {
1920 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1921 return $text == '' ? $title : $text;
1922 }
1923 }
1924
1925 /**
1926 * @deprecated since 1.16 Use link()
1927 *
1928 * Make a link for a title which may or may not be in the database. If you need to
1929 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1930 * call to this will result in a DB query.
1931 *
1932 * @param $nt Title: the title object to make the link from, e.g. from
1933 * Title::newFromText.
1934 * @param $text String: link text
1935 * @param $query String: optional query part
1936 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1937 * be included in the link text. Other characters will be appended after
1938 * the end of the link.
1939 * @param $prefix String: optional prefix. As trail, only before instead of after.
1940 */
1941 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1942 wfProfileIn( __METHOD__ );
1943 $query = wfCgiToArray( $query );
1944 list( $inside, $trail ) = self::splitTrail( $trail );
1945 if ( $text === '' ) {
1946 $text = self::linkText( $nt );
1947 }
1948
1949 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1950
1951 wfProfileOut( __METHOD__ );
1952 return $ret;
1953 }
1954
1955 /**
1956 * @deprecated since 1.16 Use link()
1957 *
1958 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1959 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1960 * pages.
1961 *
1962 * @param $title Title object of target page
1963 * @param $text String: text to replace the title
1964 * @param $query String: link target
1965 * @param $trail String: text after link
1966 * @param $prefix String: text before link text
1967 * @param $aprops String: extra attributes to the a-element
1968 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1969 * @return the a-element
1970 */
1971 static function makeKnownLinkObj(
1972 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1973 ) {
1974 wfProfileIn( __METHOD__ );
1975
1976 if ( $text == '' ) {
1977 $text = self::linkText( $title );
1978 }
1979 $attribs = Sanitizer::mergeAttributes(
1980 Sanitizer::decodeTagAttributes( $aprops ),
1981 Sanitizer::decodeTagAttributes( $style )
1982 );
1983 $query = wfCgiToArray( $query );
1984 list( $inside, $trail ) = self::splitTrail( $trail );
1985
1986 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
1987 array( 'known', 'noclasses' ) ) . $trail;
1988
1989 wfProfileOut( __METHOD__ );
1990 return $ret;
1991 }
1992
1993 /**
1994 * @deprecated since 1.16 Use link()
1995 *
1996 * Make a red link to the edit page of a given title.
1997 *
1998 * @param $title Title object of the target page
1999 * @param $text String: Link text
2000 * @param $query String: Optional query part
2001 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2002 * be included in the link text. Other characters will be appended after
2003 * the end of the link.
2004 * @param $prefix String: Optional prefix
2005 */
2006 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2007 wfProfileIn( __METHOD__ );
2008
2009 list( $inside, $trail ) = self::splitTrail( $trail );
2010 if ( $text === '' ) {
2011 $text = self::linkText( $title );
2012 }
2013
2014 $ret = self::link( $title, "$prefix$text$inside", array(),
2015 wfCgiToArray( $query ), 'broken' ) . $trail;
2016
2017 wfProfileOut( __METHOD__ );
2018 return $ret;
2019 }
2020
2021 /**
2022 * @deprecated since 1.16 Use link()
2023 *
2024 * Make a coloured link.
2025 *
2026 * @param $nt Title object of the target page
2027 * @param $colour Integer: colour of the link
2028 * @param $text String: link text
2029 * @param $query String: optional query part
2030 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2031 * be included in the link text. Other characters will be appended after
2032 * the end of the link.
2033 * @param $prefix String: Optional prefix
2034 */
2035 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2036 if ( $colour != '' ) {
2037 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2038 } else {
2039 $style = '';
2040 }
2041 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2042 }
2043
2044 /**
2045 * Returns the attributes for the tooltip and access key.
2046 */
2047 public static function tooltipAndAccesskeyAttribs( $name ) {
2048 global $wgEnableTooltipsAndAccesskeys;
2049 if ( !$wgEnableTooltipsAndAccesskeys )
2050 return array();
2051 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2052 # no attribute" instead of "output '' as value for attribute", this
2053 # would be three lines.
2054 $attribs = array(
2055 'title' => self::titleAttrib( $name, 'withaccess' ),
2056 'accesskey' => self::accesskey( $name )
2057 );
2058 if ( $attribs['title'] === false ) {
2059 unset( $attribs['title'] );
2060 }
2061 if ( $attribs['accesskey'] === false ) {
2062 unset( $attribs['accesskey'] );
2063 }
2064 return $attribs;
2065 }
2066
2067 /**
2068 * @deprecated since 1.14
2069 * Returns raw bits of HTML, use titleAttrib()
2070 */
2071 public static function tooltip( $name, $options = null ) {
2072 global $wgEnableTooltipsAndAccesskeys;
2073 if ( !$wgEnableTooltipsAndAccesskeys )
2074 return '';
2075 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2076 # no attribute" instead of "output '' as value for attribute", this
2077 # would be two lines.
2078 $tooltip = self::titleAttrib( $name, $options );
2079 if ( $tooltip === false ) {
2080 return '';
2081 }
2082 return Xml::expandAttributes( array(
2083 'title' => $tooltip
2084 ) );
2085 }
2086 }
2087
2088 /**
2089 * @since 1.18
2090 */
2091 class DummyLinker {
2092
2093 /**
2094 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2095 * into static calls to the new Linker for backwards compatibility.
2096 *
2097 * @param $fname String Name of called method
2098 * @param $args Array Arguments to the method
2099 */
2100 public function __call( $fname, $args ) {
2101 return call_user_func_array( array( 'Linker', $fname ), $args );
2102 }
2103 }