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