Fixed comments and indenting style from r68491.
[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;' ), urldecode( $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 );
1504 if ( $wgRequest->getBool( 'bot' ) ) {
1505 $query['bot'] = '1';
1506 $query['hidediff'] = '1'; // bug 15999
1507 }
1508 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1509 $rev->getUserText() ) );
1510 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1511 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1512 $query, array( 'known', 'noclasses' ) );
1513 }
1514
1515 /**
1516 * Returns HTML for the "templates used on this page" list.
1517 *
1518 * @param $templates Array of templates from Article::getUsedTemplate
1519 * or similar
1520 * @param $preview Boolean: whether this is for a preview
1521 * @param $section Boolean: whether this is for a section edit
1522 * @return String: HTML output
1523 */
1524 public function formatTemplates( $templates, $preview = false, $section = false ) {
1525 wfProfileIn( __METHOD__ );
1526
1527 $outText = '';
1528 if ( count( $templates ) > 0 ) {
1529 # Do a batch existence check
1530 $batch = new LinkBatch;
1531 foreach ( $templates as $title ) {
1532 $batch->addObj( $title );
1533 }
1534 $batch->execute();
1535
1536 # Construct the HTML
1537 $outText = '<div class="mw-templatesUsedExplanation">';
1538 if ( $preview ) {
1539 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1540 } elseif ( $section ) {
1541 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1542 } else {
1543 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1544 }
1545 $outText .= "</div><ul>\n";
1546
1547 usort( $templates, array( 'Title', 'compare' ) );
1548 foreach ( $templates as $titleObj ) {
1549 $r = $titleObj->getRestrictions( 'edit' );
1550 if ( in_array( 'sysop', $r ) ) {
1551 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1552 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1553 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1554 } else {
1555 $protected = '';
1556 }
1557 if ( $titleObj->quickUserCan( 'edit' ) ) {
1558 $editLink = $this->link(
1559 $titleObj,
1560 wfMsg( 'editlink' ),
1561 array(),
1562 array( 'action' => 'edit' )
1563 );
1564 } else {
1565 $editLink = $this->link(
1566 $titleObj,
1567 wfMsg( 'viewsourcelink' ),
1568 array(),
1569 array( 'action' => 'edit' )
1570 );
1571 }
1572 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1573 }
1574 $outText .= '</ul>';
1575 }
1576 wfProfileOut( __METHOD__ );
1577 return $outText;
1578 }
1579
1580 /**
1581 * Returns HTML for the "hidden categories on this page" list.
1582 *
1583 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1584 * or similar
1585 * @return String: HTML output
1586 */
1587 public function formatHiddenCategories( $hiddencats ) {
1588 global $wgLang;
1589 wfProfileIn( __METHOD__ );
1590
1591 $outText = '';
1592 if ( count( $hiddencats ) > 0 ) {
1593 # Construct the HTML
1594 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1595 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1596 $outText .= "</div><ul>\n";
1597
1598 foreach ( $hiddencats as $titleObj ) {
1599 $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
1600 }
1601 $outText .= '</ul>';
1602 }
1603 wfProfileOut( __METHOD__ );
1604 return $outText;
1605 }
1606
1607 /**
1608 * Format a size in bytes for output, using an appropriate
1609 * unit (B, KB, MB or GB) according to the magnitude in question
1610 *
1611 * @param $size Size to format
1612 * @return String
1613 */
1614 public function formatSize( $size ) {
1615 global $wgLang;
1616 return htmlspecialchars( $wgLang->formatSize( $size ) );
1617 }
1618
1619 /**
1620 * Given the id of an interface element, constructs the appropriate title
1621 * attribute from the system messages. (Note, this is usually the id but
1622 * isn't always, because sometimes the accesskey needs to go on a different
1623 * element than the id, for reverse-compatibility, etc.)
1624 *
1625 * @param $name String: id of the element, minus prefixes.
1626 * @param $options Mixed: null or the string 'withaccess' to add an access-
1627 * key hint
1628 * @return String: contents of the title attribute (which you must HTML-
1629 * escape), or false for no title attribute
1630 */
1631 public function titleAttrib( $name, $options = null ) {
1632 wfProfileIn( __METHOD__ );
1633
1634 if ( wfEmptyMsg( "tooltip-$name" ) ) {
1635 $tooltip = false;
1636 } else {
1637 $tooltip = wfMsg( "tooltip-$name" );
1638 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1639 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1640 # Message equal to '-' means suppress it.
1641 if ( $tooltip == '-' ) {
1642 $tooltip = false;
1643 }
1644 }
1645
1646 if ( $options == 'withaccess' ) {
1647 $accesskey = $this->accesskey( $name );
1648 if ( $accesskey !== false ) {
1649 if ( $tooltip === false || $tooltip === '' ) {
1650 $tooltip = "[$accesskey]";
1651 } else {
1652 $tooltip .= " [$accesskey]";
1653 }
1654 }
1655 }
1656
1657 wfProfileOut( __METHOD__ );
1658 return $tooltip;
1659 }
1660
1661 /**
1662 * Given the id of an interface element, constructs the appropriate
1663 * accesskey attribute from the system messages. (Note, this is usually
1664 * the id but isn't always, because sometimes the accesskey needs to go on
1665 * a different element than the id, for reverse-compatibility, etc.)
1666 *
1667 * @param $name String: id of the element, minus prefixes.
1668 * @return String: contents of the accesskey attribute (which you must HTML-
1669 * escape), or false for no accesskey attribute
1670 */
1671 public function accesskey( $name ) {
1672 wfProfileIn( __METHOD__ );
1673
1674 if ( wfEmptyMsg( "accesskey-$name" ) ) {
1675 $accesskey = false;
1676 } else {
1677 $accesskey = wfMsg( "accesskey-$name" );
1678 if ( $accesskey === '' || $accesskey === '-' ) {
1679 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1680 # attribute, but this is broken for accesskey: that might be a useful
1681 # value.
1682 $accesskey = false;
1683 }
1684 }
1685
1686 wfProfileOut( __METHOD__ );
1687 return $accesskey;
1688 }
1689
1690 /**
1691 * Creates a (show/hide) link for deleting revisions/log entries
1692 *
1693 * @param $query Array: query parameters to be passed to link()
1694 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1695 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1696 *
1697 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1698 * span to allow for customization of appearance with CSS
1699 */
1700 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1701 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1702 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1703 $tag = $restricted ? 'strong' : 'span';
1704 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1705 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1706 }
1707
1708 /**
1709 * Creates a dead (show/hide) link for deleting revisions/log entries
1710 *
1711 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1712 *
1713 * @return string HTML text wrapped in a span to allow for customization
1714 * of appearance with CSS
1715 */
1716 public function revDeleteLinkDisabled( $delete = true ) {
1717 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1718 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1719 }
1720
1721 /* Deprecated methods */
1722
1723 /**
1724 * @deprecated
1725 */
1726 function postParseLinkColour( $s = null ) {
1727 wfDeprecated( __METHOD__ );
1728 return null;
1729 }
1730
1731
1732 /**
1733 * @deprecated Use link()
1734 *
1735 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1736 * it if you already have a title object handy. See makeLinkObj for further documentation.
1737 *
1738 * @param $title String: the text of the title
1739 * @param $text String: link text
1740 * @param $query String: optional query part
1741 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1742 * be included in the link text. Other characters will be appended after
1743 * the end of the link.
1744 */
1745 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1746 wfProfileIn( __METHOD__ );
1747 $nt = Title::newFromText( $title );
1748 if ( $nt instanceof Title ) {
1749 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1750 } else {
1751 wfDebug( 'Invalid title passed to Linker::makeLink(): "' . $title . "\"\n" );
1752 $result = $text == "" ? $title : $text;
1753 }
1754
1755 wfProfileOut( __METHOD__ );
1756 return $result;
1757 }
1758
1759 /**
1760 * @deprecated Use link()
1761 *
1762 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1763 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1764 *
1765 * @param $title String: the text of the title
1766 * @param $text String: link text
1767 * @param $query String: optional query part
1768 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1769 * be included in the link text. Other characters will be appended after
1770 * the end of the link.
1771 * @param $prefix String: Optional prefix
1772 * @param $aprops String: extra attributes to the a-element
1773 */
1774 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '' ) {
1775 $nt = Title::newFromText( $title );
1776 if ( $nt instanceof Title ) {
1777 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1778 } else {
1779 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "' . $title . "\"\n" );
1780 return $text == '' ? $title : $text;
1781 }
1782 }
1783
1784 /**
1785 * @deprecated Use link()
1786 *
1787 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1788 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1789 *
1790 * @param $title String: The text of the title
1791 * @param $text String: Link text
1792 * @param $query String: Optional query part
1793 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1794 * be included in the link text. Other characters will be appended after
1795 * the end of the link.
1796 */
1797 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1798 $nt = Title::newFromText( $title );
1799 if ( $nt instanceof Title ) {
1800 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1801 } else {
1802 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "' . $title . "\"\n" );
1803 return $text == '' ? $title : $text;
1804 }
1805 }
1806
1807 /**
1808 * @deprecated Use link()
1809 *
1810 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1811 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1812 *
1813 * @param $title String: the text of the title
1814 * @param $text String: link text
1815 * @param $query String: optional query part
1816 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1817 * be included in the link text. Other characters will be appended after
1818 * the end of the link.
1819 */
1820 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1821 wfDeprecated( __METHOD__ );
1822 $nt = Title::newFromText( $title );
1823 if ( $nt instanceof Title ) {
1824 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1825 } else {
1826 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "' . $title . "\"\n" );
1827 return $text == '' ? $title : $text;
1828 }
1829 }
1830
1831 /**
1832 * @deprecated Use link()
1833 *
1834 * Make a link for a title which may or may not be in the database. If you need to
1835 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1836 * call to this will result in a DB query.
1837 *
1838 * @param $nt Title: the title object to make the link from, e.g. from
1839 * Title::newFromText.
1840 * @param $text String: link text
1841 * @param $query String: optional query part
1842 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1843 * be included in the link text. Other characters will be appended after
1844 * the end of the link.
1845 * @param $prefix String: optional prefix. As trail, only before instead of after.
1846 */
1847 function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1848 wfProfileIn( __METHOD__ );
1849
1850 $query = wfCgiToArray( $query );
1851 list( $inside, $trail ) = Linker::splitTrail( $trail );
1852 if ( $text === '' ) {
1853 $text = $this->linkText( $nt );
1854 }
1855
1856 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1857
1858 wfProfileOut( __METHOD__ );
1859 return $ret;
1860 }
1861
1862 /**
1863 * @deprecated Use link()
1864 *
1865 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1866 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1867 * pages.
1868 *
1869 * @param $title Title object of target page
1870 * @param $text String: text to replace the title
1871 * @param $query String: link target
1872 * @param $trail String: text after link
1873 * @param $prefix String: text before link text
1874 * @param $aprops String: extra attributes to the a-element
1875 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1876 * @return the a-element
1877 */
1878 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1879 wfProfileIn( __METHOD__ );
1880
1881 if ( $text == '' ) {
1882 $text = $this->linkText( $title );
1883 }
1884 $attribs = Sanitizer::mergeAttributes(
1885 Sanitizer::decodeTagAttributes( $aprops ),
1886 Sanitizer::decodeTagAttributes( $style )
1887 );
1888 $query = wfCgiToArray( $query );
1889 list( $inside, $trail ) = Linker::splitTrail( $trail );
1890
1891 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1892 array( 'known', 'noclasses' ) ) . $trail;
1893
1894 wfProfileOut( __METHOD__ );
1895 return $ret;
1896 }
1897
1898 /**
1899 * @deprecated Use link()
1900 *
1901 * Make a red link to the edit page of a given title.
1902 *
1903 * @param $title Title object of the target page
1904 * @param $text String: Link text
1905 * @param $query String: Optional query part
1906 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1907 * be included in the link text. Other characters will be appended after
1908 * the end of the link.
1909 * @param $prefix String: Optional prefix
1910 */
1911 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1912 wfProfileIn( __METHOD__ );
1913
1914 list( $inside, $trail ) = Linker::splitTrail( $trail );
1915 if ( $text === '' ) {
1916 $text = $this->linkText( $title );
1917 }
1918
1919 $ret = $this->link( $title, "$prefix$text$inside", array(),
1920 wfCgiToArray( $query ), 'broken' ) . $trail;
1921
1922 wfProfileOut( __METHOD__ );
1923 return $ret;
1924 }
1925
1926 /**
1927 * @deprecated Use link()
1928 *
1929 * Make a brown link to a short article.
1930 *
1931 * @param $nt Title object of the target page
1932 * @param $text String: link text
1933 * @param $query String: optional query part
1934 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1935 * be included in the link text. Other characters will be appended after
1936 * the end of the link.
1937 * @param $prefix String: Optional prefix
1938 */
1939 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1940 // wfDeprecated( __METHOD__ );
1941 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1942 }
1943
1944 /**
1945 * @deprecated Use link()
1946 *
1947 * Make a coloured link.
1948 *
1949 * @param $nt Title object of the target page
1950 * @param $colour Integer: colour of the link
1951 * @param $text String: link text
1952 * @param $query String: optional query part
1953 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1954 * be included in the link text. Other characters will be appended after
1955 * the end of the link.
1956 * @param $prefix String: Optional prefix
1957 */
1958 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1959 // wfDeprecated( __METHOD__ );
1960 if ( $colour != '' ) {
1961 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
1962 } else $style = '';
1963 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1964 }
1965
1966 /** Obsolete alias */
1967 function makeImage( $url, $alt = '' ) {
1968 wfDeprecated( __METHOD__ );
1969 return $this->makeExternalImage( $url, $alt );
1970 }
1971
1972 /**
1973 * Creates the HTML source for images
1974 * @deprecated use makeImageLink2
1975 *
1976 * @param $title Title object
1977 * @param $label String: label text
1978 * @param $alt String: alt text
1979 * @param $align String: horizontal alignment: none, left, center, right)
1980 * @param $handlerParams Array: parameters to be passed to the media handler
1981 * @param $framed Boolean: shows image in original size in a frame
1982 * @param $thumb Boolean: shows image as thumbnail in a frame
1983 * @param $manualthumb String: image name for the manual thumbnail
1984 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
1985 * @param $time String: timestamp of the file, set as false for current
1986 * @return String
1987 */
1988 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
1989 $thumb = false, $manualthumb = '', $valign = '', $time = false )
1990 {
1991 $frameParams = array( 'alt' => $alt, 'caption' => $label );
1992 if ( $align ) {
1993 $frameParams['align'] = $align;
1994 }
1995 if ( $framed ) {
1996 $frameParams['framed'] = true;
1997 }
1998 if ( $thumb ) {
1999 $frameParams['thumbnail'] = true;
2000 }
2001 if ( $manualthumb ) {
2002 $frameParams['manualthumb'] = $manualthumb;
2003 }
2004 if ( $valign ) {
2005 $frameParams['valign'] = $valign;
2006 }
2007 $file = wfFindFile( $title, array( 'time' => $time ) );
2008 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2009 }
2010
2011 /** @deprecated use Linker::makeMediaLinkObj() */
2012 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2013 $nt = Title::makeTitleSafe( NS_FILE, $name );
2014 return $this->makeMediaLinkObj( $nt, $text, $time );
2015 }
2016
2017 /**
2018 * Used to generate section edit links that point to "other" pages
2019 * (sections that are really part of included pages).
2020 *
2021 * @deprecated use Linker::doEditSectionLink()
2022 * @param $title Title string.
2023 * @param $section Integer: section number.
2024 */
2025 public function editSectionLinkForOther( $title, $section ) {
2026 wfDeprecated( __METHOD__ );
2027 $title = Title::newFromText( $title );
2028 return $this->doEditSectionLink( $title, $section );
2029 }
2030
2031 /**
2032 * @deprecated use Linker::doEditSectionLink()
2033 * @param $nt Title object.
2034 * @param $section Integer: section number.
2035 * @param $hint Link String: title, or default if omitted or empty
2036 */
2037 public function editSectionLink( Title $nt, $section, $hint = '' ) {
2038 wfDeprecated( __METHOD__ );
2039 if ( $hint === '' ) {
2040 # No way to pass an actual empty $hint here! The new interface al-
2041 # lows this, so we have to do this for compatibility.
2042 $hint = null;
2043 }
2044 return $this->doEditSectionLink( $nt, $section, $hint );
2045 }
2046
2047 /**
2048 * Returns the attributes for the tooltip and access key.
2049 */
2050 public function tooltipAndAccesskeyAttribs( $name ) {
2051 global $wgEnableTooltipsAndAccesskeys;
2052 if ( !$wgEnableTooltipsAndAccesskeys )
2053 return array();
2054 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2055 # no attribute" instead of "output '' as value for attribute", this
2056 # would be three lines.
2057 $attribs = array(
2058 'title' => $this->titleAttrib( $name, 'withaccess' ),
2059 'accesskey' => $this->accesskey( $name )
2060 );
2061 if ( $attribs['title'] === false ) {
2062 unset( $attribs['title'] );
2063 }
2064 if ( $attribs['accesskey'] === false ) {
2065 unset( $attribs['accesskey'] );
2066 }
2067 return $attribs;
2068 }
2069 /**
2070 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
2071 */
2072 public function tooltipAndAccesskey( $name ) {
2073 return Xml::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2074 }
2075
2076 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
2077 public function tooltip( $name, $options = null ) {
2078 global $wgEnableTooltipsAndAccesskeys;
2079 if ( !$wgEnableTooltipsAndAccesskeys )
2080 return '';
2081 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2082 # no attribute" instead of "output '' as value for attribute", this
2083 # would be two lines.
2084 $tooltip = $this->titleAttrib( $name, $options );
2085 if ( $tooltip === false ) {
2086 return '';
2087 }
2088 return Xml::expandAttributes( array(
2089 'title' => $this->titleAttrib( $name, $options )
2090 ) );
2091 }
2092 }