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