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