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