Merge "Fixed dependencies for jquery.collapsibleTabs"
[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 } else {
951 wfProfileOut( __METHOD__ );
952 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
953 }
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 * @return string
1042 */
1043 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
1044 $class = "external";
1045 if ( $linktype ) {
1046 $class .= " $linktype";
1047 }
1048 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1049 $class .= " {$attribs['class']}";
1050 }
1051 $attribs['class'] = $class;
1052
1053 if ( $escape ) {
1054 $text = htmlspecialchars( $text );
1055 }
1056 $link = '';
1057 $success = wfRunHooks( 'LinkerMakeExternalLink',
1058 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1059 if ( !$success ) {
1060 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1061 return $link;
1062 }
1063 $attribs['href'] = $url;
1064 return Html::rawElement( 'a', $attribs, $text );
1065 }
1066
1067 /**
1068 * Make user link (or user contributions for unregistered users)
1069 * @param $userId Integer: user id in database.
1070 * @param $userName String: user name in database.
1071 * @param $altUserName String: text to display instead of the user name (optional)
1072 * @return String: HTML fragment
1073 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1074 */
1075 public static function userLink( $userId, $userName, $altUserName = false ) {
1076 if ( $userId == 0 ) {
1077 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1078 } else {
1079 $page = Title::makeTitle( NS_USER, $userName );
1080 }
1081
1082 return self::link(
1083 $page,
1084 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1085 array( 'class' => 'mw-userlink' )
1086 );
1087 }
1088
1089 /**
1090 * Generate standard user tool links (talk, contributions, block link, etc.)
1091 *
1092 * @param $userId Integer: user identifier
1093 * @param $userText String: user name or IP address
1094 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1095 * red if the user has no edits?
1096 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1097 * @param $edits Integer: user edit count (optional, for performance)
1098 * @return String: HTML fragment
1099 */
1100 public static function userToolLinks(
1101 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1102 ) {
1103 global $wgUser, $wgDisableAnonTalk, $wgLang;
1104 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1105 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1106 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1107
1108 $items = array();
1109 if ( $talkable ) {
1110 $items[] = self::userTalkLink( $userId, $userText );
1111 }
1112 if ( $userId ) {
1113 // check if the user has an edit
1114 $attribs = array();
1115 if ( $redContribsWhenNoEdits ) {
1116 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1117 $user = User::newFromId( $userId );
1118 $edits = $user->getEditCount();
1119 }
1120 if ( $edits === 0 ) {
1121 $attribs['class'] = 'new';
1122 }
1123 }
1124 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1125
1126 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1127 }
1128 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1129 $items[] = self::blockLink( $userId, $userText );
1130 }
1131
1132 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1133 $items[] = self::emailLink( $userId, $userText );
1134 }
1135
1136 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1137
1138 if ( $items ) {
1139 return wfMessage( 'word-separator' )->plain()
1140 . '<span class="mw-usertoollinks">'
1141 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1142 . '</span>';
1143 } else {
1144 return '';
1145 }
1146 }
1147
1148 /**
1149 * Alias for userToolLinks( $userId, $userText, true );
1150 * @param $userId Integer: user identifier
1151 * @param $userText String: user name or IP address
1152 * @param $edits Integer: user edit count (optional, for performance)
1153 * @return String
1154 */
1155 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1156 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1157 }
1158
1159
1160 /**
1161 * @param $userId Integer: user id in database.
1162 * @param $userText String: user name in database.
1163 * @return String: HTML fragment with user talk link
1164 */
1165 public static function userTalkLink( $userId, $userText ) {
1166 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1167 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1168 return $userTalkLink;
1169 }
1170
1171 /**
1172 * @param $userId Integer: userid
1173 * @param $userText String: user name in database.
1174 * @return String: HTML fragment with block link
1175 */
1176 public static function blockLink( $userId, $userText ) {
1177 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1178 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1179 return $blockLink;
1180 }
1181
1182 /**
1183 * @param $userId Integer: userid
1184 * @param $userText String: user name in database.
1185 * @return String: HTML fragment with e-mail user link
1186 */
1187 public static function emailLink( $userId, $userText ) {
1188 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1189 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1190 return $emailLink;
1191 }
1192
1193 /**
1194 * Generate a user link if the current user is allowed to view it
1195 * @param $rev Revision object.
1196 * @param $isPublic Boolean: show only if all users can see it
1197 * @return String: HTML fragment
1198 */
1199 public static function revUserLink( $rev, $isPublic = false ) {
1200 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1201 $link = wfMessage( 'rev-deleted-user' )->escaped();
1202 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1203 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1204 $rev->getUserText( Revision::FOR_THIS_USER ) );
1205 } else {
1206 $link = wfMessage( 'rev-deleted-user' )->escaped();
1207 }
1208 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1209 return '<span class="history-deleted">' . $link . '</span>';
1210 }
1211 return $link;
1212 }
1213
1214 /**
1215 * Generate a user tool link cluster if the current user is allowed to view it
1216 * @param $rev Revision object.
1217 * @param $isPublic Boolean: show only if all users can see it
1218 * @return string HTML
1219 */
1220 public static function revUserTools( $rev, $isPublic = false ) {
1221 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1222 $link = wfMessage( 'rev-deleted-user' )->escaped();
1223 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1224 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1225 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1226 $link = self::userLink( $userId, $userText )
1227 . wfMessage( 'word-separator' )->plain()
1228 . self::userToolLinks( $userId, $userText );
1229 } else {
1230 $link = wfMessage( 'rev-deleted-user' )->escaped();
1231 }
1232 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1233 return ' <span class="history-deleted">' . $link . '</span>';
1234 }
1235 return $link;
1236 }
1237
1238 /**
1239 * This function is called by all recent changes variants, by the page history,
1240 * and by the user contributions list. It is responsible for formatting edit
1241 * comments. It escapes any HTML in the comment, but adds some CSS to format
1242 * auto-generated comments (from section editing) and formats [[wikilinks]].
1243 *
1244 * @author Erik Moeller <moeller@scireview.de>
1245 *
1246 * Note: there's not always a title to pass to this function.
1247 * Since you can't set a default parameter for a reference, I've turned it
1248 * temporarily to a value pass. Should be adjusted further. --brion
1249 *
1250 * @param $comment String
1251 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1252 * @param $local Boolean: whether section links should refer to local page
1253 * @return mixed|String
1254 */
1255 public static function formatComment( $comment, $title = null, $local = false ) {
1256 wfProfileIn( __METHOD__ );
1257
1258 # Sanitize text a bit:
1259 $comment = str_replace( "\n", " ", $comment );
1260 # Allow HTML entities (for bug 13815)
1261 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1262
1263 # Render autocomments and make links:
1264 $comment = self::formatAutocomments( $comment, $title, $local );
1265 $comment = self::formatLinksInComment( $comment, $title, $local );
1266
1267 wfProfileOut( __METHOD__ );
1268 return $comment;
1269 }
1270
1271 /**
1272 * @var Title
1273 */
1274 static $autocommentTitle;
1275 static $autocommentLocal;
1276
1277 /**
1278 * The pattern for autogen comments is / * foo * /, which makes for
1279 * some nasty regex.
1280 * We look for all comments, match any text before and after the comment,
1281 * add a separator where needed and format the comment itself with CSS
1282 * Called by Linker::formatComment.
1283 *
1284 * @param $comment String: comment text
1285 * @param $title Title|null An optional title object used to links to sections
1286 * @param $local Boolean: whether section links should refer to local page
1287 * @return String: formatted comment
1288 */
1289 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1290 // Bah!
1291 self::$autocommentTitle = $title;
1292 self::$autocommentLocal = $local;
1293 $comment = preg_replace_callback(
1294 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1295 array( 'Linker', 'formatAutocommentsCallback' ),
1296 $comment );
1297 self::$autocommentTitle = null;
1298 self::$autocommentLocal = null;
1299 return $comment;
1300 }
1301
1302 /**
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 $comment String: 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 array( 'Linker', 'formatLinksInCommentCallback' ),
1378 $comment );
1379 self::$commentContextTitle = null;
1380 self::$commentLocal = null;
1381 return $html;
1382 }
1383
1384 /**
1385 * @param $match
1386 * @return mixed
1387 */
1388 protected static function formatLinksInCommentCallback( $match ) {
1389 global $wgContLang;
1390
1391 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1392 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1393
1394 $comment = $match[0];
1395
1396 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1397 if ( strpos( $match[1], '%' ) !== false ) {
1398 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1399 }
1400
1401 # Handle link renaming [[foo|text]] will show link as "text"
1402 if ( $match[3] != "" ) {
1403 $text = $match[3];
1404 } else {
1405 $text = $match[1];
1406 }
1407 $submatch = array();
1408 $thelink = null;
1409 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1410 # Media link; trail not supported.
1411 $linkRegexp = '/\[\[(.*?)\]\]/';
1412 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1413 if ( $title ) {
1414 $thelink = self::makeMediaLinkObj( $title, $text );
1415 }
1416 } else {
1417 # Other kind of link
1418 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1419 $trail = $submatch[1];
1420 } else {
1421 $trail = "";
1422 }
1423 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1424 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1425 $match[1] = substr( $match[1], 1 );
1426 list( $inside, $trail ) = self::splitTrail( $trail );
1427
1428 $linkText = $text;
1429 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1430 $match[1], $linkText );
1431
1432 $target = Title::newFromText( $linkTarget );
1433 if ( $target ) {
1434 if ( $target->getText() == '' && $target->getInterwiki() === ''
1435 && !self::$commentLocal && self::$commentContextTitle )
1436 {
1437 $newTarget = clone ( self::$commentContextTitle );
1438 $newTarget->setFragment( '#' . $target->getFragment() );
1439 $target = $newTarget;
1440 }
1441 $thelink = self::link(
1442 $target,
1443 $linkText . $inside
1444 ) . $trail;
1445 }
1446 }
1447 if ( $thelink ) {
1448 // If the link is still valid, go ahead and replace it in!
1449 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1450 }
1451
1452 return $comment;
1453 }
1454
1455 /**
1456 * @param $contextTitle Title
1457 * @param $target
1458 * @param $text
1459 * @return string
1460 */
1461 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1462 # Valid link forms:
1463 # Foobar -- normal
1464 # :Foobar -- override special treatment of prefix (images, language links)
1465 # /Foobar -- convert to CurrentPage/Foobar
1466 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1467 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1468 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1469
1470 wfProfileIn( __METHOD__ );
1471 $ret = $target; # default return value is no change
1472
1473 # Some namespaces don't allow subpages,
1474 # so only perform processing if subpages are allowed
1475 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1476 $hash = strpos( $target, '#' );
1477 if ( $hash !== false ) {
1478 $suffix = substr( $target, $hash );
1479 $target = substr( $target, 0, $hash );
1480 } else {
1481 $suffix = '';
1482 }
1483 # bug 7425
1484 $target = trim( $target );
1485 # Look at the first character
1486 if ( $target != '' && $target[0] === '/' ) {
1487 # / at end means we don't want the slash to be shown
1488 $m = array();
1489 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1490 if ( $trailingSlashes ) {
1491 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1492 } else {
1493 $noslash = substr( $target, 1 );
1494 }
1495
1496 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1497 if ( $text === '' ) {
1498 $text = $target . $suffix;
1499 } # this might be changed for ugliness reasons
1500 } else {
1501 # check for .. subpage backlinks
1502 $dotdotcount = 0;
1503 $nodotdot = $target;
1504 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1505 ++$dotdotcount;
1506 $nodotdot = substr( $nodotdot, 3 );
1507 }
1508 if ( $dotdotcount > 0 ) {
1509 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1510 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1511 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1512 # / at the end means don't show full path
1513 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1514 $nodotdot = substr( $nodotdot, 0, -1 );
1515 if ( $text === '' ) {
1516 $text = $nodotdot . $suffix;
1517 }
1518 }
1519 $nodotdot = trim( $nodotdot );
1520 if ( $nodotdot != '' ) {
1521 $ret .= '/' . $nodotdot;
1522 }
1523 $ret .= $suffix;
1524 }
1525 }
1526 }
1527 }
1528
1529 wfProfileOut( __METHOD__ );
1530 return $ret;
1531 }
1532
1533 /**
1534 * Wrap a comment in standard punctuation and formatting if
1535 * it's non-empty, otherwise return empty string.
1536 *
1537 * @param $comment String
1538 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1539 * @param $local Boolean: whether section links should refer to local page
1540 *
1541 * @return string
1542 */
1543 public static function commentBlock( $comment, $title = null, $local = false ) {
1544 // '*' used to be the comment inserted by the software way back
1545 // in antiquity in case none was provided, here for backwards
1546 // compatability, acc. to brion -ævar
1547 if ( $comment == '' || $comment == '*' ) {
1548 return '';
1549 } else {
1550 $formatted = self::formatComment( $comment, $title, $local );
1551 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1552 return " <span class=\"comment\">$formatted</span>";
1553 }
1554 }
1555
1556 /**
1557 * Wrap and format the given revision's comment block, if the current
1558 * user is allowed to view it.
1559 *
1560 * @param $rev Revision object
1561 * @param $local Boolean: whether section links should refer to local page
1562 * @param $isPublic Boolean: show only if all users can see it
1563 * @return String: HTML fragment
1564 */
1565 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1566 if ( $rev->getRawComment() == "" ) {
1567 return "";
1568 }
1569 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1570 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1571 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1572 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1573 $rev->getTitle(), $local );
1574 } else {
1575 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1576 }
1577 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1578 return " <span class=\"history-deleted\">$block</span>";
1579 }
1580 return $block;
1581 }
1582
1583 /**
1584 * @param $size
1585 * @return string
1586 */
1587 public static function formatRevisionSize( $size ) {
1588 if ( $size == 0 ) {
1589 $stxt = wfMessage( 'historyempty' )->escaped();
1590 } else {
1591 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1592 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1593 }
1594 return "<span class=\"history-size\">$stxt</span>";
1595 }
1596
1597 /**
1598 * Add another level to the Table of Contents
1599 *
1600 * @return string
1601 */
1602 public static function tocIndent() {
1603 return "\n<ul>";
1604 }
1605
1606 /**
1607 * Finish one or more sublevels on the Table of Contents
1608 *
1609 * @return string
1610 */
1611 public static function tocUnindent( $level ) {
1612 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1613 }
1614
1615 /**
1616 * parameter level defines if we are on an indentation level
1617 *
1618 * @return string
1619 */
1620 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1621 $classes = "toclevel-$level";
1622 if ( $sectionIndex !== false ) {
1623 $classes .= " tocsection-$sectionIndex";
1624 }
1625 return "\n<li class=\"$classes\"><a href=\"#" .
1626 $anchor . '"><span class="tocnumber">' .
1627 $tocnumber . '</span> <span class="toctext">' .
1628 $tocline . '</span></a>';
1629 }
1630
1631 /**
1632 * End a Table Of Contents line.
1633 * tocUnindent() will be used instead if we're ending a line below
1634 * the new level.
1635 * @return string
1636 */
1637 public static function tocLineEnd() {
1638 return "</li>\n";
1639 }
1640
1641 /**
1642 * Wraps the TOC in a table and provides the hide/collapse javascript.
1643 *
1644 * @param $toc String: html of the Table Of Contents
1645 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1646 * @return String: full html of the TOC
1647 */
1648 public static function tocList( $toc, $lang = false ) {
1649 $lang = wfGetLangObj( $lang );
1650 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1651
1652 return
1653 '<table id="toc" class="toc"><tr><td>'
1654 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1655 . $toc
1656 . "</ul>\n</td></tr></table>\n";
1657 }
1658
1659 /**
1660 * Generate a table of contents from a section tree
1661 * Currently unused.
1662 *
1663 * @param $tree array Return value of ParserOutput::getSections()
1664 * @return String: HTML fragment
1665 */
1666 public static function generateTOC( $tree ) {
1667 $toc = '';
1668 $lastLevel = 0;
1669 foreach ( $tree as $section ) {
1670 if ( $section['toclevel'] > $lastLevel )
1671 $toc .= self::tocIndent();
1672 elseif ( $section['toclevel'] < $lastLevel )
1673 $toc .= self::tocUnindent(
1674 $lastLevel - $section['toclevel'] );
1675 else
1676 $toc .= self::tocLineEnd();
1677
1678 $toc .= self::tocLine( $section['anchor'],
1679 $section['line'], $section['number'],
1680 $section['toclevel'], $section['index'] );
1681 $lastLevel = $section['toclevel'];
1682 }
1683 $toc .= self::tocLineEnd();
1684 return self::tocList( $toc );
1685 }
1686
1687 /**
1688 * Create a headline for content
1689 *
1690 * @param $level Integer: the level of the headline (1-6)
1691 * @param $attribs String: any attributes for the headline, starting with
1692 * a space and ending with '>'
1693 * This *must* be at least '>' for no attribs
1694 * @param $anchor String: the anchor to give the headline (the bit after the #)
1695 * @param $html String: html for the text of the header
1696 * @param $link String: HTML to add for the section edit link
1697 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1698 * backward compatibility (false to omit)
1699 *
1700 * @return String: HTML headline
1701 */
1702 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1703 $ret = "<h$level$attribs"
1704 . $link
1705 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1706 . "</h$level>";
1707 if ( $legacyAnchor !== false ) {
1708 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1709 }
1710 return $ret;
1711 }
1712
1713 /**
1714 * Split a link trail, return the "inside" portion and the remainder of the trail
1715 * as a two-element array
1716 * @return array
1717 */
1718 static function splitTrail( $trail ) {
1719 global $wgContLang;
1720 $regex = $wgContLang->linkTrail();
1721 $inside = '';
1722 if ( $trail !== '' ) {
1723 $m = array();
1724 if ( preg_match( $regex, $trail, $m ) ) {
1725 $inside = $m[1];
1726 $trail = $m[2];
1727 }
1728 }
1729 return array( $inside, $trail );
1730 }
1731
1732 /**
1733 * Generate a rollback link for a given revision. Currently it's the
1734 * caller's responsibility to ensure that the revision is the top one. If
1735 * it's not, of course, the user will get an error message.
1736 *
1737 * If the calling page is called with the parameter &bot=1, all rollback
1738 * links also get that parameter. It causes the edit itself and the rollback
1739 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1740 * changes, so this allows sysops to combat a busy vandal without bothering
1741 * other users.
1742 *
1743 * @param $rev Revision object
1744 * @param $context IContextSource context to use or null for the main context.
1745 * @return string
1746 */
1747 public static function generateRollback( $rev, IContextSource $context = null ) {
1748 if ( $context === null ) {
1749 $context = RequestContext::getMain();
1750 }
1751
1752 return '<span class="mw-rollback-link">'
1753 . $context->msg( 'brackets' )->rawParams(
1754 self::buildRollbackLink( $rev, $context ) )->plain()
1755 . '</span>';
1756 }
1757
1758 /**
1759 * Build a raw rollback link, useful for collections of "tool" links
1760 *
1761 * @param $rev Revision object
1762 * @param $context IContextSource context to use or null for the main context.
1763 * @return String: HTML fragment
1764 */
1765 public static function buildRollbackLink( $rev, IContextSource $context = null ) {
1766 global $wgShowRollbackEditCount, $wgMiserMode;
1767
1768 // To config which pages are effected by miser mode
1769 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1770
1771 if ( $context === null ) {
1772 $context = RequestContext::getMain();
1773 }
1774
1775 $title = $rev->getTitle();
1776 $query = array(
1777 'action' => 'rollback',
1778 'from' => $rev->getUserText(),
1779 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1780 );
1781 if ( $context->getRequest()->getBool( 'bot' ) ) {
1782 $query['bot'] = '1';
1783 $query['hidediff'] = '1'; // bug 15999
1784 }
1785
1786 $disableRollbackEditCount = false;
1787 if( $wgMiserMode ) {
1788 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1789 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1790 $disableRollbackEditCount = true;
1791 break;
1792 }
1793 }
1794 }
1795
1796 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1797 $dbr = wfGetDB( DB_SLAVE );
1798
1799 // Up to the value of $wgShowRollbackEditCount revisions are counted
1800 $res = $dbr->select( 'revision',
1801 array( 'rev_id', 'rev_user_text' ),
1802 // $rev->getPage() returns null sometimes
1803 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1804 __METHOD__,
1805 array( 'USE INDEX' => 'page_timestamp',
1806 'ORDER BY' => 'rev_timestamp DESC',
1807 'LIMIT' => $wgShowRollbackEditCount + 1 )
1808 );
1809
1810 $editCount = 0;
1811 while( $row = $dbr->fetchObject( $res ) ) {
1812 if( $rev->getUserText() != $row->rev_user_text ) {
1813 break;
1814 }
1815 $editCount++;
1816 }
1817
1818 if( $editCount > $wgShowRollbackEditCount ) {
1819 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1820 } else {
1821 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1822 }
1823
1824 return self::link(
1825 $title,
1826 $editCount_output,
1827 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1828 $query,
1829 array( 'known', 'noclasses' )
1830 );
1831 } else {
1832 return self::link(
1833 $title,
1834 $context->msg( 'rollbacklink' )->escaped(),
1835 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1836 $query,
1837 array( 'known', 'noclasses' )
1838 );
1839 }
1840 }
1841
1842 /**
1843 * Returns HTML for the "templates used on this page" list.
1844 *
1845 * @param $templates Array of templates from Article::getUsedTemplate
1846 * or similar
1847 * @param $preview Boolean: whether this is for a preview
1848 * @param $section Boolean: whether this is for a section edit
1849 * @return String: HTML output
1850 */
1851 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1852 wfProfileIn( __METHOD__ );
1853
1854 $outText = '';
1855 if ( count( $templates ) > 0 ) {
1856 # Do a batch existence check
1857 $batch = new LinkBatch;
1858 foreach ( $templates as $title ) {
1859 $batch->addObj( $title );
1860 }
1861 $batch->execute();
1862
1863 # Construct the HTML
1864 $outText = '<div class="mw-templatesUsedExplanation">';
1865 if ( $preview ) {
1866 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1867 ->parseAsBlock();
1868 } elseif ( $section ) {
1869 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1870 ->parseAsBlock();
1871 } else {
1872 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1873 ->parseAsBlock();
1874 }
1875 $outText .= "</div><ul>\n";
1876
1877 usort( $templates, 'Title::compare' );
1878 foreach ( $templates as $titleObj ) {
1879 $r = $titleObj->getRestrictions( 'edit' );
1880 if ( in_array( 'sysop', $r ) ) {
1881 $protected = wfMessage( 'template-protected' )->parse();
1882 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1883 $protected = wfMessage( 'template-semiprotected' )->parse();
1884 } else {
1885 $protected = '';
1886 }
1887 if ( $titleObj->quickUserCan( 'edit' ) ) {
1888 $editLink = self::link(
1889 $titleObj,
1890 wfMessage( 'editlink' )->text(),
1891 array(),
1892 array( 'action' => 'edit' )
1893 );
1894 } else {
1895 $editLink = self::link(
1896 $titleObj,
1897 wfMessage( 'viewsourcelink' )->text(),
1898 array(),
1899 array( 'action' => 'edit' )
1900 );
1901 }
1902 $outText .= '<li>' . self::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1903 }
1904 $outText .= '</ul>';
1905 }
1906 wfProfileOut( __METHOD__ );
1907 return $outText;
1908 }
1909
1910 /**
1911 * Returns HTML for the "hidden categories on this page" list.
1912 *
1913 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1914 * or similar
1915 * @return String: HTML output
1916 */
1917 public static function formatHiddenCategories( $hiddencats ) {
1918 wfProfileIn( __METHOD__ );
1919
1920 $outText = '';
1921 if ( count( $hiddencats ) > 0 ) {
1922 # Construct the HTML
1923 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1924 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1925 $outText .= "</div><ul>\n";
1926
1927 foreach ( $hiddencats as $titleObj ) {
1928 $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
1929 }
1930 $outText .= '</ul>';
1931 }
1932 wfProfileOut( __METHOD__ );
1933 return $outText;
1934 }
1935
1936 /**
1937 * Format a size in bytes for output, using an appropriate
1938 * unit (B, KB, MB or GB) according to the magnitude in question
1939 *
1940 * @param $size int Size to format
1941 * @return String
1942 */
1943 public static function formatSize( $size ) {
1944 global $wgLang;
1945 return htmlspecialchars( $wgLang->formatSize( $size ) );
1946 }
1947
1948 /**
1949 * Given the id of an interface element, constructs the appropriate title
1950 * attribute from the system messages. (Note, this is usually the id but
1951 * isn't always, because sometimes the accesskey needs to go on a different
1952 * element than the id, for reverse-compatibility, etc.)
1953 *
1954 * @param $name String: id of the element, minus prefixes.
1955 * @param $options Mixed: null or the string 'withaccess' to add an access-
1956 * key hint
1957 * @return String: contents of the title attribute (which you must HTML-
1958 * escape), or false for no title attribute
1959 */
1960 public static function titleAttrib( $name, $options = null ) {
1961 wfProfileIn( __METHOD__ );
1962
1963 $message = wfMessage( "tooltip-$name" );
1964
1965 if ( !$message->exists() ) {
1966 $tooltip = false;
1967 } else {
1968 $tooltip = $message->text();
1969 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1970 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1971 # Message equal to '-' means suppress it.
1972 if ( $tooltip == '-' ) {
1973 $tooltip = false;
1974 }
1975 }
1976
1977 if ( $options == 'withaccess' ) {
1978 $accesskey = self::accesskey( $name );
1979 if ( $accesskey !== false ) {
1980 if ( $tooltip === false || $tooltip === '' ) {
1981 $tooltip = "[$accesskey]";
1982 } else {
1983 $tooltip .= " [$accesskey]";
1984 }
1985 }
1986 }
1987
1988 wfProfileOut( __METHOD__ );
1989 return $tooltip;
1990 }
1991
1992 static $accesskeycache;
1993
1994 /**
1995 * Given the id of an interface element, constructs the appropriate
1996 * accesskey attribute from the system messages. (Note, this is usually
1997 * the id but isn't always, because sometimes the accesskey needs to go on
1998 * a different element than the id, for reverse-compatibility, etc.)
1999 *
2000 * @param $name String: id of the element, minus prefixes.
2001 * @return String: contents of the accesskey attribute (which you must HTML-
2002 * escape), or false for no accesskey attribute
2003 */
2004 public static function accesskey( $name ) {
2005 if ( isset( self::$accesskeycache[$name] ) ) {
2006 return self::$accesskeycache[$name];
2007 }
2008 wfProfileIn( __METHOD__ );
2009
2010 $message = wfMessage( "accesskey-$name" );
2011
2012 if ( !$message->exists() ) {
2013 $accesskey = false;
2014 } else {
2015 $accesskey = $message->plain();
2016 if ( $accesskey === '' || $accesskey === '-' ) {
2017 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2018 # attribute, but this is broken for accesskey: that might be a useful
2019 # value.
2020 $accesskey = false;
2021 }
2022 }
2023
2024 wfProfileOut( __METHOD__ );
2025 return self::$accesskeycache[$name] = $accesskey;
2026 }
2027
2028 /**
2029 * Get a revision-deletion link, or disabled link, or nothing, depending
2030 * on user permissions & the settings on the revision.
2031 *
2032 * Will use forward-compatible revision ID in the Special:RevDelete link
2033 * if possible, otherwise the timestamp-based ID which may break after
2034 * undeletion.
2035 *
2036 * @param User $user
2037 * @param Revision $rev
2038 * @param Revision $title
2039 * @return string HTML fragment
2040 */
2041 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2042 $canHide = $user->isAllowed( 'deleterevision' );
2043 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2044 return '';
2045 }
2046
2047 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2048 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2049 } else {
2050 if ( $rev->getId() ) {
2051 // RevDelete links using revision ID are stable across
2052 // page deletion and undeletion; use when possible.
2053 $query = array(
2054 'type' => 'revision',
2055 'target' => $title->getPrefixedDBkey(),
2056 'ids' => $rev->getId()
2057 );
2058 } else {
2059 // Older deleted entries didn't save a revision ID.
2060 // We have to refer to these by timestamp, ick!
2061 $query = array(
2062 'type' => 'archive',
2063 'target' => $title->getPrefixedDBkey(),
2064 'ids' => $rev->getTimestamp()
2065 );
2066 }
2067 return Linker::revDeleteLink( $query,
2068 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2069 }
2070 }
2071
2072 /**
2073 * Creates a (show/hide) link for deleting revisions/log entries
2074 *
2075 * @param $query Array: query parameters to be passed to link()
2076 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2077 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2078 *
2079 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2080 * span to allow for customization of appearance with CSS
2081 */
2082 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2083 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2084 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2085 $html = wfMessage( $msgKey )->escaped();
2086 $tag = $restricted ? 'strong' : 'span';
2087 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2088 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2089 }
2090
2091 /**
2092 * Creates a dead (show/hide) link for deleting revisions/log entries
2093 *
2094 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2095 *
2096 * @return string HTML text wrapped in a span to allow for customization
2097 * of appearance with CSS
2098 */
2099 public static function revDeleteLinkDisabled( $delete = true ) {
2100 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2101 $html = wfMessage( $msgKey )->escaped();
2102 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2103 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2104 }
2105
2106 /* Deprecated methods */
2107
2108 /**
2109 * @deprecated since 1.16 Use link()
2110 *
2111 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2112 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2113 *
2114 * @param $title String: The text of the title
2115 * @param $text String: Link text
2116 * @param $query String: Optional query part
2117 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2118 * be included in the link text. Other characters will be appended after
2119 * the end of the link.
2120 * @return string
2121 */
2122 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2123 wfDeprecated( __METHOD__, '1.16' );
2124
2125 $nt = Title::newFromText( $title );
2126 if ( $nt instanceof Title ) {
2127 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2128 } else {
2129 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2130 return $text == '' ? $title : $text;
2131 }
2132 }
2133
2134 /**
2135 * @deprecated since 1.16 Use link()
2136 *
2137 * Make a link for a title which may or may not be in the database. If you need to
2138 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2139 * call to this will result in a DB query.
2140 *
2141 * @param $nt Title: the title object to make the link from, e.g. from
2142 * Title::newFromText.
2143 * @param $text String: link text
2144 * @param $query String: optional query part
2145 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2146 * be included in the link text. Other characters will be appended after
2147 * the end of the link.
2148 * @param $prefix String: optional prefix. As trail, only before instead of after.
2149 * @return string
2150 */
2151 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2152 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2153
2154 wfProfileIn( __METHOD__ );
2155 $query = wfCgiToArray( $query );
2156 list( $inside, $trail ) = self::splitTrail( $trail );
2157 if ( $text === '' ) {
2158 $text = self::linkText( $nt );
2159 }
2160
2161 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2162
2163 wfProfileOut( __METHOD__ );
2164 return $ret;
2165 }
2166
2167 /**
2168 * @deprecated since 1.16 Use link()
2169 *
2170 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2171 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2172 * pages.
2173 *
2174 * @param $title Title object of target page
2175 * @param $text String: text to replace the title
2176 * @param $query String: link target
2177 * @param $trail String: text after link
2178 * @param $prefix String: text before link text
2179 * @param $aprops String: extra attributes to the a-element
2180 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2181 * @return string the a-element
2182 */
2183 static function makeKnownLinkObj(
2184 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
2185 ) {
2186 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2187
2188 wfProfileIn( __METHOD__ );
2189
2190 if ( $text == '' ) {
2191 $text = self::linkText( $title );
2192 }
2193 $attribs = Sanitizer::mergeAttributes(
2194 Sanitizer::decodeTagAttributes( $aprops ),
2195 Sanitizer::decodeTagAttributes( $style )
2196 );
2197 $query = wfCgiToArray( $query );
2198 list( $inside, $trail ) = self::splitTrail( $trail );
2199
2200 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2201 array( 'known', 'noclasses' ) ) . $trail;
2202
2203 wfProfileOut( __METHOD__ );
2204 return $ret;
2205 }
2206
2207 /**
2208 * @deprecated since 1.16 Use link()
2209 *
2210 * Make a red link to the edit page of a given title.
2211 *
2212 * @param $title Title object of the target page
2213 * @param $text String: Link text
2214 * @param $query String: Optional query part
2215 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2216 * be included in the link text. Other characters will be appended after
2217 * the end of the link.
2218 * @param $prefix String: Optional prefix
2219 * @return string
2220 */
2221 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2222 wfDeprecated( __METHOD__, '1.16' );
2223
2224 wfProfileIn( __METHOD__ );
2225
2226 list( $inside, $trail ) = self::splitTrail( $trail );
2227 if ( $text === '' ) {
2228 $text = self::linkText( $title );
2229 }
2230
2231 $ret = self::link( $title, "$prefix$text$inside", array(),
2232 wfCgiToArray( $query ), 'broken' ) . $trail;
2233
2234 wfProfileOut( __METHOD__ );
2235 return $ret;
2236 }
2237
2238 /**
2239 * @deprecated since 1.16 Use link()
2240 *
2241 * Make a coloured link.
2242 *
2243 * @param $nt Title object of the target page
2244 * @param $colour Integer: colour of the link
2245 * @param $text String: link text
2246 * @param $query String: optional query part
2247 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2248 * be included in the link text. Other characters will be appended after
2249 * the end of the link.
2250 * @param $prefix String: Optional prefix
2251 * @return string
2252 */
2253 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2254 wfDeprecated( __METHOD__, '1.16' );
2255
2256 if ( $colour != '' ) {
2257 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2258 } else {
2259 $style = '';
2260 }
2261 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2262 }
2263
2264 /**
2265 * Returns the attributes for the tooltip and access key.
2266 * @return array
2267 */
2268 public static function tooltipAndAccesskeyAttribs( $name ) {
2269 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2270 # no attribute" instead of "output '' as value for attribute", this
2271 # would be three lines.
2272 $attribs = array(
2273 'title' => self::titleAttrib( $name, 'withaccess' ),
2274 'accesskey' => self::accesskey( $name )
2275 );
2276 if ( $attribs['title'] === false ) {
2277 unset( $attribs['title'] );
2278 }
2279 if ( $attribs['accesskey'] === false ) {
2280 unset( $attribs['accesskey'] );
2281 }
2282 return $attribs;
2283 }
2284
2285 /**
2286 * Returns raw bits of HTML, use titleAttrib()
2287 * @return null|string
2288 */
2289 public static function tooltip( $name, $options = null ) {
2290 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2291 # no attribute" instead of "output '' as value for attribute", this
2292 # would be two lines.
2293 $tooltip = self::titleAttrib( $name, $options );
2294 if ( $tooltip === false ) {
2295 return '';
2296 }
2297 return Xml::expandAttributes( array(
2298 'title' => $tooltip
2299 ) );
2300 }
2301 }
2302
2303 /**
2304 * @since 1.18
2305 */
2306 class DummyLinker {
2307
2308 /**
2309 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2310 * into static calls to the new Linker for backwards compatibility.
2311 *
2312 * @param $fname String Name of called method
2313 * @param $args Array Arguments to the method
2314 * @return mixed
2315 */
2316 public function __call( $fname, $args ) {
2317 return call_user_func_array( array( 'Linker', $fname ), $args );
2318 }
2319 }