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