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