a55eee90ad11e1158a0383bd0f28db123393084e
[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 ( !Hooks::run( '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 ( Hooks::run( '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 ( !Hooks::run( '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 = Hooks::run( '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 ( !Hooks::run( '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 ( !Hooks::run( '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 = Hooks::run( '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 Hooks::run( '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 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 . $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 and final / from text
1495 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1496 # ../Foobar -- convert to CurrentPage/Foobar,
1497 # (from CurrentPage/CurrentSubPage)
1498 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1499 # (from CurrentPage/CurrentSubPage)
1500
1501 wfProfileIn( __METHOD__ );
1502 $ret = $target; # default return value is no change
1503
1504 # Some namespaces don't allow subpages,
1505 # so only perform processing if subpages are allowed
1506 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1507 $hash = strpos( $target, '#' );
1508 if ( $hash !== false ) {
1509 $suffix = substr( $target, $hash );
1510 $target = substr( $target, 0, $hash );
1511 } else {
1512 $suffix = '';
1513 }
1514 # bug 7425
1515 $target = trim( $target );
1516 # Look at the first character
1517 if ( $target != '' && $target[0] === '/' ) {
1518 # / at end means we don't want the slash to be shown
1519 $m = array();
1520 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1521 if ( $trailingSlashes ) {
1522 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1523 } else {
1524 $noslash = substr( $target, 1 );
1525 }
1526
1527 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1528 if ( $text === '' ) {
1529 $text = $target . $suffix;
1530 } # this might be changed for ugliness reasons
1531 } else {
1532 # check for .. subpage backlinks
1533 $dotdotcount = 0;
1534 $nodotdot = $target;
1535 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1536 ++$dotdotcount;
1537 $nodotdot = substr( $nodotdot, 3 );
1538 }
1539 if ( $dotdotcount > 0 ) {
1540 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1541 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1542 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1543 # / at the end means don't show full path
1544 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1545 $nodotdot = rtrim( $nodotdot, '/' );
1546 if ( $text === '' ) {
1547 $text = $nodotdot . $suffix;
1548 }
1549 }
1550 $nodotdot = trim( $nodotdot );
1551 if ( $nodotdot != '' ) {
1552 $ret .= '/' . $nodotdot;
1553 }
1554 $ret .= $suffix;
1555 }
1556 }
1557 }
1558 }
1559
1560 wfProfileOut( __METHOD__ );
1561 return $ret;
1562 }
1563
1564 /**
1565 * Wrap a comment in standard punctuation and formatting if
1566 * it's non-empty, otherwise return empty string.
1567 *
1568 * @param string $comment
1569 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1570 * @param bool $local Whether section links should refer to local page
1571 *
1572 * @return string
1573 */
1574 public static function commentBlock( $comment, $title = null, $local = false ) {
1575 // '*' used to be the comment inserted by the software way back
1576 // in antiquity in case none was provided, here for backwards
1577 // compatibility, acc. to brion -ævar
1578 if ( $comment == '' || $comment == '*' ) {
1579 return '';
1580 } else {
1581 $formatted = self::formatComment( $comment, $title, $local );
1582 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1583 return " <span class=\"comment\">$formatted</span>";
1584 }
1585 }
1586
1587 /**
1588 * Wrap and format the given revision's comment block, if the current
1589 * user is allowed to view it.
1590 *
1591 * @param Revision $rev
1592 * @param bool $local Whether section links should refer to local page
1593 * @param bool $isPublic Show only if all users can see it
1594 * @return string HTML fragment
1595 */
1596 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1597 if ( $rev->getRawComment() == "" ) {
1598 return "";
1599 }
1600 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1601 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1602 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1603 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1604 $rev->getTitle(), $local );
1605 } else {
1606 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1607 }
1608 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1609 return " <span class=\"history-deleted\">$block</span>";
1610 }
1611 return $block;
1612 }
1613
1614 /**
1615 * @param int $size
1616 * @return string
1617 */
1618 public static function formatRevisionSize( $size ) {
1619 if ( $size == 0 ) {
1620 $stxt = wfMessage( 'historyempty' )->escaped();
1621 } else {
1622 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1623 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1624 }
1625 return "<span class=\"history-size\">$stxt</span>";
1626 }
1627
1628 /**
1629 * Add another level to the Table of Contents
1630 *
1631 * @return string
1632 */
1633 public static function tocIndent() {
1634 return "\n<ul>";
1635 }
1636
1637 /**
1638 * Finish one or more sublevels on the Table of Contents
1639 *
1640 * @param int $level
1641 * @return string
1642 */
1643 public static function tocUnindent( $level ) {
1644 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1645 }
1646
1647 /**
1648 * parameter level defines if we are on an indentation level
1649 *
1650 * @param string $anchor
1651 * @param string $tocline
1652 * @param string $tocnumber
1653 * @param string $level
1654 * @param string|bool $sectionIndex
1655 * @return string
1656 */
1657 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1658 $classes = "toclevel-$level";
1659 if ( $sectionIndex !== false ) {
1660 $classes .= " tocsection-$sectionIndex";
1661 }
1662 return "\n<li class=\"$classes\"><a href=\"#" .
1663 $anchor . '"><span class="tocnumber">' .
1664 $tocnumber . '</span> <span class="toctext">' .
1665 $tocline . '</span></a>';
1666 }
1667
1668 /**
1669 * End a Table Of Contents line.
1670 * tocUnindent() will be used instead if we're ending a line below
1671 * the new level.
1672 * @return string
1673 */
1674 public static function tocLineEnd() {
1675 return "</li>\n";
1676 }
1677
1678 /**
1679 * Wraps the TOC in a table and provides the hide/collapse javascript.
1680 *
1681 * @param string $toc Html of the Table Of Contents
1682 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1683 * @return string Full html of the TOC
1684 */
1685 public static function tocList( $toc, $lang = false ) {
1686 $lang = wfGetLangObj( $lang );
1687 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1688
1689 return '<div id="toc" class="toc">'
1690 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1691 . $toc
1692 . "</ul>\n</div>\n";
1693 }
1694
1695 /**
1696 * Generate a table of contents from a section tree
1697 * Currently unused.
1698 *
1699 * @param array $tree Return value of ParserOutput::getSections()
1700 * @return string HTML fragment
1701 */
1702 public static function generateTOC( $tree ) {
1703 $toc = '';
1704 $lastLevel = 0;
1705 foreach ( $tree as $section ) {
1706 if ( $section['toclevel'] > $lastLevel ) {
1707 $toc .= self::tocIndent();
1708 } elseif ( $section['toclevel'] < $lastLevel ) {
1709 $toc .= self::tocUnindent(
1710 $lastLevel - $section['toclevel'] );
1711 } else {
1712 $toc .= self::tocLineEnd();
1713 }
1714
1715 $toc .= self::tocLine( $section['anchor'],
1716 $section['line'], $section['number'],
1717 $section['toclevel'], $section['index'] );
1718 $lastLevel = $section['toclevel'];
1719 }
1720 $toc .= self::tocLineEnd();
1721 return self::tocList( $toc );
1722 }
1723
1724 /**
1725 * Create a headline for content
1726 *
1727 * @param int $level The level of the headline (1-6)
1728 * @param string $attribs Any attributes for the headline, starting with
1729 * a space and ending with '>'
1730 * This *must* be at least '>' for no attribs
1731 * @param string $anchor The anchor to give the headline (the bit after the #)
1732 * @param string $html Html for the text of the header
1733 * @param string $link HTML to add for the section edit link
1734 * @param bool|string $legacyAnchor A second, optional anchor to give for
1735 * backward compatibility (false to omit)
1736 *
1737 * @return string HTML headline
1738 */
1739 public static function makeHeadline( $level, $attribs, $anchor, $html,
1740 $link, $legacyAnchor = false
1741 ) {
1742 $ret = "<h$level$attribs"
1743 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1744 . $link
1745 . "</h$level>";
1746 if ( $legacyAnchor !== false ) {
1747 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1748 }
1749 return $ret;
1750 }
1751
1752 /**
1753 * Split a link trail, return the "inside" portion and the remainder of the trail
1754 * as a two-element array
1755 * @param string $trail
1756 * @return array
1757 */
1758 static function splitTrail( $trail ) {
1759 global $wgContLang;
1760 $regex = $wgContLang->linkTrail();
1761 $inside = '';
1762 if ( $trail !== '' ) {
1763 $m = array();
1764 if ( preg_match( $regex, $trail, $m ) ) {
1765 $inside = $m[1];
1766 $trail = $m[2];
1767 }
1768 }
1769 return array( $inside, $trail );
1770 }
1771
1772 /**
1773 * Generate a rollback link for a given revision. Currently it's the
1774 * caller's responsibility to ensure that the revision is the top one. If
1775 * it's not, of course, the user will get an error message.
1776 *
1777 * If the calling page is called with the parameter &bot=1, all rollback
1778 * links also get that parameter. It causes the edit itself and the rollback
1779 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1780 * changes, so this allows sysops to combat a busy vandal without bothering
1781 * other users.
1782 *
1783 * If the option verify is set this function will return the link only in case the
1784 * revision can be reverted. Please note that due to performance limitations
1785 * it might be assumed that a user isn't the only contributor of a page while
1786 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1787 * work if $wgShowRollbackEditCount is disabled, so this can only function
1788 * as an additional check.
1789 *
1790 * If the option noBrackets is set the rollback link wont be enclosed in []
1791 *
1792 * @param Revision $rev
1793 * @param IContextSource $context Context to use or null for the main context.
1794 * @param array $options
1795 * @return string
1796 */
1797 public static function generateRollback( $rev, IContextSource $context = null,
1798 $options = array( 'verify' )
1799 ) {
1800 if ( $context === null ) {
1801 $context = RequestContext::getMain();
1802 }
1803
1804 $editCount = false;
1805 if ( in_array( 'verify', $options ) ) {
1806 $editCount = self::getRollbackEditCount( $rev, true );
1807 if ( $editCount === false ) {
1808 return '';
1809 }
1810 }
1811
1812 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1813
1814 if ( !in_array( 'noBrackets', $options ) ) {
1815 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1816 }
1817
1818 return '<span class="mw-rollback-link">' . $inner . '</span>';
1819 }
1820
1821 /**
1822 * This function will return the number of revisions which a rollback
1823 * would revert and, if $verify is set it will verify that a revision
1824 * can be reverted (that the user isn't the only contributor and the
1825 * revision we might rollback to isn't deleted). These checks can only
1826 * function as an additional check as this function only checks against
1827 * the last $wgShowRollbackEditCount edits.
1828 *
1829 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1830 * is set and the user is the only contributor of the page.
1831 *
1832 * @param Revision $rev
1833 * @param bool $verify Try to verify that this revision can really be rolled back
1834 * @return int|bool|null
1835 */
1836 public static function getRollbackEditCount( $rev, $verify ) {
1837 global $wgShowRollbackEditCount;
1838 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1839 // Nothing has happened, indicate this by returning 'null'
1840 return null;
1841 }
1842
1843 $dbr = wfGetDB( DB_SLAVE );
1844
1845 // Up to the value of $wgShowRollbackEditCount revisions are counted
1846 $res = $dbr->select(
1847 'revision',
1848 array( 'rev_user_text', 'rev_deleted' ),
1849 // $rev->getPage() returns null sometimes
1850 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1851 __METHOD__,
1852 array(
1853 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1854 'ORDER BY' => 'rev_timestamp DESC',
1855 'LIMIT' => $wgShowRollbackEditCount + 1
1856 )
1857 );
1858
1859 $editCount = 0;
1860 $moreRevs = false;
1861 foreach ( $res as $row ) {
1862 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1863 if ( $verify &&
1864 ( $row->rev_deleted & Revision::DELETED_TEXT
1865 || $row->rev_deleted & Revision::DELETED_USER
1866 ) ) {
1867 // If the user or the text of the revision we might rollback
1868 // to is deleted in some way we can't rollback. Similar to
1869 // the sanity checks in WikiPage::commitRollback.
1870 return false;
1871 }
1872 $moreRevs = true;
1873 break;
1874 }
1875 $editCount++;
1876 }
1877
1878 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1879 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1880 // and there weren't any other revisions. That means that the current user is the only
1881 // editor, so we can't rollback
1882 return false;
1883 }
1884 return $editCount;
1885 }
1886
1887 /**
1888 * Build a raw rollback link, useful for collections of "tool" links
1889 *
1890 * @param Revision $rev
1891 * @param IContextSource|null $context Context to use or null for the main context.
1892 * @param int $editCount Number of edits that would be reverted
1893 * @return string HTML fragment
1894 */
1895 public static function buildRollbackLink( $rev, IContextSource $context = null,
1896 $editCount = false
1897 ) {
1898 global $wgShowRollbackEditCount, $wgMiserMode;
1899
1900 // To config which pages are affected by miser mode
1901 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1902
1903 if ( $context === null ) {
1904 $context = RequestContext::getMain();
1905 }
1906
1907 $title = $rev->getTitle();
1908 $query = array(
1909 'action' => 'rollback',
1910 'from' => $rev->getUserText(),
1911 'token' => $context->getUser()->getEditToken( array(
1912 $title->getPrefixedText(),
1913 $rev->getUserText()
1914 ) ),
1915 );
1916 if ( $context->getRequest()->getBool( 'bot' ) ) {
1917 $query['bot'] = '1';
1918 $query['hidediff'] = '1'; // bug 15999
1919 }
1920
1921 $disableRollbackEditCount = false;
1922 if ( $wgMiserMode ) {
1923 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1924 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1925 $disableRollbackEditCount = true;
1926 break;
1927 }
1928 }
1929 }
1930
1931 if ( !$disableRollbackEditCount
1932 && is_int( $wgShowRollbackEditCount )
1933 && $wgShowRollbackEditCount > 0
1934 ) {
1935 if ( !is_numeric( $editCount ) ) {
1936 $editCount = self::getRollbackEditCount( $rev, false );
1937 }
1938
1939 if ( $editCount > $wgShowRollbackEditCount ) {
1940 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1941 ->numParams( $wgShowRollbackEditCount )->parse();
1942 } else {
1943 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1944 }
1945
1946 return self::link(
1947 $title,
1948 $editCount_output,
1949 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1950 $query,
1951 array( 'known', 'noclasses' )
1952 );
1953 } else {
1954 return self::link(
1955 $title,
1956 $context->msg( 'rollbacklink' )->escaped(),
1957 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1958 $query,
1959 array( 'known', 'noclasses' )
1960 );
1961 }
1962 }
1963
1964 /**
1965 * Returns HTML for the "templates used on this page" list.
1966 *
1967 * Make an HTML list of templates, and then add a "More..." link at
1968 * the bottom. If $more is null, do not add a "More..." link. If $more
1969 * is a Title, make a link to that title and use it. If $more is a string,
1970 * directly paste it in as the link (escaping needs to be done manually).
1971 * Finally, if $more is a Message, call toString().
1972 *
1973 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1974 * @param bool $preview Whether this is for a preview
1975 * @param bool $section Whether this is for a section edit
1976 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1977 * @return string HTML output
1978 */
1979 public static function formatTemplates( $templates, $preview = false,
1980 $section = false, $more = null
1981 ) {
1982 global $wgLang;
1983 wfProfileIn( __METHOD__ );
1984
1985 $outText = '';
1986 if ( count( $templates ) > 0 ) {
1987 # Do a batch existence check
1988 $batch = new LinkBatch;
1989 foreach ( $templates as $title ) {
1990 $batch->addObj( $title );
1991 }
1992 $batch->execute();
1993
1994 # Construct the HTML
1995 $outText = '<div class="mw-templatesUsedExplanation">';
1996 if ( $preview ) {
1997 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1998 ->parseAsBlock();
1999 } elseif ( $section ) {
2000 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2001 ->parseAsBlock();
2002 } else {
2003 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2004 ->parseAsBlock();
2005 }
2006 $outText .= "</div><ul>\n";
2007
2008 usort( $templates, 'Title::compare' );
2009 foreach ( $templates as $titleObj ) {
2010 $protected = '';
2011 $restrictions = $titleObj->getRestrictions( 'edit' );
2012 if ( $restrictions ) {
2013 // Check backwards-compatible messages
2014 $msg = null;
2015 if ( $restrictions === array( 'sysop' ) ) {
2016 $msg = wfMessage( 'template-protected' );
2017 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2018 $msg = wfMessage( 'template-semiprotected' );
2019 }
2020 if ( $msg && !$msg->isDisabled() ) {
2021 $protected = $msg->parse();
2022 } else {
2023 // Construct the message from restriction-level-*
2024 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2025 $msgs = array();
2026 foreach ( $restrictions as $r ) {
2027 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2028 }
2029 $protected = wfMessage( 'parentheses' )
2030 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2031 }
2032 }
2033 if ( $titleObj->quickUserCan( 'edit' ) ) {
2034 $editLink = self::link(
2035 $titleObj,
2036 wfMessage( 'editlink' )->text(),
2037 array(),
2038 array( 'action' => 'edit' )
2039 );
2040 } else {
2041 $editLink = self::link(
2042 $titleObj,
2043 wfMessage( 'viewsourcelink' )->text(),
2044 array(),
2045 array( 'action' => 'edit' )
2046 );
2047 }
2048 $outText .= '<li>' . self::link( $titleObj )
2049 . wfMessage( 'word-separator' )->escaped()
2050 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2051 . wfMessage( 'word-separator' )->escaped()
2052 . $protected . '</li>';
2053 }
2054
2055 if ( $more instanceof Title ) {
2056 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2057 } elseif ( $more ) {
2058 $outText .= "<li>$more</li>";
2059 }
2060
2061 $outText .= '</ul>';
2062 }
2063 wfProfileOut( __METHOD__ );
2064 return $outText;
2065 }
2066
2067 /**
2068 * Returns HTML for the "hidden categories on this page" list.
2069 *
2070 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2071 * or similar
2072 * @return string HTML output
2073 */
2074 public static function formatHiddenCategories( $hiddencats ) {
2075 wfProfileIn( __METHOD__ );
2076
2077 $outText = '';
2078 if ( count( $hiddencats ) > 0 ) {
2079 # Construct the HTML
2080 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2081 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2082 $outText .= "</div><ul>\n";
2083
2084 foreach ( $hiddencats as $titleObj ) {
2085 # If it's hidden, it must exist - no need to check with a LinkBatch
2086 $outText .= '<li>'
2087 . self::link( $titleObj, null, array(), array(), 'known' )
2088 . "</li>\n";
2089 }
2090 $outText .= '</ul>';
2091 }
2092 wfProfileOut( __METHOD__ );
2093 return $outText;
2094 }
2095
2096 /**
2097 * Format a size in bytes for output, using an appropriate
2098 * unit (B, KB, MB or GB) according to the magnitude in question
2099 *
2100 * @param int $size Size to format
2101 * @return string
2102 */
2103 public static function formatSize( $size ) {
2104 global $wgLang;
2105 return htmlspecialchars( $wgLang->formatSize( $size ) );
2106 }
2107
2108 /**
2109 * Given the id of an interface element, constructs the appropriate title
2110 * attribute from the system messages. (Note, this is usually the id but
2111 * isn't always, because sometimes the accesskey needs to go on a different
2112 * element than the id, for reverse-compatibility, etc.)
2113 *
2114 * @param string $name Id of the element, minus prefixes.
2115 * @param string|null $options Null or the string 'withaccess' to add an access-
2116 * key hint
2117 * @return string Contents of the title attribute (which you must HTML-
2118 * escape), or false for no title attribute
2119 */
2120 public static function titleAttrib( $name, $options = null ) {
2121 wfProfileIn( __METHOD__ );
2122
2123 $message = wfMessage( "tooltip-$name" );
2124
2125 if ( !$message->exists() ) {
2126 $tooltip = false;
2127 } else {
2128 $tooltip = $message->text();
2129 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2130 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2131 # Message equal to '-' means suppress it.
2132 if ( $tooltip == '-' ) {
2133 $tooltip = false;
2134 }
2135 }
2136
2137 if ( $options == 'withaccess' ) {
2138 $accesskey = self::accesskey( $name );
2139 if ( $accesskey !== false ) {
2140 // Should be build the same as in jquery.accessKeyLabel.js
2141 if ( $tooltip === false || $tooltip === '' ) {
2142 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2143 } else {
2144 $tooltip .= wfMessage( 'word-separator' )->text();
2145 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2146 }
2147 }
2148 }
2149
2150 wfProfileOut( __METHOD__ );
2151 return $tooltip;
2152 }
2153
2154 public static $accesskeycache;
2155
2156 /**
2157 * Given the id of an interface element, constructs the appropriate
2158 * accesskey attribute from the system messages. (Note, this is usually
2159 * the id but isn't always, because sometimes the accesskey needs to go on
2160 * a different element than the id, for reverse-compatibility, etc.)
2161 *
2162 * @param string $name Id of the element, minus prefixes.
2163 * @return string Contents of the accesskey attribute (which you must HTML-
2164 * escape), or false for no accesskey attribute
2165 */
2166 public static function accesskey( $name ) {
2167 if ( isset( self::$accesskeycache[$name] ) ) {
2168 return self::$accesskeycache[$name];
2169 }
2170 wfProfileIn( __METHOD__ );
2171
2172 $message = wfMessage( "accesskey-$name" );
2173
2174 if ( !$message->exists() ) {
2175 $accesskey = false;
2176 } else {
2177 $accesskey = $message->plain();
2178 if ( $accesskey === '' || $accesskey === '-' ) {
2179 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2180 # attribute, but this is broken for accesskey: that might be a useful
2181 # value.
2182 $accesskey = false;
2183 }
2184 }
2185
2186 wfProfileOut( __METHOD__ );
2187 self::$accesskeycache[$name] = $accesskey;
2188 return self::$accesskeycache[$name];
2189 }
2190
2191 /**
2192 * Get a revision-deletion link, or disabled link, or nothing, depending
2193 * on user permissions & the settings on the revision.
2194 *
2195 * Will use forward-compatible revision ID in the Special:RevDelete link
2196 * if possible, otherwise the timestamp-based ID which may break after
2197 * undeletion.
2198 *
2199 * @param User $user
2200 * @param Revision $rev
2201 * @param Title $title
2202 * @return string HTML fragment
2203 */
2204 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2205 $canHide = $user->isAllowed( 'deleterevision' );
2206 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2207 return '';
2208 }
2209
2210 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2211 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2212 } else {
2213 if ( $rev->getId() ) {
2214 // RevDelete links using revision ID are stable across
2215 // page deletion and undeletion; use when possible.
2216 $query = array(
2217 'type' => 'revision',
2218 'target' => $title->getPrefixedDBkey(),
2219 'ids' => $rev->getId()
2220 );
2221 } else {
2222 // Older deleted entries didn't save a revision ID.
2223 // We have to refer to these by timestamp, ick!
2224 $query = array(
2225 'type' => 'archive',
2226 'target' => $title->getPrefixedDBkey(),
2227 'ids' => $rev->getTimestamp()
2228 );
2229 }
2230 return Linker::revDeleteLink( $query,
2231 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2232 }
2233 }
2234
2235 /**
2236 * Creates a (show/hide) link for deleting revisions/log entries
2237 *
2238 * @param array $query Query parameters to be passed to link()
2239 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2240 * @param bool $delete Set to true to use (show/hide) rather than (show)
2241 *
2242 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2243 * span to allow for customization of appearance with CSS
2244 */
2245 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2246 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2247 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2248 $html = wfMessage( $msgKey )->escaped();
2249 $tag = $restricted ? 'strong' : 'span';
2250 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2251 return Xml::tags(
2252 $tag,
2253 array( 'class' => 'mw-revdelundel-link' ),
2254 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2255 );
2256 }
2257
2258 /**
2259 * Creates a dead (show/hide) link for deleting revisions/log entries
2260 *
2261 * @param bool $delete Set to true to use (show/hide) rather than (show)
2262 *
2263 * @return string HTML text wrapped in a span to allow for customization
2264 * of appearance with CSS
2265 */
2266 public static function revDeleteLinkDisabled( $delete = true ) {
2267 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2268 $html = wfMessage( $msgKey )->escaped();
2269 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2270 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2271 }
2272
2273 /* Deprecated methods */
2274
2275 /**
2276 * @deprecated since 1.16 Use link(); warnings since 1.21
2277 *
2278 * Make a link for a title which may or may not be in the database. If you need to
2279 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2280 * call to this will result in a DB query.
2281 *
2282 * @param Title $nt The title object to make the link from, e.g. from Title::newFromText.
2283 * @param string $text Link text
2284 * @param string $query Optional query part
2285 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2286 * be included in the link text. Other characters will be appended after
2287 * the end of the link.
2288 * @param string $prefix Optional prefix. As trail, only before instead of after.
2289 * @return string
2290 */
2291 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2292 wfDeprecated( __METHOD__, '1.21' );
2293
2294 wfProfileIn( __METHOD__ );
2295 $query = wfCgiToArray( $query );
2296 list( $inside, $trail ) = self::splitTrail( $trail );
2297 if ( $text === '' ) {
2298 $text = self::linkText( $nt );
2299 }
2300
2301 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2302
2303 wfProfileOut( __METHOD__ );
2304 return $ret;
2305 }
2306
2307 /**
2308 * @deprecated since 1.16 Use link(); warnings since 1.21
2309 *
2310 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2311 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2312 * pages.
2313 *
2314 * @param Title $title Title object of target page
2315 * @param string $text Text to replace the title
2316 * @param string $query Link target
2317 * @param string $trail Text after link
2318 * @param string $prefix Text before link text
2319 * @param string $aprops Extra attributes to the a-element
2320 * @param string $style Style to apply - if empty, use getInternalLinkAttributesObj instead
2321 * @return string The a-element
2322 */
2323 static function makeKnownLinkObj(
2324 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2325 ) {
2326 wfDeprecated( __METHOD__, '1.21' );
2327
2328 wfProfileIn( __METHOD__ );
2329
2330 if ( $text == '' ) {
2331 $text = self::linkText( $title );
2332 }
2333 $attribs = Sanitizer::mergeAttributes(
2334 Sanitizer::decodeTagAttributes( $aprops ),
2335 Sanitizer::decodeTagAttributes( $style )
2336 );
2337 $query = wfCgiToArray( $query );
2338 list( $inside, $trail ) = self::splitTrail( $trail );
2339
2340 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2341 array( 'known', 'noclasses' ) ) . $trail;
2342
2343 wfProfileOut( __METHOD__ );
2344 return $ret;
2345 }
2346
2347 /**
2348 * Returns the attributes for the tooltip and access key.
2349 * @param string $name
2350 * @return array
2351 */
2352 public static function tooltipAndAccesskeyAttribs( $name ) {
2353 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2354 # no attribute" instead of "output '' as value for attribute", this
2355 # would be three lines.
2356 $attribs = array(
2357 'title' => self::titleAttrib( $name, 'withaccess' ),
2358 'accesskey' => self::accesskey( $name )
2359 );
2360 if ( $attribs['title'] === false ) {
2361 unset( $attribs['title'] );
2362 }
2363 if ( $attribs['accesskey'] === false ) {
2364 unset( $attribs['accesskey'] );
2365 }
2366 return $attribs;
2367 }
2368
2369 /**
2370 * Returns raw bits of HTML, use titleAttrib()
2371 * @param string $name
2372 * @param array|null $options
2373 * @return null|string
2374 */
2375 public static function tooltip( $name, $options = null ) {
2376 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2377 # no attribute" instead of "output '' as value for attribute", this
2378 # would be two lines.
2379 $tooltip = self::titleAttrib( $name, $options );
2380 if ( $tooltip === false ) {
2381 return '';
2382 }
2383 return Xml::expandAttributes( array(
2384 'title' => $tooltip
2385 ) );
2386 }
2387 }
2388
2389 /**
2390 * @since 1.18
2391 */
2392 class DummyLinker {
2393
2394 /**
2395 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2396 * into static calls to the new Linker for backwards compatibility.
2397 *
2398 * @param string $fname Name of called method
2399 * @param array $args Arguments to the method
2400 * @return mixed
2401 */
2402 public function __call( $fname, $args ) {
2403 return call_user_func_array( array( 'Linker', $fname ), $args );
2404 }
2405 }