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