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