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