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