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