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