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