merged master
[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 * class HTML for image classes. Plain text.
540 * caption HTML for image caption.
541 * link-url URL to link to
542 * link-title Title object to link to
543 * link-target Value for the target attribue, only with link-url
544 * no-link Boolean, suppress description link
545 *
546 * @param $handlerParams Array: associative array of media handler parameters, to be passed
547 * to transform(). Typical keys are "width" and "page".
548 * @param $time String: timestamp of the file, set as false for current
549 * @param $query String: query params for desc url
550 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
551 * @since 1.20
552 * @return String: HTML for an image, with links, wrappers, etc.
553 */
554 public static function makeImageLink( /*Parser*/ $parser, Title $title, $file, $frameParams = array(),
555 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
556 {
557 $res = null;
558 $dummy = new DummyLinker;
559 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
560 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
561 return $res;
562 }
563
564 if ( $file && !$file->allowInlineDisplay() ) {
565 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
566 return self::link( $title );
567 }
568
569 // Shortcuts
570 $fp =& $frameParams;
571 $hp =& $handlerParams;
572
573 // Clean up parameters
574 $page = isset( $hp['page'] ) ? $hp['page'] : false;
575 if ( !isset( $fp['align'] ) ) {
576 $fp['align'] = '';
577 }
578 if ( !isset( $fp['alt'] ) ) {
579 $fp['alt'] = '';
580 }
581 if ( !isset( $fp['title'] ) ) {
582 $fp['title'] = '';
583 }
584 if ( !isset( $fp['class'] ) ) {
585 $fp['class'] = '';
586 }
587
588 $prefix = $postfix = '';
589
590 if ( 'center' == $fp['align'] ) {
591 $prefix = '<div class="center">';
592 $postfix = '</div>';
593 $fp['align'] = 'none';
594 }
595 if ( $file && !isset( $hp['width'] ) ) {
596 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
597 // If its a vector image, and user only specifies height
598 // we don't want it to be limited by its "normal" width.
599 global $wgSVGMaxSize;
600 $hp['width'] = $wgSVGMaxSize;
601 } else {
602 $hp['width'] = $file->getWidth( $page );
603 }
604
605 if ( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) || !$hp['width'] ) {
606 global $wgThumbLimits, $wgThumbUpright;
607 if ( !isset( $widthOption ) || !isset( $wgThumbLimits[$widthOption] ) ) {
608 $widthOption = User::getDefaultOption( 'thumbsize' );
609 }
610
611 // Reduce width for upright images when parameter 'upright' is used
612 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
613 $fp['upright'] = $wgThumbUpright;
614 }
615 // 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
616 $prefWidth = isset( $fp['upright'] ) ?
617 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
618 $wgThumbLimits[$widthOption];
619
620 // Use width which is smaller: real image width or user preference width
621 // Unless image is scalable vector.
622 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
623 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
624 $hp['width'] = $prefWidth;
625 }
626 }
627 }
628
629 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
630 # Create a thumbnail. Alignment depends on the writing direction of
631 # the page content language (right-aligned for LTR languages,
632 # left-aligned for RTL languages)
633 #
634 # If a thumbnail width has not been provided, it is set
635 # to the default user option as specified in Language*.php
636 if ( $fp['align'] == '' ) {
637 if( $parser instanceof Parser ) {
638 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
639 } else {
640 # backwards compatibility, remove with makeImageLink2()
641 global $wgContLang;
642 $fp['align'] = $wgContLang->alignEnd();
643 }
644 }
645 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
646 }
647
648 if ( $file && isset( $fp['frameless'] ) ) {
649 $srcWidth = $file->getWidth( $page );
650 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
651 # This is the same behaviour as the "thumb" option does it already.
652 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
653 $hp['width'] = $srcWidth;
654 }
655 }
656
657 if ( $file && isset( $hp['width'] ) ) {
658 # Create a resized image, without the additional thumbnail features
659 $thumb = $file->transform( $hp );
660 } else {
661 $thumb = false;
662 }
663
664 if ( !$thumb ) {
665 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
666 } else {
667 $params = array(
668 'alt' => $fp['alt'],
669 'title' => $fp['title'],
670 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
671 'img-class' => $fp['class'] );
672 if ( isset( $fp['border'] ) ) {
673 $params['img-class'] .= ( $params['img-class'] !== '' ) ? ' thumbborder' : 'thumbborder';
674 }
675 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
676
677 $s = $thumb->toHtml( $params );
678 }
679 if ( $fp['align'] != '' ) {
680 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
681 }
682 return str_replace( "\n", ' ', $prefix . $s . $postfix );
683 }
684
685 /**
686 * See makeImageLink()
687 * When this function is removed, remove if( $parser instanceof Parser ) check there too
688 * @deprecated since 1.20
689 */
690 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
691 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
692 return self::makeImageLink( null, $title, $file, $frameParams,
693 $handlerParams, $time, $query, $widthOption );
694 }
695
696 /**
697 * Get the link parameters for MediaTransformOutput::toHtml() from given
698 * frame parameters supplied by the Parser.
699 * @param $frameParams array The frame parameters
700 * @param $query string An optional query string to add to description page links
701 * @return array
702 */
703 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
704 $mtoParams = array();
705 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
706 $mtoParams['custom-url-link'] = $frameParams['link-url'];
707 if ( isset( $frameParams['link-target'] ) ) {
708 $mtoParams['custom-target-link'] = $frameParams['link-target'];
709 }
710 if ( $parser ) {
711 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
712 foreach ( $extLinkAttrs as $name => $val ) {
713 // Currently could include 'rel' and 'target'
714 $mtoParams['parser-extlink-'.$name] = $val;
715 }
716 }
717 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
718 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
719 } elseif ( !empty( $frameParams['no-link'] ) ) {
720 // No link
721 } else {
722 $mtoParams['desc-link'] = true;
723 $mtoParams['desc-query'] = $query;
724 }
725 return $mtoParams;
726 }
727
728 /**
729 * Make HTML for a thumbnail including image, border and caption
730 * @param $title Title object
731 * @param $file File object or false if it doesn't exist
732 * @param $label String
733 * @param $alt String
734 * @param $align String
735 * @param $params Array
736 * @param $framed Boolean
737 * @param $manualthumb String
738 * @return mixed
739 */
740 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
741 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
742 {
743 $frameParams = array(
744 'alt' => $alt,
745 'caption' => $label,
746 'align' => $align
747 );
748 if ( $framed ) {
749 $frameParams['framed'] = true;
750 }
751 if ( $manualthumb ) {
752 $frameParams['manualthumb'] = $manualthumb;
753 }
754 return self::makeThumbLink2( $title, $file, $frameParams, $params );
755 }
756
757 /**
758 * @param $title Title
759 * @param $file File
760 * @param array $frameParams
761 * @param array $handlerParams
762 * @param bool $time
763 * @param string $query
764 * @return mixed
765 */
766 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
767 $handlerParams = array(), $time = false, $query = "" )
768 {
769 global $wgStylePath, $wgContLang;
770 $exists = $file && $file->exists();
771
772 # Shortcuts
773 $fp =& $frameParams;
774 $hp =& $handlerParams;
775
776 $page = isset( $hp['page'] ) ? $hp['page'] : false;
777 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
778 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
779 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
780 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
781
782 if ( empty( $hp['width'] ) ) {
783 // Reduce width for upright images when parameter 'upright' is used
784 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
785 }
786 $thumb = false;
787
788 if ( !$exists ) {
789 $outerWidth = $hp['width'] + 2;
790 } else {
791 if ( isset( $fp['manualthumb'] ) ) {
792 # Use manually specified thumbnail
793 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
794 if ( $manual_title ) {
795 $manual_img = wfFindFile( $manual_title );
796 if ( $manual_img ) {
797 $thumb = $manual_img->getUnscaledThumb( $hp );
798 } else {
799 $exists = false;
800 }
801 }
802 } elseif ( isset( $fp['framed'] ) ) {
803 // Use image dimensions, don't scale
804 $thumb = $file->getUnscaledThumb( $hp );
805 } else {
806 # Do not present an image bigger than the source, for bitmap-style images
807 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
808 $srcWidth = $file->getWidth( $page );
809 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
810 $hp['width'] = $srcWidth;
811 }
812 $thumb = $file->transform( $hp );
813 }
814
815 if ( $thumb ) {
816 $outerWidth = $thumb->getWidth() + 2;
817 } else {
818 $outerWidth = $hp['width'] + 2;
819 }
820 }
821
822 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
823 # So we don't need to pass it here in $query. However, the URL for the
824 # zoom icon still needs it, so we make a unique query for it. See bug 14771
825 $url = $title->getLocalURL( $query );
826 if ( $page ) {
827 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
828 }
829
830 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
831 if ( !$exists ) {
832 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
833 $zoomIcon = '';
834 } elseif ( !$thumb ) {
835 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
836 $zoomIcon = '';
837 } else {
838 $params = array(
839 'alt' => $fp['alt'],
840 'title' => $fp['title'],
841 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== '' ) ? $fp['class'] . ' thumbimage' : 'thumbimage'
842 );
843 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
844 $s .= $thumb->toHtml( $params );
845 if ( isset( $fp['framed'] ) ) {
846 $zoomIcon = "";
847 } else {
848 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
849 Html::rawElement( 'a', array(
850 'href' => $url,
851 'class' => 'internal',
852 'title' => wfMessage( 'thumbnail-more' )->text() ),
853 Html::element( 'img', array(
854 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
855 'width' => 15,
856 'height' => 11,
857 'alt' => "" ) ) ) );
858 }
859 }
860 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
861 return str_replace( "\n", ' ', $s );
862 }
863
864 /**
865 * Make a "broken" link to an image
866 *
867 * @param $title Title object
868 * @param $html String: link label in htmlescaped text form
869 * @param $query String: query string
870 * @param $trail String: link trail (HTML fragment)
871 * @param $prefix String: link prefix (HTML fragment)
872 * @param $time Boolean: a file of a certain timestamp was requested
873 * @return String
874 */
875 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
876 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
877 if ( ! $title instanceof Title ) {
878 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
879 }
880 wfProfileIn( __METHOD__ );
881 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
882
883 list( $inside, $trail ) = self::splitTrail( $trail );
884 if ( $html == '' )
885 $html = htmlspecialchars( $title->getPrefixedText() );
886
887 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
888 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
889
890 if ( $redir ) {
891 wfProfileOut( __METHOD__ );
892 return self::linkKnown( $title, "$prefix$html$inside", array(), wfCgiToArray( $query ) ) . $trail;
893 }
894
895 $href = self::getUploadUrl( $title, $query );
896
897 wfProfileOut( __METHOD__ );
898 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
899 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
900 "$prefix$html$inside</a>$trail";
901 } else {
902 wfProfileOut( __METHOD__ );
903 return self::linkKnown( $title, "$prefix$html$inside", array(), wfCgiToArray( $query ) ) . $trail;
904 }
905 }
906
907 /**
908 * Get the URL to upload a certain file
909 *
910 * @param $destFile Title object of the file to upload
911 * @param $query String: urlencoded query string to prepend
912 * @return String: urlencoded URL
913 */
914 protected static function getUploadUrl( $destFile, $query = '' ) {
915 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
916 $q = 'wpDestFile=' . $destFile->getPartialUrl();
917 if ( $query != '' )
918 $q .= '&' . $query;
919
920 if ( $wgUploadMissingFileUrl ) {
921 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
922 } elseif( $wgUploadNavigationUrl ) {
923 return wfAppendQuery( $wgUploadNavigationUrl, $q );
924 } else {
925 $upload = SpecialPage::getTitleFor( 'Upload' );
926 return $upload->getLocalUrl( $q );
927 }
928 }
929
930 /**
931 * Create a direct link to a given uploaded file.
932 *
933 * @param $title Title object.
934 * @param $html String: pre-sanitized HTML
935 * @param $time string: MW timestamp of file creation time
936 * @return String: HTML
937 */
938 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
939 $img = wfFindFile( $title, array( 'time' => $time ) );
940 return self::makeMediaLinkFile( $title, $img, $html );
941 }
942
943 /**
944 * Create a direct link to a given uploaded file.
945 * This will make a broken link if $file is false.
946 *
947 * @param $title Title object.
948 * @param $file File|bool mixed File object or false
949 * @param $html String: pre-sanitized HTML
950 * @return String: HTML
951 *
952 * @todo Handle invalid or missing images better.
953 */
954 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
955 if ( $file && $file->exists() ) {
956 $url = $file->getURL();
957 $class = 'internal';
958 } else {
959 $url = self::getUploadUrl( $title );
960 $class = 'new';
961 }
962 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
963 if ( $html == '' ) {
964 $html = $alt;
965 }
966 $u = htmlspecialchars( $url );
967 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
968 }
969
970 /**
971 * Make a link to a special page given its name and, optionally,
972 * a message key from the link text.
973 * Usage example: Linker::specialLink( 'Recentchanges' )
974 *
975 * @return string
976 */
977 public static function specialLink( $name, $key = '' ) {
978 if ( $key == '' ) {
979 $key = strtolower( $name );
980 }
981
982 return self::linkKnown( SpecialPage::getTitleFor( $name ) , wfMessage( $key )->text() );
983 }
984
985 /**
986 * Make an external link
987 * @param $url String: URL to link to
988 * @param $text String: text of link
989 * @param $escape Boolean: do we escape the link text?
990 * @param $linktype String: type of external link. Gets added to the classes
991 * @param $attribs Array of extra attributes to <a>
992 * @return string
993 */
994 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
995 $class = "external";
996 if ( $linktype ) {
997 $class .= " $linktype";
998 }
999 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1000 $class .= " {$attribs['class']}";
1001 }
1002 $attribs['class'] = $class;
1003
1004 if ( $escape ) {
1005 $text = htmlspecialchars( $text );
1006 }
1007 $link = '';
1008 $success = wfRunHooks( 'LinkerMakeExternalLink',
1009 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1010 if ( !$success ) {
1011 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1012 return $link;
1013 }
1014 $attribs['href'] = $url;
1015 return Html::rawElement( 'a', $attribs, $text );
1016 }
1017
1018 /**
1019 * Make user link (or user contributions for unregistered users)
1020 * @param $userId Integer: user id in database.
1021 * @param $userName String: user name in database.
1022 * @param $altUserName String: text to display instead of the user name (optional)
1023 * @return String: HTML fragment
1024 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1025 */
1026 public static function userLink( $userId, $userName, $altUserName = false ) {
1027 if ( $userId == 0 ) {
1028 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1029 } else {
1030 $page = Title::makeTitle( NS_USER, $userName );
1031 }
1032
1033 return self::link(
1034 $page,
1035 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1036 array( 'class' => 'mw-userlink' )
1037 );
1038 }
1039
1040 /**
1041 * Generate standard user tool links (talk, contributions, block link, etc.)
1042 *
1043 * @param $userId Integer: user identifier
1044 * @param $userText String: user name or IP address
1045 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1046 * red if the user has no edits?
1047 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1048 * @param $edits Integer: user edit count (optional, for performance)
1049 * @return String: HTML fragment
1050 */
1051 public static function userToolLinks(
1052 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1053 ) {
1054 global $wgUser, $wgDisableAnonTalk, $wgLang;
1055 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1056 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1057 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1058
1059 $items = array();
1060 if ( $talkable ) {
1061 $items[] = self::userTalkLink( $userId, $userText );
1062 }
1063 if ( $userId ) {
1064 // check if the user has an edit
1065 $attribs = array();
1066 if ( $redContribsWhenNoEdits ) {
1067 $count = !is_null( $edits ) ? $edits : User::edits( $userId );
1068 if ( $count == 0 ) {
1069 $attribs['class'] = 'new';
1070 }
1071 }
1072 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1073
1074 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1075 }
1076 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1077 $items[] = self::blockLink( $userId, $userText );
1078 }
1079
1080 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1081 $items[] = self::emailLink( $userId, $userText );
1082 }
1083
1084 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1085
1086 if ( $items ) {
1087 return wfMessage( 'word-separator' )->plain()
1088 . '<span class="mw-usertoollinks">'
1089 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1090 . '</span>';
1091 } else {
1092 return '';
1093 }
1094 }
1095
1096 /**
1097 * Alias for userToolLinks( $userId, $userText, true );
1098 * @param $userId Integer: user identifier
1099 * @param $userText String: user name or IP address
1100 * @param $edits Integer: user edit count (optional, for performance)
1101 * @return String
1102 */
1103 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1104 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1105 }
1106
1107
1108 /**
1109 * @param $userId Integer: user id in database.
1110 * @param $userText String: user name in database.
1111 * @return String: HTML fragment with user talk link
1112 */
1113 public static function userTalkLink( $userId, $userText ) {
1114 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1115 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1116 return $userTalkLink;
1117 }
1118
1119 /**
1120 * @param $userId Integer: userid
1121 * @param $userText String: user name in database.
1122 * @return String: HTML fragment with block link
1123 */
1124 public static function blockLink( $userId, $userText ) {
1125 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1126 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1127 return $blockLink;
1128 }
1129
1130 /**
1131 * @param $userId Integer: userid
1132 * @param $userText String: user name in database.
1133 * @return String: HTML fragment with e-mail user link
1134 */
1135 public static function emailLink( $userId, $userText ) {
1136 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1137 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1138 return $emailLink;
1139 }
1140
1141 /**
1142 * Generate a user link if the current user is allowed to view it
1143 * @param $rev Revision object.
1144 * @param $isPublic Boolean: show only if all users can see it
1145 * @return String: HTML fragment
1146 */
1147 public static function revUserLink( $rev, $isPublic = false ) {
1148 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1149 $link = wfMessage( 'rev-deleted-user' )->escaped();
1150 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1151 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1152 $rev->getUserText( Revision::FOR_THIS_USER ) );
1153 } else {
1154 $link = wfMessage( 'rev-deleted-user' )->escaped();
1155 }
1156 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1157 return '<span class="history-deleted">' . $link . '</span>';
1158 }
1159 return $link;
1160 }
1161
1162 /**
1163 * Generate a user tool link cluster if the current user is allowed to view it
1164 * @param $rev Revision object.
1165 * @param $isPublic Boolean: show only if all users can see it
1166 * @return string HTML
1167 */
1168 public static function revUserTools( $rev, $isPublic = false ) {
1169 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1170 $link = wfMessage( 'rev-deleted-user' )->escaped();
1171 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1172 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1173 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1174 $link = self::userLink( $userId, $userText )
1175 . wfMessage( 'word-separator' )->plain()
1176 . self::userToolLinks( $userId, $userText );
1177 } else {
1178 $link = wfMessage( 'rev-deleted-user' )->escaped();
1179 }
1180 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1181 return ' <span class="history-deleted">' . $link . '</span>';
1182 }
1183 return $link;
1184 }
1185
1186 /**
1187 * This function is called by all recent changes variants, by the page history,
1188 * and by the user contributions list. It is responsible for formatting edit
1189 * comments. It escapes any HTML in the comment, but adds some CSS to format
1190 * auto-generated comments (from section editing) and formats [[wikilinks]].
1191 *
1192 * @author Erik Moeller <moeller@scireview.de>
1193 *
1194 * Note: there's not always a title to pass to this function.
1195 * Since you can't set a default parameter for a reference, I've turned it
1196 * temporarily to a value pass. Should be adjusted further. --brion
1197 *
1198 * @param $comment String
1199 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1200 * @param $local Boolean: whether section links should refer to local page
1201 * @return mixed|String
1202 */
1203 public static function formatComment( $comment, $title = null, $local = false ) {
1204 wfProfileIn( __METHOD__ );
1205
1206 # Sanitize text a bit:
1207 $comment = str_replace( "\n", " ", $comment );
1208 # Allow HTML entities (for bug 13815)
1209 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1210
1211 # Render autocomments and make links:
1212 $comment = self::formatAutocomments( $comment, $title, $local );
1213 $comment = self::formatLinksInComment( $comment, $title, $local );
1214
1215 wfProfileOut( __METHOD__ );
1216 return $comment;
1217 }
1218
1219 /**
1220 * @var Title
1221 */
1222 static $autocommentTitle;
1223 static $autocommentLocal;
1224
1225 /**
1226 * The pattern for autogen comments is / * foo * /, which makes for
1227 * some nasty regex.
1228 * We look for all comments, match any text before and after the comment,
1229 * add a separator where needed and format the comment itself with CSS
1230 * Called by Linker::formatComment.
1231 *
1232 * @param $comment String: comment text
1233 * @param $title Title|null An optional title object used to links to sections
1234 * @param $local Boolean: whether section links should refer to local page
1235 * @return String: formatted comment
1236 */
1237 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1238 // Bah!
1239 self::$autocommentTitle = $title;
1240 self::$autocommentLocal = $local;
1241 $comment = preg_replace_callback(
1242 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1243 array( 'Linker', 'formatAutocommentsCallback' ),
1244 $comment );
1245 self::$autocommentTitle = null;
1246 self::$autocommentLocal = null;
1247 return $comment;
1248 }
1249
1250 /**
1251 * @param $match
1252 * @return string
1253 */
1254 private static function formatAutocommentsCallback( $match ) {
1255 global $wgLang;
1256 $title = self::$autocommentTitle;
1257 $local = self::$autocommentLocal;
1258
1259 $pre = $match[1];
1260 $auto = $match[2];
1261 $post = $match[3];
1262 $comment = null;
1263 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1264 if ( $comment === null ) {
1265 $link = '';
1266 if ( $title ) {
1267 $section = $auto;
1268
1269 # Remove links that a user may have manually put in the autosummary
1270 # This could be improved by copying as much of Parser::stripSectionName as desired.
1271 $section = str_replace( '[[:', '', $section );
1272 $section = str_replace( '[[', '', $section );
1273 $section = str_replace( ']]', '', $section );
1274
1275 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1276 if ( $local ) {
1277 $sectionTitle = Title::newFromText( '#' . $section );
1278 } else {
1279 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1280 $title->getDBkey(), $section );
1281 }
1282 if ( $sectionTitle ) {
1283 $link = self::link( $sectionTitle,
1284 $wgLang->getArrow(), array(), array(),
1285 'noclasses' );
1286 } else {
1287 $link = '';
1288 }
1289 }
1290 if ( $pre ) {
1291 # written summary $presep autocomment (summary /* section */)
1292 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1293 }
1294 if ( $post ) {
1295 # autocomment $postsep written summary (/* section */ summary)
1296 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1297 }
1298 $auto = '<span class="autocomment">' . $auto . '</span>';
1299 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1300 }
1301 return $comment;
1302 }
1303
1304 /**
1305 * @var Title
1306 */
1307 static $commentContextTitle;
1308 static $commentLocal;
1309
1310 /**
1311 * Formats wiki links and media links in text; all other wiki formatting
1312 * is ignored
1313 *
1314 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1315 * @param $comment String: text to format links in
1316 * @param $title Title|null An optional title object used to links to sections
1317 * @param $local Boolean: whether section links should refer to local page
1318 * @return String
1319 */
1320 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1321 self::$commentContextTitle = $title;
1322 self::$commentLocal = $local;
1323 $html = preg_replace_callback(
1324 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1325 array( 'Linker', 'formatLinksInCommentCallback' ),
1326 $comment );
1327 self::$commentContextTitle = null;
1328 self::$commentLocal = null;
1329 return $html;
1330 }
1331
1332 /**
1333 * @param $match
1334 * @return mixed
1335 */
1336 protected static function formatLinksInCommentCallback( $match ) {
1337 global $wgContLang;
1338
1339 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1340 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1341
1342 $comment = $match[0];
1343
1344 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1345 if ( strpos( $match[1], '%' ) !== false ) {
1346 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1347 }
1348
1349 # Handle link renaming [[foo|text]] will show link as "text"
1350 if ( $match[3] != "" ) {
1351 $text = $match[3];
1352 } else {
1353 $text = $match[1];
1354 }
1355 $submatch = array();
1356 $thelink = null;
1357 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1358 # Media link; trail not supported.
1359 $linkRegexp = '/\[\[(.*?)\]\]/';
1360 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1361 if ( $title ) {
1362 $thelink = self::makeMediaLinkObj( $title, $text );
1363 }
1364 } else {
1365 # Other kind of link
1366 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1367 $trail = $submatch[1];
1368 } else {
1369 $trail = "";
1370 }
1371 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1372 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1373 $match[1] = substr( $match[1], 1 );
1374 list( $inside, $trail ) = self::splitTrail( $trail );
1375
1376 $linkText = $text;
1377 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1378 $match[1], $linkText );
1379
1380 $target = Title::newFromText( $linkTarget );
1381 if ( $target ) {
1382 if ( $target->getText() == '' && $target->getInterwiki() === ''
1383 && !self::$commentLocal && self::$commentContextTitle )
1384 {
1385 $newTarget = clone ( self::$commentContextTitle );
1386 $newTarget->setFragment( '#' . $target->getFragment() );
1387 $target = $newTarget;
1388 }
1389 $thelink = self::link(
1390 $target,
1391 $linkText . $inside
1392 ) . $trail;
1393 }
1394 }
1395 if ( $thelink ) {
1396 // If the link is still valid, go ahead and replace it in!
1397 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1398 }
1399
1400 return $comment;
1401 }
1402
1403 /**
1404 * @param $contextTitle Title
1405 * @param $target
1406 * @param $text
1407 * @return string
1408 */
1409 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1410 # Valid link forms:
1411 # Foobar -- normal
1412 # :Foobar -- override special treatment of prefix (images, language links)
1413 # /Foobar -- convert to CurrentPage/Foobar
1414 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1415 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1416 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1417
1418 wfProfileIn( __METHOD__ );
1419 $ret = $target; # default return value is no change
1420
1421 # Some namespaces don't allow subpages,
1422 # so only perform processing if subpages are allowed
1423 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1424 $hash = strpos( $target, '#' );
1425 if ( $hash !== false ) {
1426 $suffix = substr( $target, $hash );
1427 $target = substr( $target, 0, $hash );
1428 } else {
1429 $suffix = '';
1430 }
1431 # bug 7425
1432 $target = trim( $target );
1433 # Look at the first character
1434 if ( $target != '' && $target[0] === '/' ) {
1435 # / at end means we don't want the slash to be shown
1436 $m = array();
1437 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1438 if ( $trailingSlashes ) {
1439 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1440 } else {
1441 $noslash = substr( $target, 1 );
1442 }
1443
1444 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1445 if ( $text === '' ) {
1446 $text = $target . $suffix;
1447 } # this might be changed for ugliness reasons
1448 } else {
1449 # check for .. subpage backlinks
1450 $dotdotcount = 0;
1451 $nodotdot = $target;
1452 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1453 ++$dotdotcount;
1454 $nodotdot = substr( $nodotdot, 3 );
1455 }
1456 if ( $dotdotcount > 0 ) {
1457 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1458 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1459 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1460 # / at the end means don't show full path
1461 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1462 $nodotdot = substr( $nodotdot, 0, -1 );
1463 if ( $text === '' ) {
1464 $text = $nodotdot . $suffix;
1465 }
1466 }
1467 $nodotdot = trim( $nodotdot );
1468 if ( $nodotdot != '' ) {
1469 $ret .= '/' . $nodotdot;
1470 }
1471 $ret .= $suffix;
1472 }
1473 }
1474 }
1475 }
1476
1477 wfProfileOut( __METHOD__ );
1478 return $ret;
1479 }
1480
1481 /**
1482 * Wrap a comment in standard punctuation and formatting if
1483 * it's non-empty, otherwise return empty string.
1484 *
1485 * @param $comment String
1486 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1487 * @param $local Boolean: whether section links should refer to local page
1488 *
1489 * @return string
1490 */
1491 public static function commentBlock( $comment, $title = null, $local = false ) {
1492 // '*' used to be the comment inserted by the software way back
1493 // in antiquity in case none was provided, here for backwards
1494 // compatability, acc. to brion -ævar
1495 if ( $comment == '' || $comment == '*' ) {
1496 return '';
1497 } else {
1498 $formatted = self::formatComment( $comment, $title, $local );
1499 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1500 return " <span class=\"comment\">$formatted</span>";
1501 }
1502 }
1503
1504 /**
1505 * Wrap and format the given revision's comment block, if the current
1506 * user is allowed to view it.
1507 *
1508 * @param $rev Revision object
1509 * @param $local Boolean: whether section links should refer to local page
1510 * @param $isPublic Boolean: show only if all users can see it
1511 * @return String: HTML fragment
1512 */
1513 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1514 if ( $rev->getRawComment() == "" ) {
1515 return "";
1516 }
1517 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1518 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1519 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1520 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1521 $rev->getTitle(), $local );
1522 } else {
1523 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1524 }
1525 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1526 return " <span class=\"history-deleted\">$block</span>";
1527 }
1528 return $block;
1529 }
1530
1531 /**
1532 * @param $size
1533 * @return string
1534 */
1535 public static function formatRevisionSize( $size ) {
1536 if ( $size == 0 ) {
1537 $stxt = wfMessage( 'historyempty' )->escaped();
1538 } else {
1539 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1540 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1541 }
1542 return "<span class=\"history-size\">$stxt</span>";
1543 }
1544
1545 /**
1546 * Add another level to the Table of Contents
1547 *
1548 * @return string
1549 */
1550 public static function tocIndent() {
1551 return "\n<ul>";
1552 }
1553
1554 /**
1555 * Finish one or more sublevels on the Table of Contents
1556 *
1557 * @return string
1558 */
1559 public static function tocUnindent( $level ) {
1560 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1561 }
1562
1563 /**
1564 * parameter level defines if we are on an indentation level
1565 *
1566 * @return string
1567 */
1568 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1569 $classes = "toclevel-$level";
1570 if ( $sectionIndex !== false ) {
1571 $classes .= " tocsection-$sectionIndex";
1572 }
1573 return "\n<li class=\"$classes\"><a href=\"#" .
1574 $anchor . '"><span class="tocnumber">' .
1575 $tocnumber . '</span> <span class="toctext">' .
1576 $tocline . '</span></a>';
1577 }
1578
1579 /**
1580 * End a Table Of Contents line.
1581 * tocUnindent() will be used instead if we're ending a line below
1582 * the new level.
1583 * @return string
1584 */
1585 public static function tocLineEnd() {
1586 return "</li>\n";
1587 }
1588
1589 /**
1590 * Wraps the TOC in a table and provides the hide/collapse javascript.
1591 *
1592 * @param $toc String: html of the Table Of Contents
1593 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1594 * @return String: full html of the TOC
1595 */
1596 public static function tocList( $toc, $lang = false ) {
1597 $lang = wfGetLangObj( $lang );
1598 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1599
1600 return
1601 '<table id="toc" class="toc"><tr><td>'
1602 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1603 . $toc
1604 . "</ul>\n</td></tr></table>\n";
1605 }
1606
1607 /**
1608 * Generate a table of contents from a section tree
1609 * Currently unused.
1610 *
1611 * @param $tree array Return value of ParserOutput::getSections()
1612 * @return String: HTML fragment
1613 */
1614 public static function generateTOC( $tree ) {
1615 $toc = '';
1616 $lastLevel = 0;
1617 foreach ( $tree as $section ) {
1618 if ( $section['toclevel'] > $lastLevel )
1619 $toc .= self::tocIndent();
1620 elseif ( $section['toclevel'] < $lastLevel )
1621 $toc .= self::tocUnindent(
1622 $lastLevel - $section['toclevel'] );
1623 else
1624 $toc .= self::tocLineEnd();
1625
1626 $toc .= self::tocLine( $section['anchor'],
1627 $section['line'], $section['number'],
1628 $section['toclevel'], $section['index'] );
1629 $lastLevel = $section['toclevel'];
1630 }
1631 $toc .= self::tocLineEnd();
1632 return self::tocList( $toc );
1633 }
1634
1635 /**
1636 * Create a headline for content
1637 *
1638 * @param $level Integer: the level of the headline (1-6)
1639 * @param $attribs String: any attributes for the headline, starting with
1640 * a space and ending with '>'
1641 * This *must* be at least '>' for no attribs
1642 * @param $anchor String: the anchor to give the headline (the bit after the #)
1643 * @param $html String: html for the text of the header
1644 * @param $link String: HTML to add for the section edit link
1645 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1646 * backward compatibility (false to omit)
1647 *
1648 * @return String: HTML headline
1649 */
1650 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1651 $ret = "<h$level$attribs"
1652 . $link
1653 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1654 . "</h$level>";
1655 if ( $legacyAnchor !== false ) {
1656 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1657 }
1658 return $ret;
1659 }
1660
1661 /**
1662 * Split a link trail, return the "inside" portion and the remainder of the trail
1663 * as a two-element array
1664 * @return array
1665 */
1666 static function splitTrail( $trail ) {
1667 global $wgContLang;
1668 $regex = $wgContLang->linkTrail();
1669 $inside = '';
1670 if ( $trail !== '' ) {
1671 $m = array();
1672 if ( preg_match( $regex, $trail, $m ) ) {
1673 $inside = $m[1];
1674 $trail = $m[2];
1675 }
1676 }
1677 return array( $inside, $trail );
1678 }
1679
1680 /**
1681 * Generate a rollback link for a given revision. Currently it's the
1682 * caller's responsibility to ensure that the revision is the top one. If
1683 * it's not, of course, the user will get an error message.
1684 *
1685 * If the calling page is called with the parameter &bot=1, all rollback
1686 * links also get that parameter. It causes the edit itself and the rollback
1687 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1688 * changes, so this allows sysops to combat a busy vandal without bothering
1689 * other users.
1690 *
1691 * @param $rev Revision object
1692 * @param $context IContextSource context to use or null for the main context.
1693 * @return string
1694 */
1695 public static function generateRollback( $rev, IContextSource $context = null ) {
1696 if ( $context === null ) {
1697 $context = RequestContext::getMain();
1698 }
1699
1700 return '<span class="mw-rollback-link">'
1701 . $context->msg( 'brackets' )->rawParams(
1702 self::buildRollbackLink( $rev, $context ) )->plain()
1703 . '</span>';
1704 }
1705
1706 /**
1707 * Build a raw rollback link, useful for collections of "tool" links
1708 *
1709 * @param $rev Revision object
1710 * @param $context IContextSource context to use or null for the main context.
1711 * @return String: HTML fragment
1712 */
1713 public static function buildRollbackLink( $rev, IContextSource $context = null ) {
1714 global $wgShowRollbackEditCount, $wgMiserMode;
1715
1716 // To config which pages are effected by miser mode
1717 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1718
1719 if ( $context === null ) {
1720 $context = RequestContext::getMain();
1721 }
1722
1723 $title = $rev->getTitle();
1724 $query = array(
1725 'action' => 'rollback',
1726 'from' => $rev->getUserText(),
1727 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1728 );
1729 if ( $context->getRequest()->getBool( 'bot' ) ) {
1730 $query['bot'] = '1';
1731 $query['hidediff'] = '1'; // bug 15999
1732 }
1733
1734 $disableRollbackEditCount = false;
1735 if( $wgMiserMode ) {
1736 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1737 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1738 $disableRollbackEditCount = true;
1739 break;
1740 }
1741 }
1742 }
1743
1744 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1745 $dbr = wfGetDB( DB_SLAVE );
1746
1747 // Up to the value of $wgShowRollbackEditCount revisions are counted
1748 $res = $dbr->select( 'revision',
1749 array( 'rev_id', 'rev_user_text' ),
1750 // $rev->getPage() returns null sometimes
1751 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1752 __METHOD__,
1753 array( 'USE INDEX' => 'page_timestamp',
1754 'ORDER BY' => 'rev_timestamp DESC',
1755 'LIMIT' => $wgShowRollbackEditCount + 1 )
1756 );
1757
1758 $editCount = 0;
1759 while( $row = $dbr->fetchObject( $res ) ) {
1760 if( $rev->getUserText() != $row->rev_user_text ) {
1761 break;
1762 }
1763 $editCount++;
1764 }
1765
1766 if( $editCount > $wgShowRollbackEditCount ) {
1767 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1768 } else {
1769 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1770 }
1771
1772 return self::link(
1773 $title,
1774 $editCount_output,
1775 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1776 $query,
1777 array( 'known', 'noclasses' )
1778 );
1779 } else {
1780 return self::link(
1781 $title,
1782 $context->msg( 'rollbacklink' )->escaped(),
1783 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1784 $query,
1785 array( 'known', 'noclasses' )
1786 );
1787 }
1788 }
1789
1790 /**
1791 * Returns HTML for the "templates used on this page" list.
1792 *
1793 * @param $templates Array of templates from Article::getUsedTemplate
1794 * or similar
1795 * @param $preview Boolean: whether this is for a preview
1796 * @param $section Boolean: whether this is for a section edit
1797 * @return String: HTML output
1798 */
1799 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1800 wfProfileIn( __METHOD__ );
1801
1802 $outText = '';
1803 if ( count( $templates ) > 0 ) {
1804 # Do a batch existence check
1805 $batch = new LinkBatch;
1806 foreach ( $templates as $title ) {
1807 $batch->addObj( $title );
1808 }
1809 $batch->execute();
1810
1811 # Construct the HTML
1812 $outText = '<div class="mw-templatesUsedExplanation">';
1813 if ( $preview ) {
1814 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1815 ->parseAsBlock();
1816 } elseif ( $section ) {
1817 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1818 ->parseAsBlock();
1819 } else {
1820 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1821 ->parseAsBlock();
1822 }
1823 $outText .= "</div><ul>\n";
1824
1825 usort( $templates, 'Title::compare' );
1826 foreach ( $templates as $titleObj ) {
1827 $r = $titleObj->getRestrictions( 'edit' );
1828 if ( in_array( 'sysop', $r ) ) {
1829 $protected = wfMessage( 'template-protected' )->parse();
1830 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1831 $protected = wfMessage( 'template-semiprotected' )->parse();
1832 } else {
1833 $protected = '';
1834 }
1835 if ( $titleObj->quickUserCan( 'edit' ) ) {
1836 $editLink = self::link(
1837 $titleObj,
1838 wfMessage( 'editlink' )->text(),
1839 array(),
1840 array( 'action' => 'edit' )
1841 );
1842 } else {
1843 $editLink = self::link(
1844 $titleObj,
1845 wfMessage( 'viewsourcelink' )->text(),
1846 array(),
1847 array( 'action' => 'edit' )
1848 );
1849 }
1850 $outText .= '<li>' . self::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1851 }
1852 $outText .= '</ul>';
1853 }
1854 wfProfileOut( __METHOD__ );
1855 return $outText;
1856 }
1857
1858 /**
1859 * Returns HTML for the "hidden categories on this page" list.
1860 *
1861 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1862 * or similar
1863 * @return String: HTML output
1864 */
1865 public static function formatHiddenCategories( $hiddencats ) {
1866 wfProfileIn( __METHOD__ );
1867
1868 $outText = '';
1869 if ( count( $hiddencats ) > 0 ) {
1870 # Construct the HTML
1871 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1872 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1873 $outText .= "</div><ul>\n";
1874
1875 foreach ( $hiddencats as $titleObj ) {
1876 $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
1877 }
1878 $outText .= '</ul>';
1879 }
1880 wfProfileOut( __METHOD__ );
1881 return $outText;
1882 }
1883
1884 /**
1885 * Format a size in bytes for output, using an appropriate
1886 * unit (B, KB, MB or GB) according to the magnitude in question
1887 *
1888 * @param $size int Size to format
1889 * @return String
1890 */
1891 public static function formatSize( $size ) {
1892 global $wgLang;
1893 return htmlspecialchars( $wgLang->formatSize( $size ) );
1894 }
1895
1896 /**
1897 * Given the id of an interface element, constructs the appropriate title
1898 * attribute from the system messages. (Note, this is usually the id but
1899 * isn't always, because sometimes the accesskey needs to go on a different
1900 * element than the id, for reverse-compatibility, etc.)
1901 *
1902 * @param $name String: id of the element, minus prefixes.
1903 * @param $options Mixed: null or the string 'withaccess' to add an access-
1904 * key hint
1905 * @return String: contents of the title attribute (which you must HTML-
1906 * escape), or false for no title attribute
1907 */
1908 public static function titleAttrib( $name, $options = null ) {
1909 wfProfileIn( __METHOD__ );
1910
1911 $message = wfMessage( "tooltip-$name" );
1912
1913 if ( !$message->exists() ) {
1914 $tooltip = false;
1915 } else {
1916 $tooltip = $message->text();
1917 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1918 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1919 # Message equal to '-' means suppress it.
1920 if ( $tooltip == '-' ) {
1921 $tooltip = false;
1922 }
1923 }
1924
1925 if ( $options == 'withaccess' ) {
1926 $accesskey = self::accesskey( $name );
1927 if ( $accesskey !== false ) {
1928 if ( $tooltip === false || $tooltip === '' ) {
1929 $tooltip = "[$accesskey]";
1930 } else {
1931 $tooltip .= " [$accesskey]";
1932 }
1933 }
1934 }
1935
1936 wfProfileOut( __METHOD__ );
1937 return $tooltip;
1938 }
1939
1940 static $accesskeycache;
1941
1942 /**
1943 * Given the id of an interface element, constructs the appropriate
1944 * accesskey attribute from the system messages. (Note, this is usually
1945 * the id but isn't always, because sometimes the accesskey needs to go on
1946 * a different element than the id, for reverse-compatibility, etc.)
1947 *
1948 * @param $name String: id of the element, minus prefixes.
1949 * @return String: contents of the accesskey attribute (which you must HTML-
1950 * escape), or false for no accesskey attribute
1951 */
1952 public static function accesskey( $name ) {
1953 if ( isset( self::$accesskeycache[$name] ) ) {
1954 return self::$accesskeycache[$name];
1955 }
1956 wfProfileIn( __METHOD__ );
1957
1958 $message = wfMessage( "accesskey-$name" );
1959
1960 if ( !$message->exists() ) {
1961 $accesskey = false;
1962 } else {
1963 $accesskey = $message->plain();
1964 if ( $accesskey === '' || $accesskey === '-' ) {
1965 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1966 # attribute, but this is broken for accesskey: that might be a useful
1967 # value.
1968 $accesskey = false;
1969 }
1970 }
1971
1972 wfProfileOut( __METHOD__ );
1973 return self::$accesskeycache[$name] = $accesskey;
1974 }
1975
1976 /**
1977 * Get a revision-deletion link, or disabled link, or nothing, depending
1978 * on user permissions & the settings on the revision.
1979 *
1980 * Will use forward-compatible revision ID in the Special:RevDelete link
1981 * if possible, otherwise the timestamp-based ID which may break after
1982 * undeletion.
1983 *
1984 * @param User $user
1985 * @param Revision $rev
1986 * @param Revision $title
1987 * @return string HTML fragment
1988 */
1989 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
1990 $canHide = $user->isAllowed( 'deleterevision' );
1991 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1992 return '';
1993 }
1994
1995 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
1996 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1997 } else {
1998 if ( $rev->getId() ) {
1999 // RevDelete links using revision ID are stable across
2000 // page deletion and undeletion; use when possible.
2001 $query = array(
2002 'type' => 'revision',
2003 'target' => $title->getPrefixedDBkey(),
2004 'ids' => $rev->getId()
2005 );
2006 } else {
2007 // Older deleted entries didn't save a revision ID.
2008 // We have to refer to these by timestamp, ick!
2009 $query = array(
2010 'type' => 'archive',
2011 'target' => $title->getPrefixedDBkey(),
2012 'ids' => $rev->getTimestamp()
2013 );
2014 }
2015 return Linker::revDeleteLink( $query,
2016 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2017 }
2018 }
2019
2020 /**
2021 * Creates a (show/hide) link for deleting revisions/log entries
2022 *
2023 * @param $query Array: query parameters to be passed to link()
2024 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2025 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2026 *
2027 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2028 * span to allow for customization of appearance with CSS
2029 */
2030 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2031 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2032 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2033 $html = wfMessage( $msgKey )->escaped();
2034 $tag = $restricted ? 'strong' : 'span';
2035 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2036 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2037 }
2038
2039 /**
2040 * Creates a dead (show/hide) link for deleting revisions/log entries
2041 *
2042 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2043 *
2044 * @return string HTML text wrapped in a span to allow for customization
2045 * of appearance with CSS
2046 */
2047 public static function revDeleteLinkDisabled( $delete = true ) {
2048 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2049 $html = wfMessage( $msgKey )->escaped();
2050 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2051 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2052 }
2053
2054 /* Deprecated methods */
2055
2056 /**
2057 * @deprecated since 1.16 Use link()
2058 *
2059 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2060 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2061 *
2062 * @param $title String: The text of the title
2063 * @param $text String: Link text
2064 * @param $query String: Optional query part
2065 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2066 * be included in the link text. Other characters will be appended after
2067 * the end of the link.
2068 * @return string
2069 */
2070 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2071 wfDeprecated( __METHOD__, '1.16' );
2072
2073 $nt = Title::newFromText( $title );
2074 if ( $nt instanceof Title ) {
2075 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2076 } else {
2077 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2078 return $text == '' ? $title : $text;
2079 }
2080 }
2081
2082 /**
2083 * @deprecated since 1.16 Use link()
2084 *
2085 * Make a link for a title which may or may not be in the database. If you need to
2086 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2087 * call to this will result in a DB query.
2088 *
2089 * @param $nt Title: the title object to make the link from, e.g. from
2090 * Title::newFromText.
2091 * @param $text String: link text
2092 * @param $query String: optional query part
2093 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2094 * be included in the link text. Other characters will be appended after
2095 * the end of the link.
2096 * @param $prefix String: optional prefix. As trail, only before instead of after.
2097 * @return string
2098 */
2099 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2100 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2101
2102 wfProfileIn( __METHOD__ );
2103 $query = wfCgiToArray( $query );
2104 list( $inside, $trail ) = self::splitTrail( $trail );
2105 if ( $text === '' ) {
2106 $text = self::linkText( $nt );
2107 }
2108
2109 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2110
2111 wfProfileOut( __METHOD__ );
2112 return $ret;
2113 }
2114
2115 /**
2116 * @deprecated since 1.16 Use link()
2117 *
2118 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2119 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2120 * pages.
2121 *
2122 * @param $title Title object of target page
2123 * @param $text String: text to replace the title
2124 * @param $query String: link target
2125 * @param $trail String: text after link
2126 * @param $prefix String: text before link text
2127 * @param $aprops String: extra attributes to the a-element
2128 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2129 * @return string the a-element
2130 */
2131 static function makeKnownLinkObj(
2132 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
2133 ) {
2134 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2135
2136 wfProfileIn( __METHOD__ );
2137
2138 if ( $text == '' ) {
2139 $text = self::linkText( $title );
2140 }
2141 $attribs = Sanitizer::mergeAttributes(
2142 Sanitizer::decodeTagAttributes( $aprops ),
2143 Sanitizer::decodeTagAttributes( $style )
2144 );
2145 $query = wfCgiToArray( $query );
2146 list( $inside, $trail ) = self::splitTrail( $trail );
2147
2148 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2149 array( 'known', 'noclasses' ) ) . $trail;
2150
2151 wfProfileOut( __METHOD__ );
2152 return $ret;
2153 }
2154
2155 /**
2156 * @deprecated since 1.16 Use link()
2157 *
2158 * Make a red link to the edit page of a given title.
2159 *
2160 * @param $title Title object of the target page
2161 * @param $text String: Link text
2162 * @param $query String: Optional query part
2163 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2164 * be included in the link text. Other characters will be appended after
2165 * the end of the link.
2166 * @param $prefix String: Optional prefix
2167 * @return string
2168 */
2169 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2170 wfDeprecated( __METHOD__, '1.16' );
2171
2172 wfProfileIn( __METHOD__ );
2173
2174 list( $inside, $trail ) = self::splitTrail( $trail );
2175 if ( $text === '' ) {
2176 $text = self::linkText( $title );
2177 }
2178
2179 $ret = self::link( $title, "$prefix$text$inside", array(),
2180 wfCgiToArray( $query ), 'broken' ) . $trail;
2181
2182 wfProfileOut( __METHOD__ );
2183 return $ret;
2184 }
2185
2186 /**
2187 * @deprecated since 1.16 Use link()
2188 *
2189 * Make a coloured link.
2190 *
2191 * @param $nt Title object of the target page
2192 * @param $colour Integer: colour of the link
2193 * @param $text String: link text
2194 * @param $query String: optional query part
2195 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2196 * be included in the link text. Other characters will be appended after
2197 * the end of the link.
2198 * @param $prefix String: Optional prefix
2199 * @return string
2200 */
2201 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2202 wfDeprecated( __METHOD__, '1.16' );
2203
2204 if ( $colour != '' ) {
2205 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2206 } else {
2207 $style = '';
2208 }
2209 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2210 }
2211
2212 /**
2213 * Returns the attributes for the tooltip and access key.
2214 * @return array
2215 */
2216 public static function tooltipAndAccesskeyAttribs( $name ) {
2217 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2218 # no attribute" instead of "output '' as value for attribute", this
2219 # would be three lines.
2220 $attribs = array(
2221 'title' => self::titleAttrib( $name, 'withaccess' ),
2222 'accesskey' => self::accesskey( $name )
2223 );
2224 if ( $attribs['title'] === false ) {
2225 unset( $attribs['title'] );
2226 }
2227 if ( $attribs['accesskey'] === false ) {
2228 unset( $attribs['accesskey'] );
2229 }
2230 return $attribs;
2231 }
2232
2233 /**
2234 * Returns raw bits of HTML, use titleAttrib()
2235 * @return null|string
2236 */
2237 public static function tooltip( $name, $options = null ) {
2238 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2239 # no attribute" instead of "output '' as value for attribute", this
2240 # would be two lines.
2241 $tooltip = self::titleAttrib( $name, $options );
2242 if ( $tooltip === false ) {
2243 return '';
2244 }
2245 return Xml::expandAttributes( array(
2246 'title' => $tooltip
2247 ) );
2248 }
2249 }
2250
2251 /**
2252 * @since 1.18
2253 */
2254 class DummyLinker {
2255
2256 /**
2257 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2258 * into static calls to the new Linker for backwards compatibility.
2259 *
2260 * @param $fname String Name of called method
2261 * @param $args Array Arguments to the method
2262 * @return mixed
2263 */
2264 public function __call( $fname, $args ) {
2265 return call_user_func_array( array( 'Linker', $fname ), $args );
2266 }
2267 }