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