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