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