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