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