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