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