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