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