Follow-up I47412b67 (dde8471): convert string query to array
[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 ) + $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 = '' ) {
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 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
704 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
705 } elseif ( !empty( $frameParams['no-link'] ) ) {
706 // No link
707 } else {
708 $mtoParams['desc-link'] = true;
709 $mtoParams['desc-query'] = $query;
710 }
711 return $mtoParams;
712 }
713
714 /**
715 * Make HTML for a thumbnail including image, border and caption
716 * @param $title Title object
717 * @param $file File object or false if it doesn't exist
718 * @param $label String
719 * @param $alt String
720 * @param $align String
721 * @param $params Array
722 * @param $framed Boolean
723 * @param $manualthumb String
724 * @return mixed
725 */
726 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
727 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
728 {
729 $frameParams = array(
730 'alt' => $alt,
731 'caption' => $label,
732 'align' => $align
733 );
734 if ( $framed ) {
735 $frameParams['framed'] = true;
736 }
737 if ( $manualthumb ) {
738 $frameParams['manualthumb'] = $manualthumb;
739 }
740 return self::makeThumbLink2( $title, $file, $frameParams, $params );
741 }
742
743 /**
744 * @param $title Title
745 * @param $file File
746 * @param array $frameParams
747 * @param array $handlerParams
748 * @param bool $time
749 * @param string $query
750 * @return mixed
751 */
752 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
753 $handlerParams = array(), $time = false, $query = "" )
754 {
755 global $wgStylePath, $wgContLang;
756 $exists = $file && $file->exists();
757
758 # Shortcuts
759 $fp =& $frameParams;
760 $hp =& $handlerParams;
761
762 $page = isset( $hp['page'] ) ? $hp['page'] : false;
763 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
764 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
765 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
766 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
767
768 if ( empty( $hp['width'] ) ) {
769 // Reduce width for upright images when parameter 'upright' is used
770 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
771 }
772 $thumb = false;
773
774 if ( !$exists ) {
775 $outerWidth = $hp['width'] + 2;
776 } else {
777 if ( isset( $fp['manualthumb'] ) ) {
778 # Use manually specified thumbnail
779 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
780 if ( $manual_title ) {
781 $manual_img = wfFindFile( $manual_title );
782 if ( $manual_img ) {
783 $thumb = $manual_img->getUnscaledThumb( $hp );
784 } else {
785 $exists = false;
786 }
787 }
788 } elseif ( isset( $fp['framed'] ) ) {
789 // Use image dimensions, don't scale
790 $thumb = $file->getUnscaledThumb( $hp );
791 } else {
792 # Do not present an image bigger than the source, for bitmap-style images
793 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
794 $srcWidth = $file->getWidth( $page );
795 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
796 $hp['width'] = $srcWidth;
797 }
798 $thumb = $file->transform( $hp );
799 }
800
801 if ( $thumb ) {
802 $outerWidth = $thumb->getWidth() + 2;
803 } else {
804 $outerWidth = $hp['width'] + 2;
805 }
806 }
807
808 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
809 # So we don't need to pass it here in $query. However, the URL for the
810 # zoom icon still needs it, so we make a unique query for it. See bug 14771
811 $url = $title->getLocalURL( $query );
812 if ( $page ) {
813 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
814 }
815
816 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
817 if ( !$exists ) {
818 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
819 $zoomIcon = '';
820 } elseif ( !$thumb ) {
821 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
822 $zoomIcon = '';
823 } else {
824 $params = array(
825 'alt' => $fp['alt'],
826 'title' => $fp['title'],
827 'img-class' => 'thumbimage' );
828 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
829 $s .= $thumb->toHtml( $params );
830 if ( isset( $fp['framed'] ) ) {
831 $zoomIcon = "";
832 } else {
833 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
834 Html::rawElement( 'a', array(
835 'href' => $url,
836 'class' => 'internal',
837 'title' => wfMsg( 'thumbnail-more' ) ),
838 Html::element( 'img', array(
839 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
840 'width' => 15,
841 'height' => 11,
842 'alt' => "" ) ) ) );
843 }
844 }
845 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
846 return str_replace( "\n", ' ', $s );
847 }
848
849 /**
850 * Make a "broken" link to an image
851 *
852 * @param $title Title object
853 * @param $html String: link label in htmlescaped text form
854 * @param $query String: query string
855 * @param $trail String: link trail (HTML fragment)
856 * @param $prefix String: link prefix (HTML fragment)
857 * @param $time Boolean: a file of a certain timestamp was requested
858 * @return String
859 */
860 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
861 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
862 if ( ! $title instanceof Title ) {
863 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
864 }
865 wfProfileIn( __METHOD__ );
866 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
867
868 list( $inside, $trail ) = self::splitTrail( $trail );
869 if ( $html == '' )
870 $html = htmlspecialchars( $title->getPrefixedText() );
871
872 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
873 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
874
875 if ( $redir ) {
876 wfProfileOut( __METHOD__ );
877 return self::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
878 }
879
880 $href = self::getUploadUrl( $title, $query );
881
882 wfProfileOut( __METHOD__ );
883 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
884 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
885 "$prefix$html$inside</a>$trail";
886 } else {
887 wfProfileOut( __METHOD__ );
888 return self::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
889 }
890 }
891
892 /**
893 * Get the URL to upload a certain file
894 *
895 * @param $destFile Title object of the file to upload
896 * @param $query String: urlencoded query string to prepend
897 * @return String: urlencoded URL
898 */
899 protected static function getUploadUrl( $destFile, $query = '' ) {
900 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
901 $q = 'wpDestFile=' . $destFile->getPartialUrl();
902 if ( $query != '' )
903 $q .= '&' . $query;
904
905 if ( $wgUploadMissingFileUrl ) {
906 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
907 } elseif( $wgUploadNavigationUrl ) {
908 return wfAppendQuery( $wgUploadNavigationUrl, $q );
909 } else {
910 $upload = SpecialPage::getTitleFor( 'Upload' );
911 return $upload->getLocalUrl( $q );
912 }
913 }
914
915 /**
916 * Create a direct link to a given uploaded file.
917 *
918 * @param $title Title object.
919 * @param $html String: pre-sanitized HTML
920 * @param $time string: MW timestamp of file creation time
921 * @return String: HTML
922 */
923 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
924 $img = wfFindFile( $title, array( 'time' => $time ) );
925 return self::makeMediaLinkFile( $title, $img, $html );
926 }
927
928 /**
929 * Create a direct link to a given uploaded file.
930 * This will make a broken link if $file is false.
931 *
932 * @param $title Title object.
933 * @param $file File|bool mixed File object or false
934 * @param $html String: pre-sanitized HTML
935 * @return String: HTML
936 *
937 * @todo Handle invalid or missing images better.
938 */
939 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
940 if ( $file && $file->exists() ) {
941 $url = $file->getURL();
942 $class = 'internal';
943 } else {
944 $url = self::getUploadUrl( $title );
945 $class = 'new';
946 }
947 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
948 if ( $html == '' ) {
949 $html = $alt;
950 }
951 $u = htmlspecialchars( $url );
952 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
953 }
954
955 /**
956 * Make a link to a special page given its name and, optionally,
957 * a message key from the link text.
958 * Usage example: Linker::specialLink( 'Recentchanges' )
959 *
960 * @return string
961 */
962 public static function specialLink( $name, $key = '' ) {
963 if ( $key == '' ) {
964 $key = strtolower( $name );
965 }
966
967 return self::linkKnown( SpecialPage::getTitleFor( $name ) , wfMsg( $key ) );
968 }
969
970 /**
971 * Make an external link
972 * @param $url String: URL to link to
973 * @param $text String: text of link
974 * @param $escape Boolean: do we escape the link text?
975 * @param $linktype String: type of external link. Gets added to the classes
976 * @param $attribs Array of extra attributes to <a>
977 * @return string
978 */
979 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
980 $class = "external";
981 if ( $linktype ) {
982 $class .= " $linktype";
983 }
984 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
985 $class .= " {$attribs['class']}";
986 }
987 $attribs['class'] = $class;
988
989 if ( $escape ) {
990 $text = htmlspecialchars( $text );
991 }
992 $link = '';
993 $success = wfRunHooks( 'LinkerMakeExternalLink',
994 array( &$url, &$text, &$link, &$attribs, $linktype ) );
995 if ( !$success ) {
996 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
997 return $link;
998 }
999 $attribs['href'] = $url;
1000 return Html::rawElement( 'a', $attribs, $text );
1001 }
1002
1003 /**
1004 * Make user link (or user contributions for unregistered users)
1005 * @param $userId Integer: user id in database.
1006 * @param $userName String: user name in database.
1007 * @param $altUserName String: text to display instead of the user name (optional)
1008 * @return String: HTML fragment
1009 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1010 */
1011 public static function userLink( $userId, $userName, $altUserName = false ) {
1012 if ( $userId == 0 ) {
1013 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1014 } else {
1015 $page = Title::makeTitle( NS_USER, $userName );
1016 }
1017
1018 return self::link(
1019 $page,
1020 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1021 array( 'class' => 'mw-userlink' )
1022 );
1023 }
1024
1025 /**
1026 * Generate standard user tool links (talk, contributions, block link, etc.)
1027 *
1028 * @param $userId Integer: user identifier
1029 * @param $userText String: user name or IP address
1030 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1031 * red if the user has no edits?
1032 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1033 * @param $edits Integer: user edit count (optional, for performance)
1034 * @return String: HTML fragment
1035 */
1036 public static function userToolLinks(
1037 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1038 ) {
1039 global $wgUser, $wgDisableAnonTalk, $wgLang;
1040 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1041 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1042 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1043
1044 $items = array();
1045 if ( $talkable ) {
1046 $items[] = self::userTalkLink( $userId, $userText );
1047 }
1048 if ( $userId ) {
1049 // check if the user has an edit
1050 $attribs = array();
1051 if ( $redContribsWhenNoEdits ) {
1052 $count = !is_null( $edits ) ? $edits : User::edits( $userId );
1053 if ( $count == 0 ) {
1054 $attribs['class'] = 'new';
1055 }
1056 }
1057 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1058
1059 $items[] = self::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1060 }
1061 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1062 $items[] = self::blockLink( $userId, $userText );
1063 }
1064
1065 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1066 $items[] = self::emailLink( $userId, $userText );
1067 }
1068
1069 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1070
1071 if ( $items ) {
1072 return wfMessage( 'word-separator' )->plain()
1073 . '<span class="mw-usertoollinks">'
1074 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1075 . '</span>';
1076 } else {
1077 return '';
1078 }
1079 }
1080
1081 /**
1082 * Alias for userToolLinks( $userId, $userText, true );
1083 * @param $userId Integer: user identifier
1084 * @param $userText String: user name or IP address
1085 * @param $edits Integer: user edit count (optional, for performance)
1086 * @return String
1087 */
1088 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1089 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1090 }
1091
1092
1093 /**
1094 * @param $userId Integer: user id in database.
1095 * @param $userText String: user name in database.
1096 * @return String: HTML fragment with user talk link
1097 */
1098 public static function userTalkLink( $userId, $userText ) {
1099 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1100 $userTalkLink = self::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1101 return $userTalkLink;
1102 }
1103
1104 /**
1105 * @param $userId Integer: userid
1106 * @param $userText String: user name in database.
1107 * @return String: HTML fragment with block link
1108 */
1109 public static function blockLink( $userId, $userText ) {
1110 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1111 $blockLink = self::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1112 return $blockLink;
1113 }
1114
1115 /**
1116 * @param $userId Integer: userid
1117 * @param $userText String: user name in database.
1118 * @return String: HTML fragment with e-mail user link
1119 */
1120 public static function emailLink( $userId, $userText ) {
1121 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1122 $emailLink = self::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1123 return $emailLink;
1124 }
1125
1126 /**
1127 * Generate a user link if the current user is allowed to view it
1128 * @param $rev Revision object.
1129 * @param $isPublic Boolean: show only if all users can see it
1130 * @return String: HTML fragment
1131 */
1132 public static function revUserLink( $rev, $isPublic = false ) {
1133 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1134 $link = wfMsgHtml( 'rev-deleted-user' );
1135 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1136 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1137 $rev->getUserText( Revision::FOR_THIS_USER ) );
1138 } else {
1139 $link = wfMsgHtml( 'rev-deleted-user' );
1140 }
1141 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1142 return '<span class="history-deleted">' . $link . '</span>';
1143 }
1144 return $link;
1145 }
1146
1147 /**
1148 * Generate a user tool link cluster if the current user is allowed to view it
1149 * @param $rev Revision object.
1150 * @param $isPublic Boolean: show only if all users can see it
1151 * @return string HTML
1152 */
1153 public static function revUserTools( $rev, $isPublic = false ) {
1154 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1155 $link = wfMsgHtml( 'rev-deleted-user' );
1156 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1157 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1158 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1159 $link = self::userLink( $userId, $userText )
1160 . wfMessage( 'word-separator' )->plain()
1161 . self::userToolLinks( $userId, $userText );
1162 } else {
1163 $link = wfMsgHtml( 'rev-deleted-user' );
1164 }
1165 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1166 return ' <span class="history-deleted">' . $link . '</span>';
1167 }
1168 return $link;
1169 }
1170
1171 /**
1172 * This function is called by all recent changes variants, by the page history,
1173 * and by the user contributions list. It is responsible for formatting edit
1174 * comments. It escapes any HTML in the comment, but adds some CSS to format
1175 * auto-generated comments (from section editing) and formats [[wikilinks]].
1176 *
1177 * @author Erik Moeller <moeller@scireview.de>
1178 *
1179 * Note: there's not always a title to pass to this function.
1180 * Since you can't set a default parameter for a reference, I've turned it
1181 * temporarily to a value pass. Should be adjusted further. --brion
1182 *
1183 * @param $comment String
1184 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1185 * @param $local Boolean: whether section links should refer to local page
1186 * @return mixed|String
1187 */
1188 public static function formatComment( $comment, $title = null, $local = false ) {
1189 wfProfileIn( __METHOD__ );
1190
1191 # Sanitize text a bit:
1192 $comment = str_replace( "\n", " ", $comment );
1193 # Allow HTML entities (for bug 13815)
1194 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1195
1196 # Render autocomments and make links:
1197 $comment = self::formatAutocomments( $comment, $title, $local );
1198 $comment = self::formatLinksInComment( $comment, $title, $local );
1199
1200 wfProfileOut( __METHOD__ );
1201 return $comment;
1202 }
1203
1204 /**
1205 * @var Title
1206 */
1207 static $autocommentTitle;
1208 static $autocommentLocal;
1209
1210 /**
1211 * The pattern for autogen comments is / * foo * /, which makes for
1212 * some nasty regex.
1213 * We look for all comments, match any text before and after the comment,
1214 * add a separator where needed and format the comment itself with CSS
1215 * Called by Linker::formatComment.
1216 *
1217 * @param $comment String: comment text
1218 * @param $title Title|null An optional title object used to links to sections
1219 * @param $local Boolean: whether section links should refer to local page
1220 * @return String: formatted comment
1221 */
1222 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1223 // Bah!
1224 self::$autocommentTitle = $title;
1225 self::$autocommentLocal = $local;
1226 $comment = preg_replace_callback(
1227 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1228 array( 'Linker', 'formatAutocommentsCallback' ),
1229 $comment );
1230 self::$autocommentTitle = null;
1231 self::$autocommentLocal = null;
1232 return $comment;
1233 }
1234
1235 /**
1236 * @param $match
1237 * @return string
1238 */
1239 private static function formatAutocommentsCallback( $match ) {
1240 global $wgLang;
1241 $title = self::$autocommentTitle;
1242 $local = self::$autocommentLocal;
1243
1244 $pre = $match[1];
1245 $auto = $match[2];
1246 $post = $match[3];
1247 $comment = null;
1248 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1249 if ( $comment === null ) {
1250 $link = '';
1251 if ( $title ) {
1252 $section = $auto;
1253
1254 # Remove links that a user may have manually put in the autosummary
1255 # This could be improved by copying as much of Parser::stripSectionName as desired.
1256 $section = str_replace( '[[:', '', $section );
1257 $section = str_replace( '[[', '', $section );
1258 $section = str_replace( ']]', '', $section );
1259
1260 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1261 if ( $local ) {
1262 $sectionTitle = Title::newFromText( '#' . $section );
1263 } else {
1264 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1265 $title->getDBkey(), $section );
1266 }
1267 if ( $sectionTitle ) {
1268 $link = self::link( $sectionTitle,
1269 $wgLang->getArrow(), array(), array(),
1270 'noclasses' );
1271 } else {
1272 $link = '';
1273 }
1274 }
1275 if ( $pre ) {
1276 # written summary $presep autocomment (summary /* section */)
1277 $pre .= wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) );
1278 }
1279 if ( $post ) {
1280 # autocomment $postsep written summary (/* section */ summary)
1281 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1282 }
1283 $auto = '<span class="autocomment">' . $auto . '</span>';
1284 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1285 }
1286 return $comment;
1287 }
1288
1289 /**
1290 * @var Title
1291 */
1292 static $commentContextTitle;
1293 static $commentLocal;
1294
1295 /**
1296 * Formats wiki links and media links in text; all other wiki formatting
1297 * is ignored
1298 *
1299 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1300 * @param $comment String: text to format links in
1301 * @param $title Title|null An optional title object used to links to sections
1302 * @param $local Boolean: whether section links should refer to local page
1303 * @return String
1304 */
1305 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1306 self::$commentContextTitle = $title;
1307 self::$commentLocal = $local;
1308 $html = preg_replace_callback(
1309 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1310 array( 'Linker', 'formatLinksInCommentCallback' ),
1311 $comment );
1312 self::$commentContextTitle = null;
1313 self::$commentLocal = null;
1314 return $html;
1315 }
1316
1317 /**
1318 * @param $match
1319 * @return mixed
1320 */
1321 protected static function formatLinksInCommentCallback( $match ) {
1322 global $wgContLang;
1323
1324 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1325 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1326
1327 $comment = $match[0];
1328
1329 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1330 if ( strpos( $match[1], '%' ) !== false ) {
1331 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1332 }
1333
1334 # Handle link renaming [[foo|text]] will show link as "text"
1335 if ( $match[3] != "" ) {
1336 $text = $match[3];
1337 } else {
1338 $text = $match[1];
1339 }
1340 $submatch = array();
1341 $thelink = null;
1342 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1343 # Media link; trail not supported.
1344 $linkRegexp = '/\[\[(.*?)\]\]/';
1345 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1346 if ( $title ) {
1347 $thelink = self::makeMediaLinkObj( $title, $text );
1348 }
1349 } else {
1350 # Other kind of link
1351 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1352 $trail = $submatch[1];
1353 } else {
1354 $trail = "";
1355 }
1356 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1357 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1358 $match[1] = substr( $match[1], 1 );
1359 list( $inside, $trail ) = self::splitTrail( $trail );
1360
1361 $linkText = $text;
1362 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1363 $match[1], $linkText );
1364
1365 $target = Title::newFromText( $linkTarget );
1366 if ( $target ) {
1367 if ( $target->getText() == '' && $target->getInterwiki() === ''
1368 && !self::$commentLocal && self::$commentContextTitle )
1369 {
1370 $newTarget = clone ( self::$commentContextTitle );
1371 $newTarget->setFragment( '#' . $target->getFragment() );
1372 $target = $newTarget;
1373 }
1374 $thelink = self::link(
1375 $target,
1376 $linkText . $inside
1377 ) . $trail;
1378 }
1379 }
1380 if ( $thelink ) {
1381 // If the link is still valid, go ahead and replace it in!
1382 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1383 }
1384
1385 return $comment;
1386 }
1387
1388 /**
1389 * @param $contextTitle Title
1390 * @param $target
1391 * @param $text
1392 * @return string
1393 */
1394 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1395 # Valid link forms:
1396 # Foobar -- normal
1397 # :Foobar -- override special treatment of prefix (images, language links)
1398 # /Foobar -- convert to CurrentPage/Foobar
1399 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1400 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1401 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1402
1403 wfProfileIn( __METHOD__ );
1404 $ret = $target; # default return value is no change
1405
1406 # Some namespaces don't allow subpages,
1407 # so only perform processing if subpages are allowed
1408 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1409 $hash = strpos( $target, '#' );
1410 if ( $hash !== false ) {
1411 $suffix = substr( $target, $hash );
1412 $target = substr( $target, 0, $hash );
1413 } else {
1414 $suffix = '';
1415 }
1416 # bug 7425
1417 $target = trim( $target );
1418 # Look at the first character
1419 if ( $target != '' && $target[0] === '/' ) {
1420 # / at end means we don't want the slash to be shown
1421 $m = array();
1422 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1423 if ( $trailingSlashes ) {
1424 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1425 } else {
1426 $noslash = substr( $target, 1 );
1427 }
1428
1429 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1430 if ( $text === '' ) {
1431 $text = $target . $suffix;
1432 } # this might be changed for ugliness reasons
1433 } else {
1434 # check for .. subpage backlinks
1435 $dotdotcount = 0;
1436 $nodotdot = $target;
1437 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1438 ++$dotdotcount;
1439 $nodotdot = substr( $nodotdot, 3 );
1440 }
1441 if ( $dotdotcount > 0 ) {
1442 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1443 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1444 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1445 # / at the end means don't show full path
1446 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1447 $nodotdot = substr( $nodotdot, 0, -1 );
1448 if ( $text === '' ) {
1449 $text = $nodotdot . $suffix;
1450 }
1451 }
1452 $nodotdot = trim( $nodotdot );
1453 if ( $nodotdot != '' ) {
1454 $ret .= '/' . $nodotdot;
1455 }
1456 $ret .= $suffix;
1457 }
1458 }
1459 }
1460 }
1461
1462 wfProfileOut( __METHOD__ );
1463 return $ret;
1464 }
1465
1466 /**
1467 * Wrap a comment in standard punctuation and formatting if
1468 * it's non-empty, otherwise return empty string.
1469 *
1470 * @param $comment String
1471 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1472 * @param $local Boolean: whether section links should refer to local page
1473 *
1474 * @return string
1475 */
1476 public static function commentBlock( $comment, $title = null, $local = false ) {
1477 // '*' used to be the comment inserted by the software way back
1478 // in antiquity in case none was provided, here for backwards
1479 // compatability, acc. to brion -ævar
1480 if ( $comment == '' || $comment == '*' ) {
1481 return '';
1482 } else {
1483 $formatted = self::formatComment( $comment, $title, $local );
1484 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1485 return " <span class=\"comment\">$formatted</span>";
1486 }
1487 }
1488
1489 /**
1490 * Wrap and format the given revision's comment block, if the current
1491 * user is allowed to view it.
1492 *
1493 * @param $rev Revision object
1494 * @param $local Boolean: whether section links should refer to local page
1495 * @param $isPublic Boolean: show only if all users can see it
1496 * @return String: HTML fragment
1497 */
1498 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1499 if ( $rev->getRawComment() == "" ) {
1500 return "";
1501 }
1502 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1503 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1504 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1505 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1506 $rev->getTitle(), $local );
1507 } else {
1508 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1509 }
1510 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1511 return " <span class=\"history-deleted\">$block</span>";
1512 }
1513 return $block;
1514 }
1515
1516 /**
1517 * @param $size
1518 * @return string
1519 */
1520 public static function formatRevisionSize( $size ) {
1521 if ( $size == 0 ) {
1522 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1523 } else {
1524 global $wgLang;
1525 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1526 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1527 }
1528 $stxt = htmlspecialchars( $stxt );
1529 return "<span class=\"history-size\">$stxt</span>";
1530 }
1531
1532 /**
1533 * Add another level to the Table of Contents
1534 *
1535 * @return string
1536 */
1537 public static function tocIndent() {
1538 return "\n<ul>";
1539 }
1540
1541 /**
1542 * Finish one or more sublevels on the Table of Contents
1543 *
1544 * @return string
1545 */
1546 public static function tocUnindent( $level ) {
1547 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1548 }
1549
1550 /**
1551 * parameter level defines if we are on an indentation level
1552 *
1553 * @return string
1554 */
1555 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1556 $classes = "toclevel-$level";
1557 if ( $sectionIndex !== false ) {
1558 $classes .= " tocsection-$sectionIndex";
1559 }
1560 return "\n<li class=\"$classes\"><a href=\"#" .
1561 $anchor . '"><span class="tocnumber">' .
1562 $tocnumber . '</span> <span class="toctext">' .
1563 $tocline . '</span></a>';
1564 }
1565
1566 /**
1567 * End a Table Of Contents line.
1568 * tocUnindent() will be used instead if we're ending a line below
1569 * the new level.
1570 * @return string
1571 */
1572 public static function tocLineEnd() {
1573 return "</li>\n";
1574 }
1575
1576 /**
1577 * Wraps the TOC in a table and provides the hide/collapse javascript.
1578 *
1579 * @param $toc String: html of the Table Of Contents
1580 * @param $lang mixed: Language code for the toc title
1581 * @return String: full html of the TOC
1582 */
1583 public static function tocList( $toc, $lang = false ) {
1584 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1585 return
1586 '<table id="toc" class="toc"><tr><td>'
1587 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1588 . $toc
1589 . "</ul>\n</td></tr></table>\n";
1590 }
1591
1592 /**
1593 * Generate a table of contents from a section tree
1594 * Currently unused.
1595 *
1596 * @param $tree array Return value of ParserOutput::getSections()
1597 * @return String: HTML fragment
1598 */
1599 public static function generateTOC( $tree ) {
1600 $toc = '';
1601 $lastLevel = 0;
1602 foreach ( $tree as $section ) {
1603 if ( $section['toclevel'] > $lastLevel )
1604 $toc .= self::tocIndent();
1605 elseif ( $section['toclevel'] < $lastLevel )
1606 $toc .= self::tocUnindent(
1607 $lastLevel - $section['toclevel'] );
1608 else
1609 $toc .= self::tocLineEnd();
1610
1611 $toc .= self::tocLine( $section['anchor'],
1612 $section['line'], $section['number'],
1613 $section['toclevel'], $section['index'] );
1614 $lastLevel = $section['toclevel'];
1615 }
1616 $toc .= self::tocLineEnd();
1617 return self::tocList( $toc );
1618 }
1619
1620 /**
1621 * Create a headline for content
1622 *
1623 * @param $level Integer: the level of the headline (1-6)
1624 * @param $attribs String: any attributes for the headline, starting with
1625 * a space and ending with '>'
1626 * This *must* be at least '>' for no attribs
1627 * @param $anchor String: the anchor to give the headline (the bit after the #)
1628 * @param $html String: html for the text of the header
1629 * @param $link String: HTML to add for the section edit link
1630 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1631 * backward compatibility (false to omit)
1632 *
1633 * @return String: HTML headline
1634 */
1635 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1636 $ret = "<h$level$attribs"
1637 . $link
1638 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1639 . "</h$level>";
1640 if ( $legacyAnchor !== false ) {
1641 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1642 }
1643 return $ret;
1644 }
1645
1646 /**
1647 * Split a link trail, return the "inside" portion and the remainder of the trail
1648 * as a two-element array
1649 * @return array
1650 */
1651 static function splitTrail( $trail ) {
1652 global $wgContLang;
1653 $regex = $wgContLang->linkTrail();
1654 $inside = '';
1655 if ( $trail !== '' ) {
1656 $m = array();
1657 if ( preg_match( $regex, $trail, $m ) ) {
1658 $inside = $m[1];
1659 $trail = $m[2];
1660 }
1661 }
1662 return array( $inside, $trail );
1663 }
1664
1665 /**
1666 * Generate a rollback link for a given revision. Currently it's the
1667 * caller's responsibility to ensure that the revision is the top one. If
1668 * it's not, of course, the user will get an error message.
1669 *
1670 * If the calling page is called with the parameter &bot=1, all rollback
1671 * links also get that parameter. It causes the edit itself and the rollback
1672 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1673 * changes, so this allows sysops to combat a busy vandal without bothering
1674 * other users.
1675 *
1676 * @param $rev Revision object
1677 * @param $context IContextSource context to use or null for the main context.
1678 * @return string
1679 */
1680 public static function generateRollback( $rev, IContextSource $context = null ) {
1681 if ( $context === null ) {
1682 $context = RequestContext::getMain();
1683 }
1684
1685 return '<span class="mw-rollback-link">'
1686 . $context->msg( 'brackets' )->rawParams(
1687 self::buildRollbackLink( $rev, $context ) )->plain()
1688 . '</span>';
1689 }
1690
1691 /**
1692 * Build a raw rollback link, useful for collections of "tool" links
1693 *
1694 * @param $rev Revision object
1695 * @param $context IContextSource context to use or null for the main context.
1696 * @return String: HTML fragment
1697 */
1698 public static function buildRollbackLink( $rev, IContextSource $context = null ) {
1699 global $wgShowRollbackEditCount, $wgMiserMode;
1700
1701 // To config which pages are effected by miser mode
1702 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1703
1704 if ( $context === null ) {
1705 $context = RequestContext::getMain();
1706 }
1707
1708 $title = $rev->getTitle();
1709 $query = array(
1710 'action' => 'rollback',
1711 'from' => $rev->getUserText(),
1712 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1713 );
1714 if ( $context->getRequest()->getBool( 'bot' ) ) {
1715 $query['bot'] = '1';
1716 $query['hidediff'] = '1'; // bug 15999
1717 }
1718
1719 $disableRollbackEditCount = false;
1720 if( $wgMiserMode ) {
1721 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1722 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1723 $disableRollbackEditCount = true;
1724 break;
1725 }
1726 }
1727 }
1728
1729 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1730 $dbr = wfGetDB( DB_SLAVE );
1731
1732 // Up to the value of $wgShowRollbackEditCount revisions are counted
1733 $res = $dbr->select( 'revision',
1734 array( 'rev_id', 'rev_user_text' ),
1735 // $rev->getPage() returns null sometimes
1736 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1737 __METHOD__,
1738 array( 'USE INDEX' => 'page_timestamp',
1739 'ORDER BY' => 'rev_timestamp DESC',
1740 'LIMIT' => $wgShowRollbackEditCount + 1 )
1741 );
1742
1743 $editCount = 0;
1744 while( $row = $dbr->fetchObject( $res ) ) {
1745 if( $rev->getUserText() != $row->rev_user_text ) {
1746 break;
1747 }
1748 $editCount++;
1749 }
1750
1751 if( $editCount > $wgShowRollbackEditCount ) {
1752 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1753 } else {
1754 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1755 }
1756
1757 return self::link(
1758 $title,
1759 $editCount_output,
1760 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1761 $query,
1762 array( 'known', 'noclasses' )
1763 );
1764 } else {
1765 return self::link(
1766 $title,
1767 $context->msg( 'rollbacklink' )->escaped(),
1768 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1769 $query,
1770 array( 'known', 'noclasses' )
1771 );
1772 }
1773 }
1774
1775 /**
1776 * Returns HTML for the "templates used on this page" list.
1777 *
1778 * @param $templates Array of templates from Article::getUsedTemplate
1779 * or similar
1780 * @param $preview Boolean: whether this is for a preview
1781 * @param $section Boolean: whether this is for a section edit
1782 * @return String: HTML output
1783 */
1784 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1785 wfProfileIn( __METHOD__ );
1786
1787 $outText = '';
1788 if ( count( $templates ) > 0 ) {
1789 # Do a batch existence check
1790 $batch = new LinkBatch;
1791 foreach ( $templates as $title ) {
1792 $batch->addObj( $title );
1793 }
1794 $batch->execute();
1795
1796 # Construct the HTML
1797 $outText = '<div class="mw-templatesUsedExplanation">';
1798 if ( $preview ) {
1799 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1800 } elseif ( $section ) {
1801 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1802 } else {
1803 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1804 }
1805 $outText .= "</div><ul>\n";
1806
1807 usort( $templates, 'Title::compare' );
1808 foreach ( $templates as $titleObj ) {
1809 $r = $titleObj->getRestrictions( 'edit' );
1810 if ( in_array( 'sysop', $r ) ) {
1811 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1812 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1813 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1814 } else {
1815 $protected = '';
1816 }
1817 if ( $titleObj->quickUserCan( 'edit' ) ) {
1818 $editLink = self::link(
1819 $titleObj,
1820 wfMsg( 'editlink' ),
1821 array(),
1822 array( 'action' => 'edit' )
1823 );
1824 } else {
1825 $editLink = self::link(
1826 $titleObj,
1827 wfMsg( 'viewsourcelink' ),
1828 array(),
1829 array( 'action' => 'edit' )
1830 );
1831 }
1832 $outText .= '<li>' . self::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1833 }
1834 $outText .= '</ul>';
1835 }
1836 wfProfileOut( __METHOD__ );
1837 return $outText;
1838 }
1839
1840 /**
1841 * Returns HTML for the "hidden categories on this page" list.
1842 *
1843 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1844 * or similar
1845 * @return String: HTML output
1846 */
1847 public static function formatHiddenCategories( $hiddencats ) {
1848 global $wgLang;
1849 wfProfileIn( __METHOD__ );
1850
1851 $outText = '';
1852 if ( count( $hiddencats ) > 0 ) {
1853 # Construct the HTML
1854 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1855 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1856 $outText .= "</div><ul>\n";
1857
1858 foreach ( $hiddencats as $titleObj ) {
1859 $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
1860 }
1861 $outText .= '</ul>';
1862 }
1863 wfProfileOut( __METHOD__ );
1864 return $outText;
1865 }
1866
1867 /**
1868 * Format a size in bytes for output, using an appropriate
1869 * unit (B, KB, MB or GB) according to the magnitude in question
1870 *
1871 * @param $size int Size to format
1872 * @return String
1873 */
1874 public static function formatSize( $size ) {
1875 global $wgLang;
1876 return htmlspecialchars( $wgLang->formatSize( $size ) );
1877 }
1878
1879 /**
1880 * Given the id of an interface element, constructs the appropriate title
1881 * attribute from the system messages. (Note, this is usually the id but
1882 * isn't always, because sometimes the accesskey needs to go on a different
1883 * element than the id, for reverse-compatibility, etc.)
1884 *
1885 * @param $name String: id of the element, minus prefixes.
1886 * @param $options Mixed: null or the string 'withaccess' to add an access-
1887 * key hint
1888 * @return String: contents of the title attribute (which you must HTML-
1889 * escape), or false for no title attribute
1890 */
1891 public static function titleAttrib( $name, $options = null ) {
1892 wfProfileIn( __METHOD__ );
1893
1894 $message = wfMessage( "tooltip-$name" );
1895
1896 if ( !$message->exists() ) {
1897 $tooltip = false;
1898 } else {
1899 $tooltip = $message->text();
1900 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1901 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1902 # Message equal to '-' means suppress it.
1903 if ( $tooltip == '-' ) {
1904 $tooltip = false;
1905 }
1906 }
1907
1908 if ( $options == 'withaccess' ) {
1909 $accesskey = self::accesskey( $name );
1910 if ( $accesskey !== false ) {
1911 if ( $tooltip === false || $tooltip === '' ) {
1912 $tooltip = "[$accesskey]";
1913 } else {
1914 $tooltip .= " [$accesskey]";
1915 }
1916 }
1917 }
1918
1919 wfProfileOut( __METHOD__ );
1920 return $tooltip;
1921 }
1922
1923 static $accesskeycache;
1924
1925 /**
1926 * Given the id of an interface element, constructs the appropriate
1927 * accesskey attribute from the system messages. (Note, this is usually
1928 * the id but isn't always, because sometimes the accesskey needs to go on
1929 * a different element than the id, for reverse-compatibility, etc.)
1930 *
1931 * @param $name String: id of the element, minus prefixes.
1932 * @return String: contents of the accesskey attribute (which you must HTML-
1933 * escape), or false for no accesskey attribute
1934 */
1935 public static function accesskey( $name ) {
1936 if ( isset( self::$accesskeycache[$name] ) ) {
1937 return self::$accesskeycache[$name];
1938 }
1939 wfProfileIn( __METHOD__ );
1940
1941 $message = wfMessage( "accesskey-$name" );
1942
1943 if ( !$message->exists() ) {
1944 $accesskey = false;
1945 } else {
1946 $accesskey = $message->plain();
1947 if ( $accesskey === '' || $accesskey === '-' ) {
1948 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1949 # attribute, but this is broken for accesskey: that might be a useful
1950 # value.
1951 $accesskey = false;
1952 }
1953 }
1954
1955 wfProfileOut( __METHOD__ );
1956 return self::$accesskeycache[$name] = $accesskey;
1957 }
1958
1959 /**
1960 * Get a revision-deletion link, or disabled link, or nothing, depending
1961 * on user permissions & the settings on the revision.
1962 *
1963 * Will use forward-compatible revision ID in the Special:RevDelete link
1964 * if possible, otherwise the timestamp-based ID which may break after
1965 * undeletion.
1966 *
1967 * @param User $user
1968 * @param Revision $rev
1969 * @param Revision $title
1970 * @return string HTML fragment
1971 */
1972 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
1973 $canHide = $user->isAllowed( 'deleterevision' );
1974 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1975 return '';
1976 }
1977
1978 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
1979 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1980 } else {
1981 if ( $rev->getId() ) {
1982 // RevDelete links using revision ID are stable across
1983 // page deletion and undeletion; use when possible.
1984 $query = array(
1985 'type' => 'revision',
1986 'target' => $title->getPrefixedDBkey(),
1987 'ids' => $rev->getId()
1988 );
1989 } else {
1990 // Older deleted entries didn't save a revision ID.
1991 // We have to refer to these by timestamp, ick!
1992 $query = array(
1993 'type' => 'archive',
1994 'target' => $title->getPrefixedDBkey(),
1995 'ids' => $rev->getTimestamp()
1996 );
1997 }
1998 return Linker::revDeleteLink( $query,
1999 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2000 }
2001 }
2002
2003 /**
2004 * Creates a (show/hide) link for deleting revisions/log entries
2005 *
2006 * @param $query Array: query parameters to be passed to link()
2007 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2008 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2009 *
2010 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2011 * span to allow for customization of appearance with CSS
2012 */
2013 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2014 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2015 $html = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
2016 $tag = $restricted ? 'strong' : 'span';
2017 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2018 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2019 }
2020
2021 /**
2022 * Creates a dead (show/hide) link for deleting revisions/log entries
2023 *
2024 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2025 *
2026 * @return string HTML text wrapped in a span to allow for customization
2027 * of appearance with CSS
2028 */
2029 public static function revDeleteLinkDisabled( $delete = true ) {
2030 $html = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
2031 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $html )->escaped() );
2032 }
2033
2034 /* Deprecated methods */
2035
2036 /**
2037 * @deprecated since 1.16 Use link()
2038 *
2039 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2040 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2041 *
2042 * @param $title String: The text of the title
2043 * @param $text String: Link text
2044 * @param $query String: Optional query part
2045 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2046 * be included in the link text. Other characters will be appended after
2047 * the end of the link.
2048 * @return string
2049 */
2050 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2051 wfDeprecated( __METHOD__, '1.16' );
2052
2053 $nt = Title::newFromText( $title );
2054 if ( $nt instanceof Title ) {
2055 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2056 } else {
2057 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2058 return $text == '' ? $title : $text;
2059 }
2060 }
2061
2062 /**
2063 * @deprecated since 1.16 Use link()
2064 *
2065 * Make a link for a title which may or may not be in the database. If you need to
2066 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2067 * call to this will result in a DB query.
2068 *
2069 * @param $nt Title: the title object to make the link from, e.g. from
2070 * Title::newFromText.
2071 * @param $text String: link text
2072 * @param $query String: optional query part
2073 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2074 * be included in the link text. Other characters will be appended after
2075 * the end of the link.
2076 * @param $prefix String: optional prefix. As trail, only before instead of after.
2077 * @return string
2078 */
2079 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2080 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2081
2082 wfProfileIn( __METHOD__ );
2083 $query = wfCgiToArray( $query );
2084 list( $inside, $trail ) = self::splitTrail( $trail );
2085 if ( $text === '' ) {
2086 $text = self::linkText( $nt );
2087 }
2088
2089 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2090
2091 wfProfileOut( __METHOD__ );
2092 return $ret;
2093 }
2094
2095 /**
2096 * @deprecated since 1.16 Use link()
2097 *
2098 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2099 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2100 * pages.
2101 *
2102 * @param $title Title object of target page
2103 * @param $text String: text to replace the title
2104 * @param $query String: link target
2105 * @param $trail String: text after link
2106 * @param $prefix String: text before link text
2107 * @param $aprops String: extra attributes to the a-element
2108 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2109 * @return string the a-element
2110 */
2111 static function makeKnownLinkObj(
2112 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
2113 ) {
2114 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2115
2116 wfProfileIn( __METHOD__ );
2117
2118 if ( $text == '' ) {
2119 $text = self::linkText( $title );
2120 }
2121 $attribs = Sanitizer::mergeAttributes(
2122 Sanitizer::decodeTagAttributes( $aprops ),
2123 Sanitizer::decodeTagAttributes( $style )
2124 );
2125 $query = wfCgiToArray( $query );
2126 list( $inside, $trail ) = self::splitTrail( $trail );
2127
2128 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2129 array( 'known', 'noclasses' ) ) . $trail;
2130
2131 wfProfileOut( __METHOD__ );
2132 return $ret;
2133 }
2134
2135 /**
2136 * @deprecated since 1.16 Use link()
2137 *
2138 * Make a red link to the edit page of a given title.
2139 *
2140 * @param $title Title object of the target page
2141 * @param $text String: Link text
2142 * @param $query String: Optional query part
2143 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2144 * be included in the link text. Other characters will be appended after
2145 * the end of the link.
2146 * @param $prefix String: Optional prefix
2147 * @return string
2148 */
2149 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2150 wfDeprecated( __METHOD__, '1.16' );
2151
2152 wfProfileIn( __METHOD__ );
2153
2154 list( $inside, $trail ) = self::splitTrail( $trail );
2155 if ( $text === '' ) {
2156 $text = self::linkText( $title );
2157 }
2158
2159 $ret = self::link( $title, "$prefix$text$inside", array(),
2160 wfCgiToArray( $query ), 'broken' ) . $trail;
2161
2162 wfProfileOut( __METHOD__ );
2163 return $ret;
2164 }
2165
2166 /**
2167 * @deprecated since 1.16 Use link()
2168 *
2169 * Make a coloured link.
2170 *
2171 * @param $nt Title object of the target page
2172 * @param $colour Integer: colour of the link
2173 * @param $text String: link text
2174 * @param $query String: optional query part
2175 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2176 * be included in the link text. Other characters will be appended after
2177 * the end of the link.
2178 * @param $prefix String: Optional prefix
2179 * @return string
2180 */
2181 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2182 wfDeprecated( __METHOD__, '1.16' );
2183
2184 if ( $colour != '' ) {
2185 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2186 } else {
2187 $style = '';
2188 }
2189 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2190 }
2191
2192 /**
2193 * Returns the attributes for the tooltip and access key.
2194 * @return array
2195 */
2196 public static function tooltipAndAccesskeyAttribs( $name ) {
2197 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2198 # no attribute" instead of "output '' as value for attribute", this
2199 # would be three lines.
2200 $attribs = array(
2201 'title' => self::titleAttrib( $name, 'withaccess' ),
2202 'accesskey' => self::accesskey( $name )
2203 );
2204 if ( $attribs['title'] === false ) {
2205 unset( $attribs['title'] );
2206 }
2207 if ( $attribs['accesskey'] === false ) {
2208 unset( $attribs['accesskey'] );
2209 }
2210 return $attribs;
2211 }
2212
2213 /**
2214 * Returns raw bits of HTML, use titleAttrib()
2215 * @return null|string
2216 */
2217 public static function tooltip( $name, $options = null ) {
2218 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2219 # no attribute" instead of "output '' as value for attribute", this
2220 # would be two lines.
2221 $tooltip = self::titleAttrib( $name, $options );
2222 if ( $tooltip === false ) {
2223 return '';
2224 }
2225 return Xml::expandAttributes( array(
2226 'title' => $tooltip
2227 ) );
2228 }
2229 }
2230
2231 /**
2232 * @since 1.18
2233 */
2234 class DummyLinker {
2235
2236 /**
2237 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2238 * into static calls to the new Linker for backwards compatibility.
2239 *
2240 * @param $fname String Name of called method
2241 * @param $args Array Arguments to the method
2242 * @return mixed
2243 */
2244 public function __call( $fname, $args ) {
2245 return call_user_func_array( array( 'Linker', $fname ), $args );
2246 }
2247 }