Embrace comment with () only when really needed. In Special:ListFiles and ImagePage...
[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 ) = SpecialPageFactory::resolveAlias( $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 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
766 }
767 }
768
769 /**
770 * Get the URL to upload a certain file
771 *
772 * @param $destFile Title object of the file to upload
773 * @param $query String: urlencoded query string to prepend
774 * @return String: urlencoded URL
775 */
776 protected static function getUploadUrl( $destFile, $query = '' ) {
777 global $wgUploadMissingFileUrl;
778 $q = 'wpDestFile=' . $destFile->getPartialUrl();
779 if ( $query != '' )
780 $q .= '&' . $query;
781
782 if ( $wgUploadMissingFileUrl ) {
783 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
784 } else {
785 $upload = SpecialPage::getTitleFor( 'Upload' );
786 return $upload->getLocalUrl( $q );
787 }
788 }
789
790 /**
791 * Create a direct link to a given uploaded file.
792 *
793 * @param $title Title object.
794 * @param $text String: pre-sanitized HTML
795 * @param $time string: MW timestamp of file creation time
796 * @return String: HTML
797 */
798 public static function makeMediaLinkObj( $title, $text = '', $time = false ) {
799 $img = wfFindFile( $title, array( 'time' => $time ) );
800 return self::makeMediaLinkFile( $title, $img, $text );
801 }
802
803 /**
804 * Create a direct link to a given uploaded file.
805 * This will make a broken link if $file is false.
806 *
807 * @param $title Title object.
808 * @param $file mixed File object or false
809 * @param $text String: pre-sanitized HTML
810 * @return String: HTML
811 *
812 * @todo Handle invalid or missing images better.
813 */
814 public static function makeMediaLinkFile( Title $title, $file, $text = '' ) {
815 if ( $file && $file->exists() ) {
816 $url = $file->getURL();
817 $class = 'internal';
818 } else {
819 $url = self::getUploadUrl( $title );
820 $class = 'new';
821 }
822 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
823 if ( $text == '' ) {
824 $text = $alt;
825 }
826 $u = htmlspecialchars( $url );
827 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
828 }
829
830 /**
831 * Make a link to a special page given its name and, optionally,
832 * a message key from the link text.
833 * Usage example: $skin->specialLink( 'recentchanges' )
834 */
835 static function specialLink( $name, $key = '' ) {
836 if ( $key == '' ) { $key = strtolower( $name ); }
837
838 return self::linkKnown( SpecialPage::getTitleFor( $name ) , wfMsg( $key ) );
839 }
840
841 /**
842 * Make an external link
843 * @param $url String: URL to link to
844 * @param $text String: text of link
845 * @param $escape Boolean: do we escape the link text?
846 * @param $linktype String: type of external link. Gets added to the classes
847 * @param $attribs Array of extra attributes to <a>
848 */
849 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
850 $class = "external";
851 if ( isset($linktype) && $linktype ) {
852 $class .= " $linktype";
853 }
854 if ( isset($attribs['class']) && $attribs['class'] ) {
855 $class .= " {$attribs['class']}";
856 }
857 $attribs['class'] = $class;
858
859 if ( $escape ) {
860 $text = htmlspecialchars( $text );
861 }
862 $link = '';
863 $success = wfRunHooks( 'LinkerMakeExternalLink',
864 array( &$url, &$text, &$link, &$attribs, $linktype ) );
865 if ( !$success ) {
866 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
867 return $link;
868 }
869 $attribs['href'] = $url;
870 return Html::rawElement( 'a', $attribs, $text );
871 }
872
873 /**
874 * Make user link (or user contributions for unregistered users)
875 * @param $userId Integer: user id in database.
876 * @param $userText String: user name in database
877 * @return String: HTML fragment
878 * @private
879 */
880 static function userLink( $userId, $userText ) {
881 if ( $userId == 0 ) {
882 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
883 } else {
884 $page = Title::makeTitle( NS_USER, $userText );
885 }
886 return self::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
887 }
888
889 /**
890 * Generate standard user tool links (talk, contributions, block link, etc.)
891 *
892 * @param $userId Integer: user identifier
893 * @param $userText String: user name or IP address
894 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
895 * red if the user has no edits?
896 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK)
897 * @param $edits Integer: user edit count (optional, for performance)
898 * @return String: HTML fragment
899 */
900 public static function userToolLinks(
901 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
902 ) {
903 global $wgUser, $wgDisableAnonTalk, $wgLang;
904 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
905 $blockable = !$flags & self::TOOL_LINKS_NOBLOCK;
906
907 $items = array();
908 if ( $talkable ) {
909 $items[] = self::userTalkLink( $userId, $userText );
910 }
911 if ( $userId ) {
912 // check if the user has an edit
913 $attribs = array();
914 if ( $redContribsWhenNoEdits ) {
915 $count = !is_null( $edits ) ? $edits : User::edits( $userId );
916 if ( $count == 0 ) {
917 $attribs['class'] = 'new';
918 }
919 }
920 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
921
922 $items[] = self::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
923 }
924 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
925 $items[] = self::blockLink( $userId, $userText );
926 }
927
928 if ( $items ) {
929 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
930 } else {
931 return '';
932 }
933 }
934
935 /**
936 * Alias for userToolLinks( $userId, $userText, true );
937 * @param $userId Integer: user identifier
938 * @param $userText String: user name or IP address
939 * @param $edits Integer: user edit count (optional, for performance)
940 */
941 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
942 return self::userToolLinks( $userId, $userText, true, 0, $edits );
943 }
944
945
946 /**
947 * @param $userId Integer: user id in database.
948 * @param $userText String: user name in database.
949 * @return String: HTML fragment with user talk link
950 * @private
951 */
952 static function userTalkLink( $userId, $userText ) {
953 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
954 $userTalkLink = self::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
955 return $userTalkLink;
956 }
957
958 /**
959 * @param $userId Integer: userid
960 * @param $userText String: user name in database.
961 * @return String: HTML fragment with block link
962 * @private
963 */
964 static function blockLink( $userId, $userText ) {
965 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
966 $blockLink = self::link( $blockPage, wfMsgHtml( 'blocklink' ) );
967 return $blockLink;
968 }
969
970 /**
971 * Generate a user link if the current user is allowed to view it
972 * @param $rev Revision object.
973 * @param $isPublic Boolean: show only if all users can see it
974 * @return String: HTML fragment
975 */
976 static function revUserLink( $rev, $isPublic = false ) {
977 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
978 $link = wfMsgHtml( 'rev-deleted-user' );
979 } else if ( $rev->userCan( Revision::DELETED_USER ) ) {
980 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
981 $rev->getUserText( Revision::FOR_THIS_USER ) );
982 } else {
983 $link = wfMsgHtml( 'rev-deleted-user' );
984 }
985 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
986 return '<span class="history-deleted">' . $link . '</span>';
987 }
988 return $link;
989 }
990
991 /**
992 * Generate a user tool link cluster if the current user is allowed to view it
993 * @param $rev Revision object.
994 * @param $isPublic Boolean: show only if all users can see it
995 * @return string HTML
996 */
997 static function revUserTools( $rev, $isPublic = false ) {
998 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
999 $link = wfMsgHtml( 'rev-deleted-user' );
1000 } else if ( $rev->userCan( Revision::DELETED_USER ) ) {
1001 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1002 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1003 $link = self::userLink( $userId, $userText ) .
1004 ' ' . self::userToolLinks( $userId, $userText );
1005 } else {
1006 $link = wfMsgHtml( 'rev-deleted-user' );
1007 }
1008 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1009 return ' <span class="history-deleted">' . $link . '</span>';
1010 }
1011 return $link;
1012 }
1013
1014 /**
1015 * This function is called by all recent changes variants, by the page history,
1016 * and by the user contributions list. It is responsible for formatting edit
1017 * comments. It escapes any HTML in the comment, but adds some CSS to format
1018 * auto-generated comments (from section editing) and formats [[wikilinks]].
1019 *
1020 * @author Erik Moeller <moeller@scireview.de>
1021 *
1022 * Note: there's not always a title to pass to this function.
1023 * Since you can't set a default parameter for a reference, I've turned it
1024 * temporarily to a value pass. Should be adjusted further. --brion
1025 *
1026 * @param $comment String
1027 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1028 * @param $local Boolean: whether section links should refer to local page
1029 */
1030 static function formatComment( $comment, $title = null, $local = false ) {
1031 wfProfileIn( __METHOD__ );
1032
1033 # Sanitize text a bit:
1034 $comment = str_replace( "\n", " ", $comment );
1035 # Allow HTML entities (for bug 13815)
1036 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1037
1038 # Render autocomments and make links:
1039 $comment = self::formatAutocomments( $comment, $title, $local );
1040 $comment = self::formatLinksInComment( $comment, $title, $local );
1041
1042 wfProfileOut( __METHOD__ );
1043 return $comment;
1044 }
1045
1046 static $autocommentTitle;
1047 static $autocommentLocal;
1048
1049 /**
1050 * The pattern for autogen comments is / * foo * /, which makes for
1051 * some nasty regex.
1052 * We look for all comments, match any text before and after the comment,
1053 * add a separator where needed and format the comment itself with CSS
1054 * Called by Linker::formatComment.
1055 *
1056 * @param $comment String: comment text
1057 * @param $title An optional title object used to links to sections
1058 * @param $local Boolean: whether section links should refer to local page
1059 * @return String: formatted comment
1060 */
1061 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1062 // Bah!
1063 self::$autocommentTitle = $title;
1064 self::$autocommentLocal = $local;
1065 $comment = preg_replace_callback(
1066 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1067 array( 'Linker', 'formatAutocommentsCallback' ),
1068 $comment );
1069 self::$autocommentTitle = null;
1070 self::$autocommentLocal = null;
1071 return $comment;
1072 }
1073
1074 private static function formatAutocommentsCallback( $match ) {
1075 $title = self::$autocommentTitle;
1076 $local = self::$autocommentLocal;
1077
1078 $pre = $match[1];
1079 $auto = $match[2];
1080 $post = $match[3];
1081 $link = '';
1082 if ( $title ) {
1083 $section = $auto;
1084
1085 # Remove links that a user may have manually put in the autosummary
1086 # This could be improved by copying as much of Parser::stripSectionName as desired.
1087 $section = str_replace( '[[:', '', $section );
1088 $section = str_replace( '[[', '', $section );
1089 $section = str_replace( ']]', '', $section );
1090
1091 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1092 if ( $local ) {
1093 $sectionTitle = Title::newFromText( '#' . $section );
1094 } else {
1095 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1096 $title->getDBkey(), $section );
1097 }
1098 if ( $sectionTitle ) {
1099 $link = self::link( $sectionTitle,
1100 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1101 'noclasses' );
1102 } else {
1103 $link = '';
1104 }
1105 }
1106 $auto = "$link$auto";
1107 if ( $pre ) {
1108 # written summary $presep autocomment (summary /* section */)
1109 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1110 }
1111 if ( $post ) {
1112 # autocomment $postsep written summary (/* section */ summary)
1113 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1114 }
1115 $auto = '<span class="autocomment">' . $auto . '</span>';
1116 $comment = $pre . $auto . $post;
1117 return $comment;
1118 }
1119
1120 static $commentContextTitle;
1121 static $commentLocal;
1122
1123 /**
1124 * Formats wiki links and media links in text; all other wiki formatting
1125 * is ignored
1126 *
1127 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1128 * @param $comment String: text to format links in
1129 * @param $title An optional title object used to links to sections
1130 * @param $local Boolean: whether section links should refer to local page
1131 * @return String
1132 */
1133 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1134 self::$commentContextTitle = $title;
1135 self::$commentLocal = $local;
1136 $html = preg_replace_callback(
1137 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1138 array( 'Linker', 'formatLinksInCommentCallback' ),
1139 $comment );
1140 self::$commentContextTitle = null;
1141 self::$commentLocal = null;
1142 return $html;
1143 }
1144
1145 protected static function formatLinksInCommentCallback( $match ) {
1146 global $wgContLang;
1147
1148 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1149 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1150
1151 $comment = $match[0];
1152
1153 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1154 if ( strpos( $match[1], '%' ) !== false ) {
1155 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1156 }
1157
1158 # Handle link renaming [[foo|text]] will show link as "text"
1159 if ( $match[3] != "" ) {
1160 $text = $match[3];
1161 } else {
1162 $text = $match[1];
1163 }
1164 $submatch = array();
1165 $thelink = null;
1166 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1167 # Media link; trail not supported.
1168 $linkRegexp = '/\[\[(.*?)\]\]/';
1169 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1170 $thelink = self::makeMediaLinkObj( $title, $text );
1171 } else {
1172 # Other kind of link
1173 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1174 $trail = $submatch[1];
1175 } else {
1176 $trail = "";
1177 }
1178 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1179 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1180 $match[1] = substr( $match[1], 1 );
1181 list( $inside, $trail ) = self::splitTrail( $trail );
1182
1183 $linkText = $text;
1184 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1185 $match[1], $linkText );
1186
1187 $target = Title::newFromText( $linkTarget );
1188 if ( $target ) {
1189 if ( $target->getText() == '' && $target->getInterwiki() === ''
1190 && !self::$commentLocal && self::$commentContextTitle )
1191 {
1192 $newTarget = clone ( self::$commentContextTitle );
1193 $newTarget->setFragment( '#' . $target->getFragment() );
1194 $target = $newTarget;
1195 }
1196 $thelink = self::link(
1197 $target,
1198 $linkText . $inside
1199 ) . $trail;
1200 }
1201 }
1202 if ( $thelink ) {
1203 // If the link is still valid, go ahead and replace it in!
1204 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1205 }
1206
1207 return $comment;
1208 }
1209
1210 /**
1211 * @param $contextTitle Title
1212 * @param $target
1213 * @param $text
1214 * @return string
1215 */
1216 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1217 # Valid link forms:
1218 # Foobar -- normal
1219 # :Foobar -- override special treatment of prefix (images, language links)
1220 # /Foobar -- convert to CurrentPage/Foobar
1221 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1222 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1223 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1224
1225 wfProfileIn( __METHOD__ );
1226 $ret = $target; # default return value is no change
1227
1228 # Some namespaces don't allow subpages,
1229 # so only perform processing if subpages are allowed
1230 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1231 $hash = strpos( $target, '#' );
1232 if ( $hash !== false ) {
1233 $suffix = substr( $target, $hash );
1234 $target = substr( $target, 0, $hash );
1235 } else {
1236 $suffix = '';
1237 }
1238 # bug 7425
1239 $target = trim( $target );
1240 # Look at the first character
1241 if ( $target != '' && $target { 0 } === '/' ) {
1242 # / at end means we don't want the slash to be shown
1243 $m = array();
1244 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1245 if ( $trailingSlashes ) {
1246 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1247 } else {
1248 $noslash = substr( $target, 1 );
1249 }
1250
1251 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1252 if ( $text === '' ) {
1253 $text = $target . $suffix;
1254 } # this might be changed for ugliness reasons
1255 } else {
1256 # check for .. subpage backlinks
1257 $dotdotcount = 0;
1258 $nodotdot = $target;
1259 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1260 ++$dotdotcount;
1261 $nodotdot = substr( $nodotdot, 3 );
1262 }
1263 if ( $dotdotcount > 0 ) {
1264 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1265 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1266 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1267 # / at the end means don't show full path
1268 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1269 $nodotdot = substr( $nodotdot, 0, -1 );
1270 if ( $text === '' ) {
1271 $text = $nodotdot . $suffix;
1272 }
1273 }
1274 $nodotdot = trim( $nodotdot );
1275 if ( $nodotdot != '' ) {
1276 $ret .= '/' . $nodotdot;
1277 }
1278 $ret .= $suffix;
1279 }
1280 }
1281 }
1282 }
1283
1284 wfProfileOut( __METHOD__ );
1285 return $ret;
1286 }
1287
1288 /**
1289 * Wrap a comment in standard punctuation and formatting if
1290 * it's non-empty, otherwise return empty string.
1291 *
1292 * @param $comment String
1293 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1294 * @param $local Boolean: whether section links should refer to local page
1295 * @param $embraced Boolean: whether the formatted comment should be embraced with ()
1296 * @return string
1297 */
1298 static function commentBlock( $comment, $title = null, $local = false, $embraced = true ) {
1299 // '*' used to be the comment inserted by the software way back
1300 // in antiquity in case none was provided, here for backwards
1301 // compatability, acc. to brion -ævar
1302 if ( $comment == '' || $comment == '*' ) {
1303 return '';
1304 } else {
1305 $formatted = self::formatComment( $comment, $title, $local );
1306 if ( $embraced ) {
1307 $formatted = wfMessage( 'parentheses', $formatted );
1308 }
1309 return Html::rawElement( 'span', array( 'class' => 'comment' ), $formatted );
1310 }
1311 }
1312
1313 /**
1314 * Wrap and format the given revision's comment block, if the current
1315 * user is allowed to view it.
1316 *
1317 * @param $rev Revision object
1318 * @param $local Boolean: whether section links should refer to local page
1319 * @param $isPublic Boolean: show only if all users can see it
1320 * @return String: HTML fragment
1321 */
1322 static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1323 if ( $rev->getRawComment() == "" ) {
1324 return "";
1325 }
1326 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1327 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1328 } else if ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1329 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1330 $rev->getTitle(), $local );
1331 } else {
1332 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1333 }
1334 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1335 return " <span class=\"history-deleted\">$block</span>";
1336 }
1337 return $block;
1338 }
1339
1340 public static function formatRevisionSize( $size ) {
1341 if ( $size == 0 ) {
1342 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1343 } else {
1344 global $wgLang;
1345 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1346 $stxt = "($stxt)";
1347 }
1348 $stxt = htmlspecialchars( $stxt );
1349 return "<span class=\"history-size\">$stxt</span>";
1350 }
1351
1352 /**
1353 * Add another level to the Table of Contents
1354 */
1355 static function tocIndent() {
1356 return "\n<ul>";
1357 }
1358
1359 /**
1360 * Finish one or more sublevels on the Table of Contents
1361 */
1362 static function tocUnindent( $level ) {
1363 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1364 }
1365
1366 /**
1367 * parameter level defines if we are on an indentation level
1368 */
1369 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1370 $classes = "toclevel-$level";
1371 if ( $sectionIndex !== false )
1372 $classes .= " tocsection-$sectionIndex";
1373 return "\n<li class=\"$classes\"><a href=\"#" .
1374 $anchor . '"><span class="tocnumber">' .
1375 $tocnumber . '</span> <span class="toctext">' .
1376 $tocline . '</span></a>';
1377 }
1378
1379 /**
1380 * End a Table Of Contents line.
1381 * tocUnindent() will be used instead if we're ending a line below
1382 * the new level.
1383 */
1384 static function tocLineEnd() {
1385 return "</li>\n";
1386 }
1387
1388 /**
1389 * Wraps the TOC in a table and provides the hide/collapse javascript.
1390 *
1391 * @param $toc String: html of the Table Of Contents
1392 * @param $lang mixed: Language code for the toc title
1393 * @return String: full html of the TOC
1394 */
1395 static function tocList( $toc, $lang = false ) {
1396 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1397 return
1398 '<table id="toc" class="toc"><tr><td>'
1399 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1400 . $toc
1401 . "</ul>\n</td></tr></table>\n";
1402 }
1403
1404 /**
1405 * Generate a table of contents from a section tree
1406 * Currently unused.
1407 *
1408 * @param $tree Return value of ParserOutput::getSections()
1409 * @return String: HTML fragment
1410 */
1411 public static function generateTOC( $tree ) {
1412 $toc = '';
1413 $lastLevel = 0;
1414 foreach ( $tree as $section ) {
1415 if ( $section['toclevel'] > $lastLevel )
1416 $toc .= self::tocIndent();
1417 else if ( $section['toclevel'] < $lastLevel )
1418 $toc .= self::tocUnindent(
1419 $lastLevel - $section['toclevel'] );
1420 else
1421 $toc .= self::tocLineEnd();
1422
1423 $toc .= self::tocLine( $section['anchor'],
1424 $section['line'], $section['number'],
1425 $section['toclevel'], $section['index'] );
1426 $lastLevel = $section['toclevel'];
1427 }
1428 $toc .= self::tocLineEnd();
1429 return self::tocList( $toc );
1430 }
1431
1432 /**
1433 * Create a headline for content
1434 *
1435 * @param $level Integer: the level of the headline (1-6)
1436 * @param $attribs String: any attributes for the headline, starting with
1437 * a space and ending with '>'
1438 * This *must* be at least '>' for no attribs
1439 * @param $anchor String: the anchor to give the headline (the bit after the #)
1440 * @param $text String: the text of the header
1441 * @param $link String: HTML to add for the section edit link
1442 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1443 * backward compatibility (false to omit)
1444 *
1445 * @return String: HTML headline
1446 */
1447 public static function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1448 $ret = "<h$level$attribs"
1449 . $link
1450 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1451 . "</h$level>";
1452 if ( $legacyAnchor !== false ) {
1453 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1454 }
1455 return $ret;
1456 }
1457
1458 /**
1459 * Split a link trail, return the "inside" portion and the remainder of the trail
1460 * as a two-element array
1461 */
1462 static function splitTrail( $trail ) {
1463 global $wgContLang;
1464 $regex = $wgContLang->linkTrail();
1465 $inside = '';
1466 if ( $trail !== '' ) {
1467 $m = array();
1468 if ( preg_match( $regex, $trail, $m ) ) {
1469 $inside = $m[1];
1470 $trail = $m[2];
1471 }
1472 }
1473 return array( $inside, $trail );
1474 }
1475
1476 /**
1477 * Generate a rollback link for a given revision. Currently it's the
1478 * caller's responsibility to ensure that the revision is the top one. If
1479 * it's not, of course, the user will get an error message.
1480 *
1481 * If the calling page is called with the parameter &bot=1, all rollback
1482 * links also get that parameter. It causes the edit itself and the rollback
1483 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1484 * changes, so this allows sysops to combat a busy vandal without bothering
1485 * other users.
1486 *
1487 * @param $rev Revision object
1488 */
1489 static function generateRollback( $rev ) {
1490 return '<span class="mw-rollback-link">['
1491 . self::buildRollbackLink( $rev )
1492 . ']</span>';
1493 }
1494
1495 /**
1496 * Build a raw rollback link, useful for collections of "tool" links
1497 *
1498 * @param $rev Revision object
1499 * @return String: HTML fragment
1500 */
1501 public static function buildRollbackLink( $rev ) {
1502 global $wgRequest, $wgUser;
1503 $title = $rev->getTitle();
1504 $query = array(
1505 'action' => 'rollback',
1506 'from' => $rev->getUserText(),
1507 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1508 );
1509 if ( $wgRequest->getBool( 'bot' ) ) {
1510 $query['bot'] = '1';
1511 $query['hidediff'] = '1'; // bug 15999
1512 }
1513 return self::link(
1514 $title,
1515 wfMsgHtml( 'rollbacklink' ),
1516 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1517 $query,
1518 array( 'known', 'noclasses' )
1519 );
1520 }
1521
1522 /**
1523 * Returns HTML for the "templates used on this page" list.
1524 *
1525 * @param $templates Array of templates from Article::getUsedTemplate
1526 * or similar
1527 * @param $preview Boolean: whether this is for a preview
1528 * @param $section Boolean: whether this is for a section edit
1529 * @return String: HTML output
1530 */
1531 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1532 wfProfileIn( __METHOD__ );
1533
1534 $outText = '';
1535 if ( count( $templates ) > 0 ) {
1536 # Do a batch existence check
1537 $batch = new LinkBatch;
1538 foreach ( $templates as $title ) {
1539 $batch->addObj( $title );
1540 }
1541 $batch->execute();
1542
1543 # Construct the HTML
1544 $outText = '<div class="mw-templatesUsedExplanation">';
1545 if ( $preview ) {
1546 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1547 } elseif ( $section ) {
1548 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1549 } else {
1550 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1551 }
1552 $outText .= "</div><ul>\n";
1553
1554 usort( $templates, array( 'Title', 'compare' ) );
1555 foreach ( $templates as $titleObj ) {
1556 $r = $titleObj->getRestrictions( 'edit' );
1557 if ( in_array( 'sysop', $r ) ) {
1558 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1559 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1560 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1561 } else {
1562 $protected = '';
1563 }
1564 if ( $titleObj->quickUserCan( 'edit' ) ) {
1565 $editLink = self::link(
1566 $titleObj,
1567 wfMsg( 'editlink' ),
1568 array(),
1569 array( 'action' => 'edit' )
1570 );
1571 } else {
1572 $editLink = self::link(
1573 $titleObj,
1574 wfMsg( 'viewsourcelink' ),
1575 array(),
1576 array( 'action' => 'edit' )
1577 );
1578 }
1579 $outText .= '<li>' . self::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1580 }
1581 $outText .= '</ul>';
1582 }
1583 wfProfileOut( __METHOD__ );
1584 return $outText;
1585 }
1586
1587 /**
1588 * Returns HTML for the "hidden categories on this page" list.
1589 *
1590 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1591 * or similar
1592 * @return String: HTML output
1593 */
1594 public static function formatHiddenCategories( $hiddencats ) {
1595 global $wgLang;
1596 wfProfileIn( __METHOD__ );
1597
1598 $outText = '';
1599 if ( count( $hiddencats ) > 0 ) {
1600 # Construct the HTML
1601 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1602 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1603 $outText .= "</div><ul>\n";
1604
1605 foreach ( $hiddencats as $titleObj ) {
1606 $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
1607 }
1608 $outText .= '</ul>';
1609 }
1610 wfProfileOut( __METHOD__ );
1611 return $outText;
1612 }
1613
1614 /**
1615 * Format a size in bytes for output, using an appropriate
1616 * unit (B, KB, MB or GB) according to the magnitude in question
1617 *
1618 * @param $size Size to format
1619 * @return String
1620 */
1621 public static function formatSize( $size ) {
1622 global $wgLang;
1623 return htmlspecialchars( $wgLang->formatSize( $size ) );
1624 }
1625
1626 /**
1627 * Given the id of an interface element, constructs the appropriate title
1628 * attribute from the system messages. (Note, this is usually the id but
1629 * isn't always, because sometimes the accesskey needs to go on a different
1630 * element than the id, for reverse-compatibility, etc.)
1631 *
1632 * @param $name String: id of the element, minus prefixes.
1633 * @param $options Mixed: null or the string 'withaccess' to add an access-
1634 * key hint
1635 * @return String: contents of the title attribute (which you must HTML-
1636 * escape), or false for no title attribute
1637 */
1638 public static function titleAttrib( $name, $options = null ) {
1639 wfProfileIn( __METHOD__ );
1640
1641 $message = wfMessage( "tooltip-$name" );
1642
1643 if ( !$message->exists() ) {
1644 $tooltip = false;
1645 } else {
1646 $tooltip = $message->text();
1647 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1648 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1649 # Message equal to '-' means suppress it.
1650 if ( $tooltip == '-' ) {
1651 $tooltip = false;
1652 }
1653 }
1654
1655 if ( $options == 'withaccess' ) {
1656 $accesskey = self::accesskey( $name );
1657 if ( $accesskey !== false ) {
1658 if ( $tooltip === false || $tooltip === '' ) {
1659 $tooltip = "[$accesskey]";
1660 } else {
1661 $tooltip .= " [$accesskey]";
1662 }
1663 }
1664 }
1665
1666 wfProfileOut( __METHOD__ );
1667 return $tooltip;
1668 }
1669
1670 static $accesskeycache;
1671
1672 /**
1673 * Given the id of an interface element, constructs the appropriate
1674 * accesskey attribute from the system messages. (Note, this is usually
1675 * the id but isn't always, because sometimes the accesskey needs to go on
1676 * a different element than the id, for reverse-compatibility, etc.)
1677 *
1678 * @param $name String: id of the element, minus prefixes.
1679 * @return String: contents of the accesskey attribute (which you must HTML-
1680 * escape), or false for no accesskey attribute
1681 */
1682 public static function accesskey( $name ) {
1683 if ( isset( self::$accesskeycache[$name] ) ) {
1684 return self::$accesskeycache[$name];
1685 }
1686 wfProfileIn( __METHOD__ );
1687
1688 $message = wfMessage( "accesskey-$name" );
1689
1690 if ( !$message->exists() ) {
1691 $accesskey = false;
1692 } else {
1693 $accesskey = $message->plain();
1694 if ( $accesskey === '' || $accesskey === '-' ) {
1695 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1696 # attribute, but this is broken for accesskey: that might be a useful
1697 # value.
1698 $accesskey = false;
1699 }
1700 }
1701
1702 wfProfileOut( __METHOD__ );
1703 return self::$accesskeycache[$name] = $accesskey;
1704 }
1705
1706 /**
1707 * Creates a (show/hide) link for deleting revisions/log entries
1708 *
1709 * @param $query Array: query parameters to be passed to link()
1710 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1711 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1712 *
1713 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1714 * span to allow for customization of appearance with CSS
1715 */
1716 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1717 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1718 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1719 $tag = $restricted ? 'strong' : 'span';
1720 $link = self::link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1721 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1722 }
1723
1724 /**
1725 * Creates a dead (show/hide) link for deleting revisions/log entries
1726 *
1727 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1728 *
1729 * @return string HTML text wrapped in a span to allow for customization
1730 * of appearance with CSS
1731 */
1732 public static function revDeleteLinkDisabled( $delete = true ) {
1733 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1734 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1735 }
1736
1737 /* Deprecated methods */
1738
1739 /**
1740 * @deprecated since 1.16 Use link()
1741 *
1742 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1743 * it if you already have a title object handy. See makeLinkObj for further documentation.
1744 *
1745 * @param $title String: the text of the title
1746 * @param $text String: link text
1747 * @param $query String: optional query part
1748 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1749 * be included in the link text. Other characters will be appended after
1750 * the end of the link.
1751 */
1752 static function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1753 wfProfileIn( __METHOD__ );
1754 $nt = Title::newFromText( $title );
1755 if ( $nt instanceof Title ) {
1756 $result = self::makeLinkObj( $nt, $text, $query, $trail );
1757 } else {
1758 wfDebug( 'Invalid title passed to self::makeLink(): "' . $title . "\"\n" );
1759 $result = $text == "" ? $title : $text;
1760 }
1761
1762 wfProfileOut( __METHOD__ );
1763 return $result;
1764 }
1765
1766 /**
1767 * @deprecated since 1.16 Use link()
1768 *
1769 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1770 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1771 *
1772 * @param $title String: the text of the title
1773 * @param $text String: link text
1774 * @param $query String: optional query part
1775 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1776 * be included in the link text. Other characters will be appended after
1777 * the end of the link.
1778 * @param $prefix String: Optional prefix
1779 * @param $aprops String: extra attributes to the a-element
1780 */
1781 static function makeKnownLink(
1782 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = ''
1783 ) {
1784 $nt = Title::newFromText( $title );
1785 if ( $nt instanceof Title ) {
1786 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1787 } else {
1788 wfDebug( 'Invalid title passed to self::makeKnownLink(): "' . $title . "\"\n" );
1789 return $text == '' ? $title : $text;
1790 }
1791 }
1792
1793 /**
1794 * @deprecated since 1.16 Use link()
1795 *
1796 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1797 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1798 *
1799 * @param $title String: The text of the title
1800 * @param $text String: Link text
1801 * @param $query String: Optional query part
1802 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1803 * be included in the link text. Other characters will be appended after
1804 * the end of the link.
1805 */
1806 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1807 $nt = Title::newFromText( $title );
1808 if ( $nt instanceof Title ) {
1809 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
1810 } else {
1811 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1812 return $text == '' ? $title : $text;
1813 }
1814 }
1815
1816 /**
1817 * @deprecated since 1.16 Use link()
1818 *
1819 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1820 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1821 *
1822 * @param $title String: the text of the title
1823 * @param $text String: link text
1824 * @param $query String: optional query part
1825 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1826 * be included in the link text. Other characters will be appended after
1827 * the end of the link.
1828 */
1829 static function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1830 wfDeprecated( __METHOD__ );
1831 $nt = Title::newFromText( $title );
1832 if ( $nt instanceof Title ) {
1833 return self::makeStubLinkObj( $nt, $text, $query, $trail );
1834 } else {
1835 wfDebug( 'Invalid title passed to self::makeStubLink(): "' . $title . "\"\n" );
1836 return $text == '' ? $title : $text;
1837 }
1838 }
1839
1840 /**
1841 * @deprecated since 1.16 Use link()
1842 *
1843 * Make a link for a title which may or may not be in the database. If you need to
1844 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1845 * call to this will result in a DB query.
1846 *
1847 * @param $nt Title: the title object to make the link from, e.g. from
1848 * Title::newFromText.
1849 * @param $text String: link text
1850 * @param $query String: optional query part
1851 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1852 * be included in the link text. Other characters will be appended after
1853 * the end of the link.
1854 * @param $prefix String: optional prefix. As trail, only before instead of after.
1855 */
1856 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1857 wfProfileIn( __METHOD__ );
1858 $query = wfCgiToArray( $query );
1859 list( $inside, $trail ) = self::splitTrail( $trail );
1860 if ( $text === '' ) {
1861 $text = self::linkText( $nt );
1862 }
1863
1864 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1865
1866 wfProfileOut( __METHOD__ );
1867 return $ret;
1868 }
1869
1870 /**
1871 * @deprecated since 1.16 Use link()
1872 *
1873 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1874 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1875 * pages.
1876 *
1877 * @param $title Title object of target page
1878 * @param $text String: text to replace the title
1879 * @param $query String: link target
1880 * @param $trail String: text after link
1881 * @param $prefix String: text before link text
1882 * @param $aprops String: extra attributes to the a-element
1883 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1884 * @return the a-element
1885 */
1886 static function makeKnownLinkObj(
1887 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1888 ) {
1889 wfProfileIn( __METHOD__ );
1890
1891 if ( $text == '' ) {
1892 $text = self::linkText( $title );
1893 }
1894 $attribs = Sanitizer::mergeAttributes(
1895 Sanitizer::decodeTagAttributes( $aprops ),
1896 Sanitizer::decodeTagAttributes( $style )
1897 );
1898 $query = wfCgiToArray( $query );
1899 list( $inside, $trail ) = self::splitTrail( $trail );
1900
1901 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
1902 array( 'known', 'noclasses' ) ) . $trail;
1903
1904 wfProfileOut( __METHOD__ );
1905 return $ret;
1906 }
1907
1908 /**
1909 * @deprecated since 1.16 Use link()
1910 *
1911 * Make a red link to the edit page of a given title.
1912 *
1913 * @param $title Title object of the target page
1914 * @param $text String: Link text
1915 * @param $query String: Optional query part
1916 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1917 * be included in the link text. Other characters will be appended after
1918 * the end of the link.
1919 * @param $prefix String: Optional prefix
1920 */
1921 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1922 wfProfileIn( __METHOD__ );
1923
1924 list( $inside, $trail ) = self::splitTrail( $trail );
1925 if ( $text === '' ) {
1926 $text = self::linkText( $title );
1927 }
1928
1929 $ret = self::link( $title, "$prefix$text$inside", array(),
1930 wfCgiToArray( $query ), 'broken' ) . $trail;
1931
1932 wfProfileOut( __METHOD__ );
1933 return $ret;
1934 }
1935
1936 /**
1937 * @deprecated since 1.16 Use link()
1938 *
1939 * Make a brown link to a short article.
1940 *
1941 * @param $nt Title object of the target page
1942 * @param $text String: link text
1943 * @param $query String: optional query part
1944 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1945 * be included in the link text. Other characters will be appended after
1946 * the end of the link.
1947 * @param $prefix String: Optional prefix
1948 */
1949 static function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1950 return self::makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1951 }
1952
1953 /**
1954 * @deprecated since 1.16 Use link()
1955 *
1956 * Make a coloured link.
1957 *
1958 * @param $nt Title object of the target page
1959 * @param $colour Integer: colour of the link
1960 * @param $text String: link text
1961 * @param $query String: optional query part
1962 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1963 * be included in the link text. Other characters will be appended after
1964 * the end of the link.
1965 * @param $prefix String: Optional prefix
1966 */
1967 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1968 if ( $colour != '' ) {
1969 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
1970 } else {
1971 $style = '';
1972 }
1973 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1974 }
1975
1976 /** Obsolete alias */
1977 static function makeImage( $url, $alt = '' ) {
1978 wfDeprecated( __METHOD__ );
1979 return self::makeExternalImage( $url, $alt );
1980 }
1981
1982 /**
1983 * Creates the HTML source for images
1984 * @deprecated since 1.16 use makeImageLink2
1985 *
1986 * @param $title Title object
1987 * @param $label String: label text
1988 * @param $alt String: alt text
1989 * @param $align String: horizontal alignment: none, left, center, right)
1990 * @param $handlerParams Array: parameters to be passed to the media handler
1991 * @param $framed Boolean: shows image in original size in a frame
1992 * @param $thumb Boolean: shows image as thumbnail in a frame
1993 * @param $manualthumb String: image name for the manual thumbnail
1994 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
1995 * @param $time String: timestamp of the file, set as false for current
1996 * @return String
1997 */
1998 static function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(),
1999 $framed = false, $thumb = false, $manualthumb = '', $valign = '', $time = false )
2000 {
2001 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2002 if ( $align ) {
2003 $frameParams['align'] = $align;
2004 }
2005 if ( $framed ) {
2006 $frameParams['framed'] = true;
2007 }
2008 if ( $thumb ) {
2009 $frameParams['thumbnail'] = true;
2010 }
2011 if ( $manualthumb ) {
2012 $frameParams['manualthumb'] = $manualthumb;
2013 }
2014 if ( $valign ) {
2015 $frameParams['valign'] = $valign;
2016 }
2017 $file = wfFindFile( $title, array( 'time' => $time ) );
2018 return self::makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2019 }
2020
2021 /** @deprecated use Linker::makeMediaLinkObj() */
2022 static function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2023 $nt = Title::makeTitleSafe( NS_FILE, $name );
2024 return self::makeMediaLinkObj( $nt, $text, $time );
2025 }
2026
2027 /**
2028 * Returns the attributes for the tooltip and access key.
2029 */
2030 public static function tooltipAndAccesskeyAttribs( $name ) {
2031 global $wgEnableTooltipsAndAccesskeys;
2032 if ( !$wgEnableTooltipsAndAccesskeys )
2033 return array();
2034 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2035 # no attribute" instead of "output '' as value for attribute", this
2036 # would be three lines.
2037 $attribs = array(
2038 'title' => self::titleAttrib( $name, 'withaccess' ),
2039 'accesskey' => self::accesskey( $name )
2040 );
2041 if ( $attribs['title'] === false ) {
2042 unset( $attribs['title'] );
2043 }
2044 if ( $attribs['accesskey'] === false ) {
2045 unset( $attribs['accesskey'] );
2046 }
2047 return $attribs;
2048 }
2049
2050 /**
2051 * @deprecated since 1.14
2052 * Returns raw bits of HTML, use titleAttrib() and accesskey()
2053 */
2054 public static function tooltipAndAccesskey( $name ) {
2055 return Xml::expandAttributes( self::tooltipAndAccesskeyAttribs( $name ) );
2056 }
2057
2058 /**
2059 * @deprecated since 1.14
2060 * Returns raw bits of HTML, use titleAttrib()
2061 */
2062 public static function tooltip( $name, $options = null ) {
2063 global $wgEnableTooltipsAndAccesskeys;
2064 if ( !$wgEnableTooltipsAndAccesskeys )
2065 return '';
2066 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2067 # no attribute" instead of "output '' as value for attribute", this
2068 # would be two lines.
2069 $tooltip = self::titleAttrib( $name, $options );
2070 if ( $tooltip === false ) {
2071 return '';
2072 }
2073 return Xml::expandAttributes( array(
2074 'title' => self::titleAttrib( $name, $options )
2075 ) );
2076 }
2077 }
2078
2079 class DummyLinker {
2080
2081 /**
2082 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2083 * into static calls to the new Linker for backwards compatibility.
2084 *
2085 * @param $fname String Name of called method
2086 * @param $args Array Arguments to the method
2087 */
2088 function __call( $fname, $args ) {
2089 return call_user_func_array( array( 'Linker', $fname ), $args );
2090 }
2091
2092 }
2093