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