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