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