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