Remove inexplicable $nt->isContentPage() check for rendering link colors in makeLinkO...
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Split off some of the internal bits from Skin.php.
4 * These functions are used for primarily page content:
5 * links, embedded images, table of contents. Links are
6 * also used in the skin.
7 * For the moment, Skin is a descendent class of Linker.
8 * In the future, it should probably be further split
9 * so that ever other bit of the wiki doesn't have to
10 * go loading up Skin to get at it.
11 *
12 * @addtogroup Skins
13 */
14 class Linker {
15
16 /**
17 * Flags for userToolLinks()
18 */
19 const TOOL_LINKS_NOBLOCK = 1;
20
21 function __construct() {}
22
23 /**
24 * @deprecated
25 */
26 function postParseLinkColour( $s = NULL ) {
27 return NULL;
28 }
29
30 /** @todo document */
31 function getExternalLinkAttributes( $link, $text, $class='' ) {
32 $link = htmlspecialchars( $link );
33
34 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
35
36 $r .= " title=\"{$link}\"";
37 return $r;
38 }
39
40 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
41 global $wgContLang;
42
43 $link = urldecode( $link );
44 $link = $wgContLang->checkTitleEncoding( $link );
45 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
46 $link = htmlspecialchars( $link );
47
48 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
49
50 $r .= " title=\"{$link}\"";
51 return $r;
52 }
53
54 /** @todo document */
55 function getInternalLinkAttributes( $link, $text, $class='' ) {
56 $link = urldecode( $link );
57 $link = str_replace( '_', ' ', $link );
58 $link = htmlspecialchars( $link );
59 $r = ($class != '') ? ' class="' . htmlspecialchars( $class ) . '"' : '';
60 $r .= " title=\"{$link}\"";
61 return $r;
62 }
63
64 /**
65 * @param $nt Title object.
66 * @param $text String: FIXME
67 * @param $class String: CSS class of the link, default ''.
68 */
69 function getInternalLinkAttributesObj( &$nt, $text, $class='' ) {
70 $r = ($class != '') ? ' class="' . htmlspecialchars( $class ) . '"' : '';
71 $r .= ' title="' . $nt->getEscapedText() . '"';
72 return $r;
73 }
74
75 /**
76 * Return the CSS colour of a known link
77 *
78 * @param mixed $s
79 * @param integer $threshold user defined threshold
80 * @return string CSS class
81 */
82 function getLinkColour( $s, $threshold ) {
83 if( $s == false ) {
84 return '';
85 }
86
87 $colour = '';
88 if ( !empty( $s->page_is_redirect ) ) {
89 # Page is a redirect
90 $colour = 'mw-redirect';
91 } elseif ( $threshold > 0 && $s->page_len < $threshold && Namespace::isContent( $s->page_namespace ) ) {
92 # Page is a stub
93 $colour = 'stub';
94 }
95 return $colour;
96 }
97
98 /**
99 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
100 * it if you already have a title object handy. See makeLinkObj for further documentation.
101 *
102 * @param $title String: the text of the title
103 * @param $text String: link text
104 * @param $query String: optional query part
105 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
106 * be included in the link text. Other characters will be appended after
107 * the end of the link.
108 */
109 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
110 wfProfileIn( __METHOD__ );
111 $nt = Title::newFromText( $title );
112 if ( $nt instanceof Title ) {
113 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
114 } else {
115 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
116 $result = $text == "" ? $title : $text;
117 }
118
119 wfProfileOut( __METHOD__ );
120 return $result;
121 }
122
123 /**
124 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
125 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
126 *
127 * @param $title String: the text of the title
128 * @param $text String: link text
129 * @param $query String: optional query part
130 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
131 * be included in the link text. Other characters will be appended after
132 * the end of the link.
133 */
134 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
135 $nt = Title::newFromText( $title );
136 if ( $nt instanceof Title ) {
137 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
138 } else {
139 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
140 return $text == '' ? $title : $text;
141 }
142 }
143
144 /**
145 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
146 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
147 *
148 * @param string $title The text of the title
149 * @param string $text Link text
150 * @param string $query Optional query part
151 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
152 * be included in the link text. Other characters will be appended after
153 * the end of the link.
154 */
155 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
156 $nt = Title::newFromText( $title );
157 if ( $nt instanceof Title ) {
158 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
159 } else {
160 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
161 return $text == '' ? $title : $text;
162 }
163 }
164
165 /**
166 * @deprecated use makeColouredLinkObj
167 *
168 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
169 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
170 *
171 * @param $title String: the text of the title
172 * @param $text String: link text
173 * @param $query String: optional query part
174 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
175 * be included in the link text. Other characters will be appended after
176 * the end of the link.
177 */
178 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
179 $nt = Title::newFromText( $title );
180 if ( $nt instanceof Title ) {
181 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
182 } else {
183 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
184 return $text == '' ? $title : $text;
185 }
186 }
187
188 /**
189 * Make a link for a title which may or may not be in the database. If you need to
190 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
191 * call to this will result in a DB query.
192 *
193 * @param $nt Title: the title object to make the link from, e.g. from
194 * Title::newFromText.
195 * @param $text String: link text
196 * @param $query String: optional query part
197 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
198 * be included in the link text. Other characters will be appended after
199 * the end of the link.
200 * @param $prefix String: optional prefix. As trail, only before instead of after.
201 */
202 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
203 global $wgUser;
204 wfProfileIn( __METHOD__ );
205
206 if ( !$nt instanceof Title ) {
207 # Fail gracefully
208 wfProfileOut( __METHOD__ );
209 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
210 }
211
212 if ( $nt->isExternal() ) {
213 $u = $nt->getFullURL();
214 $link = $nt->getPrefixedURL();
215 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
216 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
217
218 $inside = '';
219 if ( '' != $trail ) {
220 $m = array();
221 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
222 $inside = $m[1];
223 $trail = $m[2];
224 }
225 }
226 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
227
228 wfProfileOut( __METHOD__ );
229 return $t;
230 } elseif ( $nt->isAlwaysKnown() ) {
231 # Image links, special page links and self-links with fragements are always known.
232 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
233 } else {
234 wfProfileIn( __METHOD__.'-immediate' );
235
236 # Handles links to special pages which do not exist in the database:
237 if( $nt->getNamespace() == NS_SPECIAL ) {
238 if( SpecialPage::exists( $nt->getDBkey() ) ) {
239 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
240 } else {
241 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
242 }
243 wfProfileOut( __METHOD__.'-immediate' );
244 wfProfileOut( __METHOD__ );
245 return $retVal;
246 }
247
248 # Work out link colour immediately
249 $aid = $nt->getArticleID() ;
250 if ( 0 == $aid ) {
251 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
252 } else {
253 $colour = '';
254 # FIXME: This is stupid, we should combine this query with
255 # the Title::getArticleID() query above.
256 $threshold = $wgUser->getOption('stubthreshold');
257 $dbr = wfGetDB( DB_SLAVE );
258 $s = $dbr->selectRow(
259 array( 'page' ),
260 array( 'page_len', 'page_is_redirect', 'page_namespace' ),
261 array( 'page_id' => $aid ), __METHOD__ ) ;
262 $colour = $this->getLinkColour( $s, $threshold );
263
264 $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
265 }
266 wfProfileOut( __METHOD__.'-immediate' );
267 }
268 wfProfileOut( __METHOD__ );
269 return $retVal;
270 }
271
272 /**
273 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
274 * it doesn't have to do a database query. It's also valid for interwiki titles and special
275 * pages.
276 *
277 * @param $nt Title object of target page
278 * @param $text String: text to replace the title
279 * @param $query String: link target
280 * @param $trail String: text after link
281 * @param $prefix String: text before link text
282 * @param $aprops String: extra attributes to the a-element
283 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
284 * @return the a-element
285 */
286 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
287 wfProfileIn( __METHOD__ );
288
289 if ( !$nt instanceof Title ) {
290 # Fail gracefully
291 wfProfileOut( __METHOD__ );
292 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
293 }
294
295 $u = $nt->escapeLocalURL( $query );
296 if ( $nt->getFragment() != '' ) {
297 if( $nt->getPrefixedDbkey() == '' ) {
298 $u = '';
299 if ( '' == $text ) {
300 $text = htmlspecialchars( $nt->getFragment() );
301 }
302 }
303 $u .= $nt->getFragmentForURL();
304 }
305 if ( $text == '' ) {
306 $text = htmlspecialchars( $nt->getPrefixedText() );
307 }
308 if ( $style == '' ) {
309 $style = $this->getInternalLinkAttributesObj( $nt, $text );
310 }
311
312 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
313
314 list( $inside, $trail ) = Linker::splitTrail( $trail );
315 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
316 wfProfileOut( __METHOD__ );
317 return $r;
318 }
319
320 /**
321 * Make a red link to the edit page of a given title.
322 *
323 * @param $nt Title object of the target page
324 * @param $text String: Link text
325 * @param $query String: Optional query part
326 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
327 * be included in the link text. Other characters will be appended after
328 * the end of the link.
329 */
330 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
331 wfProfileIn( __METHOD__ );
332
333 if ( !$nt instanceof Title ) {
334 # Fail gracefully
335 wfProfileOut( __METHOD__ );
336 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
337 }
338
339 if( $nt->getNamespace() == NS_SPECIAL ) {
340 $q = $query;
341 } else if ( '' == $query ) {
342 $q = 'action=edit';
343 } else {
344 $q = 'action=edit&'.$query;
345 }
346 $u = $nt->escapeLocalURL( $q );
347
348 if ( '' == $text ) {
349 $text = htmlspecialchars( $nt->getPrefixedText() );
350 }
351 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new' );
352
353 list( $inside, $trail ) = Linker::splitTrail( $trail );
354 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
355
356 wfProfileOut( __METHOD__ );
357 return $s;
358 }
359
360 /**
361 * @deprecated use makeColouredLinkObj
362 *
363 * Make a brown link to a short article.
364 *
365 * @param $nt Title object of the target page
366 * @param $text String: link text
367 * @param $query String: optional query part
368 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
369 * be included in the link text. Other characters will be appended after
370 * the end of the link.
371 */
372 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
373 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
374 }
375
376 /**
377 * Make a coloured link.
378 *
379 * @param $nt Title object of the target page
380 * @param $colour Integer: colour of the link
381 * @param $text String: link text
382 * @param $query String: optional query part
383 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
384 * be included in the link text. Other characters will be appended after
385 * the end of the link.
386 */
387 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
388
389 if($colour != ''){
390 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
391 } else $style = '';
392 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
393 }
394
395 /**
396 * Generate either a normal exists-style link or a stub link, depending
397 * on the given page size.
398 *
399 * @param $size Integer
400 * @param $nt Title object.
401 * @param $text String
402 * @param $query String
403 * @param $trail String
404 * @param $prefix String
405 * @return string HTML of link
406 */
407 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
408 global $wgUser;
409 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
410 $colour = ( $size < $threshold ) ? 'stub' : '';
411 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
412 }
413
414 /**
415 * Make appropriate markup for a link to the current article. This is currently rendered
416 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
417 * despite $query not being used.
418 */
419 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
420 if ( '' == $text ) {
421 $text = htmlspecialchars( $nt->getPrefixedText() );
422 }
423 list( $inside, $trail ) = Linker::splitTrail( $trail );
424 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
425 }
426
427 /** @todo document */
428 function fnamePart( $url ) {
429 $basename = strrchr( $url, '/' );
430 if ( false === $basename ) {
431 $basename = $url;
432 } else {
433 $basename = substr( $basename, 1 );
434 }
435 return htmlspecialchars( $basename );
436 }
437
438 /** Obsolete alias */
439 function makeImage( $url, $alt = '' ) {
440 return $this->makeExternalImage( $url, $alt );
441 }
442
443 /** @todo document */
444 function makeExternalImage( $url, $alt = '' ) {
445 if ( '' == $alt ) {
446 $alt = $this->fnamePart( $url );
447 }
448 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
449 return $s;
450 }
451
452 /**
453 * Creates the HTML source for images
454 * @deprecated use makeImageLink2
455 *
456 * @param object $title
457 * @param string $label label text
458 * @param string $alt alt text
459 * @param string $align horizontal alignment: none, left, center, right)
460 * @param array $handlerParams Parameters to be passed to the media handler
461 * @param boolean $framed shows image in original size in a frame
462 * @param boolean $thumb shows image as thumbnail in a frame
463 * @param string $manualthumb image name for the manual thumbnail
464 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
465 * @param string $time, timestamp of the file, set as false for current
466 * @return string
467 */
468 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
469 $thumb = false, $manualthumb = '', $valign = '', $time = false )
470 {
471 $frameParams = array( 'alt' => $alt, 'caption' => $label );
472 if ( $align ) {
473 $frameParams['align'] = $align;
474 }
475 if ( $framed ) {
476 $frameParams['framed'] = true;
477 }
478 if ( $thumb ) {
479 $frameParams['thumbnail'] = true;
480 }
481 if ( $manualthumb ) {
482 $frameParams['manualthumb'] = $manualthumb;
483 }
484 if ( $valign ) {
485 $frameParams['valign'] = $valign;
486 }
487 $file = wfFindFile( $title, $time );
488 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
489 }
490
491 /**
492 * Make an image link
493 * @param Title $title Title object
494 * @param File $file File object, or false if it doesn't exist
495 *
496 * @param array $frameParams Associative array of parameters external to the media handler.
497 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
498 * will often be false.
499 * thumbnail If present, downscale and frame
500 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
501 * framed Shows image in original size in a frame
502 * frameless Downscale but don't frame
503 * upright If present, tweak default sizes for portrait orientation
504 * upright_factor Fudge factor for "upright" tweak (default 0.75)
505 * border If present, show a border around the image
506 * align Horizontal alignment (left, right, center, none)
507 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
508 * bottom, text-bottom)
509 * alt Alternate text for image (i.e. alt attribute). Plain text.
510 * caption HTML for image caption.
511 *
512 * @param array $handlerParams Associative array of media handler parameters, to be passed
513 * to transform(). Typical keys are "width" and "page".
514 * @param string $time, timestamp of the file, set as false for current
515 */
516 function makeImageLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
517 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
518 if ( $file && !$file->allowInlineDisplay() ) {
519 wfDebug( __METHOD__.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
520 return $this->makeKnownLinkObj( $title );
521 }
522
523 // Shortcuts
524 $fp =& $frameParams;
525 $hp =& $handlerParams;
526
527 // Clean up parameters
528 $page = isset( $hp['page'] ) ? $hp['page'] : false;
529 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
530 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
531
532 $prefix = $postfix = '';
533
534 if ( 'center' == $fp['align'] )
535 {
536 $prefix = '<div class="center">';
537 $postfix = '</div>';
538 $fp['align'] = 'none';
539 }
540 if ( $file && !isset( $hp['width'] ) ) {
541 $hp['width'] = $file->getWidth( $page );
542
543 if( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) || !$hp['width'] ) {
544 $wopt = $wgUser->getOption( 'thumbsize' );
545
546 if( !isset( $wgThumbLimits[$wopt] ) ) {
547 $wopt = User::getDefaultOption( 'thumbsize' );
548 }
549
550 // Reduce width for upright images when parameter 'upright' is used
551 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
552 $fp['upright'] = $wgThumbUpright;
553 }
554 // Use width which is smaller: real image width or user preference width
555 // 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
556 $prefWidth = isset( $fp['upright'] ) ?
557 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
558 $wgThumbLimits[$wopt];
559 if ( $hp['width'] <= 0 || $prefWidth < $hp['width'] ) {
560 $hp['width'] = $prefWidth;
561 }
562 }
563 }
564
565 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
566
567 # Create a thumbnail. Alignment depends on language
568 # writing direction, # right aligned for left-to-right-
569 # languages ("Western languages"), left-aligned
570 # for right-to-left-languages ("Semitic languages")
571 #
572 # If thumbnail width has not been provided, it is set
573 # to the default user option as specified in Language*.php
574 if ( $fp['align'] == '' ) {
575 $fp['align'] = $wgContLang->isRTL() ? 'left' : 'right';
576 }
577 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time ).$postfix;
578 }
579
580 if ( $file && isset( $fp['frameless'] ) ) {
581 $srcWidth = $file->getWidth( $page );
582 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
583 # This is the same behaviour as the "thumb" option does it already.
584 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
585 $hp['width'] = $srcWidth;
586 }
587 }
588
589 if ( $file && $hp['width'] ) {
590 # Create a resized image, without the additional thumbnail features
591 $thumb = $file->transform( $hp );
592 } else {
593 $thumb = false;
594 }
595
596 if ( !$thumb ) {
597 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
598 } else {
599 $s = $thumb->toHtml( array(
600 'desc-link' => true,
601 'alt' => $fp['alt'],
602 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false ,
603 'img-class' => isset( $fp['border'] ) ? 'thumbborder' : false ) );
604 }
605 if ( '' != $fp['align'] ) {
606 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
607 }
608 return str_replace("\n", ' ',$prefix.$s.$postfix);
609 }
610
611 /**
612 * Make HTML for a thumbnail including image, border and caption
613 * @param Title $title
614 * @param File $file File object or false if it doesn't exist
615 */
616 function makeThumbLinkObj( Title $title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
617 $frameParams = array(
618 'alt' => $alt,
619 'caption' => $label,
620 'align' => $align
621 );
622 if ( $framed ) $frameParams['framed'] = true;
623 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
624 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
625 }
626
627 function makeThumbLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
628 global $wgStylePath, $wgContLang;
629 $exists = $file && $file->exists();
630
631 # Shortcuts
632 $fp =& $frameParams;
633 $hp =& $handlerParams;
634
635 $page = isset( $hp['page'] ) ? $hp['page'] : false;
636 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
637 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
638 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
639
640 if ( empty( $hp['width'] ) ) {
641 // Reduce width for upright images when parameter 'upright' is used
642 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
643 }
644 $thumb = false;
645
646 if ( !$exists ) {
647 $outerWidth = $hp['width'] + 2;
648 } else {
649 if ( isset( $fp['manualthumb'] ) ) {
650 # Use manually specified thumbnail
651 $manual_title = Title::makeTitleSafe( NS_IMAGE, $fp['manualthumb'] );
652 if( $manual_title ) {
653 $manual_img = wfFindFile( $manual_title );
654 if ( $manual_img ) {
655 $thumb = $manual_img->getUnscaledThumb();
656 } else {
657 $exists = false;
658 }
659 }
660 } elseif ( isset( $fp['framed'] ) ) {
661 // Use image dimensions, don't scale
662 $thumb = $file->getUnscaledThumb( $page );
663 } else {
664 # Do not present an image bigger than the source, for bitmap-style images
665 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
666 $srcWidth = $file->getWidth( $page );
667 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
668 $hp['width'] = $srcWidth;
669 }
670 $thumb = $file->transform( $hp );
671 }
672
673 if ( $thumb ) {
674 $outerWidth = $thumb->getWidth() + 2;
675 } else {
676 $outerWidth = $hp['width'] + 2;
677 }
678 }
679
680 $query = $page ? 'page=' . urlencode( $page ) : '';
681 $url = $title->getLocalURL( $query );
682
683 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
684
685 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
686 if( !$exists ) {
687 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
688 $zoomicon = '';
689 } elseif ( !$thumb ) {
690 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
691 $zoomicon = '';
692 } else {
693 $s .= $thumb->toHtml( array(
694 'alt' => $fp['alt'],
695 'img-class' => 'thumbimage',
696 'desc-link' => true ) );
697 if ( isset( $fp['framed'] ) ) {
698 $zoomicon="";
699 } else {
700 $zoomicon = '<div class="magnify">'.
701 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
702 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
703 'width="15" height="11" alt="" /></a></div>';
704 }
705 }
706 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
707 return str_replace("\n", ' ', $s);
708 }
709
710 /**
711 * Make a "broken" link to an image
712 *
713 * @param Title $title Image title
714 * @param string $text Link label
715 * @param string $query Query string
716 * @param string $trail Link trail
717 * @param string $prefix Link prefix
718 * @param bool $time, a file of a certain timestamp was requested
719 * @return string
720 */
721 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
722 global $wgEnableUploads;
723 if( $title instanceof Title ) {
724 wfProfileIn( __METHOD__ );
725 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
726 if( $wgEnableUploads && !$currentExists ) {
727 $upload = SpecialPage::getTitleFor( 'Upload' );
728 if( $text == '' )
729 $text = htmlspecialchars( $title->getPrefixedText() );
730 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
731 if( $redir ) {
732 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
733 }
734 $q = 'wpDestFile=' . $title->getPartialUrl();
735 if( $query != '' )
736 $q .= '&' . $query;
737 list( $inside, $trail ) = self::splitTrail( $trail );
738 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
739 wfProfileOut( __METHOD__ );
740 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
741 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
742 } else {
743 wfProfileOut( __METHOD__ );
744 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
745 }
746 } else {
747 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
748 }
749 }
750
751 /** @deprecated use Linker::makeMediaLinkObj() */
752 function makeMediaLink( $name, $unused = '', $text = '' ) {
753 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
754 return $this->makeMediaLinkObj( $nt, $text );
755 }
756
757 /**
758 * Create a direct link to a given uploaded file.
759 *
760 * @param $title Title object.
761 * @param $text String: pre-sanitized HTML
762 * @return string HTML
763 *
764 * @public
765 * @todo Handle invalid or missing images better.
766 */
767 function makeMediaLinkObj( $title, $text = '' ) {
768 if( is_null( $title ) ) {
769 ### HOTFIX. Instead of breaking, return empty string.
770 return $text;
771 } else {
772 $img = wfFindFile( $title );
773 if( $img ) {
774 $url = $img->getURL();
775 $class = 'internal';
776 } else {
777 $upload = SpecialPage::getTitleFor( 'Upload' );
778 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
779 $class = 'new';
780 }
781 $alt = htmlspecialchars( $title->getText() );
782 if( $text == '' ) {
783 $text = $alt;
784 }
785 $u = htmlspecialchars( $url );
786 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
787 }
788 }
789
790 /** @todo document */
791 function specialLink( $name, $key = '' ) {
792 global $wgContLang;
793
794 if ( '' == $key ) { $key = strtolower( $name ); }
795 $pn = $wgContLang->ucfirst( $name );
796 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
797 wfMsg( $key ) );
798 }
799
800 /** @todo document */
801 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
802 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
803 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
804 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
805 $style .= ' rel="nofollow"';
806 }
807 $url = htmlspecialchars( $url );
808 if( $escape ) {
809 $text = htmlspecialchars( $text );
810 }
811 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
812 }
813
814 /**
815 * Make user link (or user contributions for unregistered users)
816 * @param $userId Integer: user id in database.
817 * @param $userText String: user name in database
818 * @return string HTML fragment
819 * @private
820 */
821 function userLink( $userId, $userText ) {
822 $encName = htmlspecialchars( $userText );
823 if( $userId == 0 ) {
824 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
825 return $this->makeKnownLinkObj( $contribsPage,
826 $encName);
827 } else {
828 $userPage = Title::makeTitle( NS_USER, $userText );
829 return $this->makeLinkObj( $userPage, $encName );
830 }
831 }
832
833 /**
834 * Generate standard user tool links (talk, contributions, block link, etc.)
835 *
836 * @param int $userId User identifier
837 * @param string $userText User name or IP address
838 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
839 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
840 * @return string
841 */
842 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
843 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
844 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
845 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
846
847 $items = array();
848 if( $talkable ) {
849 $items[] = $this->userTalkLink( $userId, $userText );
850 }
851 if( $userId ) {
852 // check if the user has an edit
853 if( $redContribsWhenNoEdits && User::edits( $userId ) == 0 ) {
854 $style = " class='new'";
855 } else {
856 $style = '';
857 }
858 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
859
860 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
861 }
862 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
863 $items[] = $this->blockLink( $userId, $userText );
864 }
865
866 if( $items ) {
867 return ' (' . implode( ' | ', $items ) . ')';
868 } else {
869 return '';
870 }
871 }
872
873 /**
874 * Alias for userToolLinks( $userId, $userText, true );
875 */
876 public function userToolLinksRedContribs( $userId, $userText ) {
877 return $this->userToolLinks( $userId, $userText, true );
878 }
879
880
881 /**
882 * @param $userId Integer: user id in database.
883 * @param $userText String: user name in database.
884 * @return string HTML fragment with user talk link
885 * @private
886 */
887 function userTalkLink( $userId, $userText ) {
888 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
889 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
890 return $userTalkLink;
891 }
892
893 /**
894 * @param $userId Integer: userid
895 * @param $userText String: user name in database.
896 * @return string HTML fragment with block link
897 * @private
898 */
899 function blockLink( $userId, $userText ) {
900 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
901 $blockLink = $this->makeKnownLinkObj( $blockPage,
902 wfMsgHtml( 'blocklink' ) );
903 return $blockLink;
904 }
905
906 /**
907 * Generate a user link if the current user is allowed to view it
908 * @param $rev Revision object.
909 * @return string HTML
910 */
911 function revUserLink( $rev ) {
912 if( $rev->userCan( Revision::DELETED_USER ) ) {
913 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
914 } else {
915 $link = wfMsgHtml( 'rev-deleted-user' );
916 }
917 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
918 return '<span class="history-deleted">' . $link . '</span>';
919 }
920 return $link;
921 }
922
923 /**
924 * Generate a user tool link cluster if the current user is allowed to view it
925 * @param $rev Revision object.
926 * @return string HTML
927 */
928 function revUserTools( $rev ) {
929 if( $rev->userCan( Revision::DELETED_USER ) ) {
930 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
931 ' ' .
932 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
933 } else {
934 $link = wfMsgHtml( 'rev-deleted-user' );
935 }
936 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
937 return '<span class="history-deleted">' . $link . '</span>';
938 }
939 return $link;
940 }
941
942 /**
943 * This function is called by all recent changes variants, by the page history,
944 * and by the user contributions list. It is responsible for formatting edit
945 * comments. It escapes any HTML in the comment, but adds some CSS to format
946 * auto-generated comments (from section editing) and formats [[wikilinks]].
947 *
948 * @author Erik Moeller <moeller@scireview.de>
949 *
950 * Note: there's not always a title to pass to this function.
951 * Since you can't set a default parameter for a reference, I've turned it
952 * temporarily to a value pass. Should be adjusted further. --brion
953 *
954 * @param string $comment
955 * @param mixed $title Title object (to generate link to the section in autocomment) or null
956 * @param bool $local Whether section links should refer to local page
957 */
958 function formatComment($comment, $title = NULL, $local = false) {
959 wfProfileIn( __METHOD__ );
960
961 # Sanitize text a bit:
962 $comment = str_replace( "\n", " ", $comment );
963 $comment = htmlspecialchars( $comment );
964
965 # Render autocomments and make links:
966 $comment = $this->formatAutoComments( $comment, $title, $local );
967 $comment = $this->formatLinksInComment( $comment );
968
969 wfProfileOut( __METHOD__ );
970 return $comment;
971 }
972
973 /**
974 * The pattern for autogen comments is / * foo * /, which makes for
975 * some nasty regex.
976 * We look for all comments, match any text before and after the comment,
977 * add a separator where needed and format the comment itself with CSS
978 * Called by Linker::formatComment.
979 *
980 * @param string $comment Comment text
981 * @param object $title An optional title object used to links to sections
982 * @return string $comment formatted comment
983 *
984 * @todo Document the $local parameter.
985 */
986 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
987 $match = array();
988 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
989 $pre=$match[1];
990 $auto=$match[2];
991 $post=$match[3];
992 $link='';
993 if( $title ) {
994 $section = $auto;
995
996 # Generate a valid anchor name from the section title.
997 # Hackish, but should generally work - we strip wiki
998 # syntax, including the magic [[: that is used to
999 # "link rather than show" in case of images and
1000 # interlanguage links.
1001 $section = str_replace( '[[:', '', $section );
1002 $section = str_replace( '[[', '', $section );
1003 $section = str_replace( ']]', '', $section );
1004 if ( $local ) {
1005 $sectionTitle = Title::newFromText( '#' . $section);
1006 } else {
1007 $sectionTitle = wfClone( $title );
1008 $sectionTitle->mFragment = $section;
1009 }
1010 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1011 }
1012 $auto = $link . $auto;
1013 if( $pre ) {
1014 $auto = '- ' . $auto; # written summary $presep autocomment (summary /* section */)
1015 }
1016 if( $post ) {
1017 $auto .= ': '; # autocomment $postsep written summary (/* section */ summary)
1018 }
1019 $auto = '<span class="autocomment">' . $auto . '</span>';
1020 $comment = $pre . $auto . $post;
1021 }
1022
1023 return $comment;
1024 }
1025
1026 /**
1027 * Formats wiki links and media links in text; all other wiki formatting
1028 * is ignored
1029 *
1030 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1031 * @param string $comment Text to format links in
1032 * @return string
1033 */
1034 public function formatLinksInComment( $comment ) {
1035 return preg_replace_callback(
1036 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1037 array( $this, 'formatLinksInCommentCallback' ),
1038 $comment );
1039 }
1040
1041 protected function formatLinksInCommentCallback( $match ) {
1042 global $wgContLang;
1043
1044 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1045 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1046
1047 $comment = $match[0];
1048
1049 # Handle link renaming [[foo|text]] will show link as "text"
1050 if( "" != $match[3] ) {
1051 $text = $match[3];
1052 } else {
1053 $text = $match[1];
1054 }
1055 $submatch = array();
1056 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1057 # Media link; trail not supported.
1058 $linkRegexp = '/\[\[(.*?)\]\]/';
1059 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1060 } else {
1061 # Other kind of link
1062 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1063 $trail = $submatch[1];
1064 } else {
1065 $trail = "";
1066 }
1067 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1068 if (isset($match[1][0]) && $match[1][0] == ':')
1069 $match[1] = substr($match[1], 1);
1070 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1071 }
1072 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1073
1074 return $comment;
1075 }
1076
1077 /**
1078 * Wrap a comment in standard punctuation and formatting if
1079 * it's non-empty, otherwise return empty string.
1080 *
1081 * @param string $comment
1082 * @param mixed $title Title object (to generate link to section in autocomment) or null
1083 * @param bool $local Whether section links should refer to local page
1084 *
1085 * @return string
1086 */
1087 function commentBlock( $comment, $title = NULL, $local = false ) {
1088 // '*' used to be the comment inserted by the software way back
1089 // in antiquity in case none was provided, here for backwards
1090 // compatability, acc. to brion -ævar
1091 if( $comment == '' || $comment == '*' ) {
1092 return '';
1093 } else {
1094 $formatted = $this->formatComment( $comment, $title, $local );
1095 return " <span class=\"comment\">($formatted)</span>";
1096 }
1097 }
1098
1099 /**
1100 * Wrap and format the given revision's comment block, if the current
1101 * user is allowed to view it.
1102 *
1103 * @param Revision $rev
1104 * @param bool $local Whether section links should refer to local page
1105 * @return string HTML
1106 */
1107 function revComment( Revision $rev, $local = false ) {
1108 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1109 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1110 } else {
1111 $block = " <span class=\"comment\">" .
1112 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1113 }
1114 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1115 return " <span class=\"history-deleted\">$block</span>";
1116 }
1117 return $block;
1118 }
1119
1120 /** @todo document */
1121 function tocIndent() {
1122 return "\n<ul>";
1123 }
1124
1125 /** @todo document */
1126 function tocUnindent($level) {
1127 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1128 }
1129
1130 /**
1131 * parameter level defines if we are on an indentation level
1132 */
1133 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1134 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1135 $anchor . '"><span class="tocnumber">' .
1136 $tocnumber . '</span> <span class="toctext">' .
1137 $tocline . '</span></a>';
1138 }
1139
1140 /** @todo document */
1141 function tocLineEnd() {
1142 return "</li>\n";
1143 }
1144
1145 /** @todo document */
1146 function tocList($toc) {
1147 global $wgJsMimeType;
1148 $title = wfMsgHtml('toc') ;
1149 return
1150 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1151 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1152 . $toc
1153 # no trailing newline, script should not be wrapped in a
1154 # paragraph
1155 . "</ul>\n</td></tr></table>"
1156 . '<script type="' . $wgJsMimeType . '">'
1157 . ' if (window.showTocToggle) {'
1158 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1159 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1160 . ' showTocToggle();'
1161 . ' } '
1162 . "</script>\n";
1163 }
1164
1165 /**
1166 * Used to generate section edit links that point to "other" pages
1167 * (sections that are really part of included pages).
1168 *
1169 * @param $title Title string.
1170 * @param $section Integer: section number.
1171 */
1172 public function editSectionLinkForOther( $title, $section ) {
1173 $title = Title::newFromText( $title );
1174 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1175 }
1176
1177 /**
1178 * @param $nt Title object.
1179 * @param $section Integer: section number.
1180 * @param $hint Link String: title, or default if omitted or empty
1181 */
1182 public function editSectionLink( Title $nt, $section, $hint='' ) {
1183 if( $hint != '' ) {
1184 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1185 $hint = " title=\"$hint\"";
1186 }
1187 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1188 }
1189
1190 /**
1191 * Implement editSectionLink and editSectionLinkForOther.
1192 *
1193 * @param $nt Title object
1194 * @param $section Integer, section number
1195 * @param $hint String, for HTML title attribute
1196 * @param $hook String, name of hook to run
1197 * @return String, HTML to use for edit link
1198 */
1199 protected function doEditSectionLink( Title $nt, $section, $hint, $hook ) {
1200 global $wgContLang;
1201 $editurl = '&section='.$section;
1202 $url = $this->makeKnownLinkObj(
1203 $nt,
1204 wfMsg('editsection'),
1205 'action=edit'.$editurl,
1206 '', '', '', $hint
1207 );
1208 $result = null;
1209
1210 // The two hooks have slightly different interfaces . . .
1211 if( $hook == 'EditSectionLink' ) {
1212 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
1213 } elseif( $hook == 'EditSectionLinkForOther' ) {
1214 wfRunHooks( 'EditSectionLinkForOther', array( &$this, $nt, $section, $url, &$result ) );
1215 }
1216
1217 // For reverse compatibility, add the brackets *after* the hook is run,
1218 // and even add them to hook-provided text.
1219 if( is_null( $result ) ) {
1220 $result = wfMsg( 'editsection-brackets', $url );
1221 } else {
1222 $result = wfMsg( 'editsection-brackets', $result );
1223 }
1224 return "<span class=\"editsection\">$result</span>";
1225 }
1226
1227 /**
1228 * Create a headline for content
1229 *
1230 * @param int $level The level of the headline (1-6)
1231 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1232 * This *must* be at least '>' for no attribs
1233 * @param string $anchor The anchor to give the headline (the bit after the #)
1234 * @param string $text The text of the header
1235 * @param string $link HTML to add for the section edit link
1236 *
1237 * @return string HTML headline
1238 */
1239 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1240 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1241 }
1242
1243 /**
1244 * Split a link trail, return the "inside" portion and the remainder of the trail
1245 * as a two-element array
1246 *
1247 * @static
1248 */
1249 static function splitTrail( $trail ) {
1250 static $regex = false;
1251 if ( $regex === false ) {
1252 global $wgContLang;
1253 $regex = $wgContLang->linkTrail();
1254 }
1255 $inside = '';
1256 if ( '' != $trail ) {
1257 $m = array();
1258 if ( preg_match( $regex, $trail, $m ) ) {
1259 $inside = $m[1];
1260 $trail = $m[2];
1261 }
1262 }
1263 return array( $inside, $trail );
1264 }
1265
1266 /**
1267 * Generate a rollback link for a given revision. Currently it's the
1268 * caller's responsibility to ensure that the revision is the top one. If
1269 * it's not, of course, the user will get an error message.
1270 *
1271 * If the calling page is called with the parameter &bot=1, all rollback
1272 * links also get that parameter. It causes the edit itself and the rollback
1273 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1274 * changes, so this allows sysops to combat a busy vandal without bothering
1275 * other users.
1276 *
1277 * @param Revision $rev
1278 */
1279 function generateRollback( $rev ) {
1280 return '<span class="mw-rollback-link">['
1281 . $this->buildRollbackLink( $rev )
1282 . ']</span>';
1283 }
1284
1285 /**
1286 * Build a raw rollback link, useful for collections of "tool" links
1287 *
1288 * @param Revision $rev
1289 * @return string
1290 */
1291 public function buildRollbackLink( $rev ) {
1292 global $wgRequest, $wgUser;
1293 $title = $rev->getTitle();
1294 $extra = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1295 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1296 $rev->getUserText() ) ) );
1297 return $this->makeKnownLinkObj(
1298 $title,
1299 wfMsgHtml( 'rollbacklink' ),
1300 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1301 );
1302 }
1303
1304 /**
1305 * Returns HTML for the "templates used on this page" list.
1306 *
1307 * @param array $templates Array of templates from Article::getUsedTemplate
1308 * or similar
1309 * @param bool $preview Whether this is for a preview
1310 * @param bool $section Whether this is for a section edit
1311 * @return string HTML output
1312 */
1313 public function formatTemplates( $templates, $preview = false, $section = false) {
1314 global $wgUser;
1315 wfProfileIn( __METHOD__ );
1316
1317 $sk = $wgUser->getSkin();
1318
1319 $outText = '';
1320 if ( count( $templates ) > 0 ) {
1321 # Do a batch existence check
1322 $batch = new LinkBatch;
1323 foreach( $templates as $title ) {
1324 $batch->addObj( $title );
1325 }
1326 $batch->execute();
1327
1328 # Construct the HTML
1329 $outText = '<div class="mw-templatesUsedExplanation">';
1330 if ( $preview ) {
1331 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1332 } elseif ( $section ) {
1333 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1334 } else {
1335 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1336 }
1337 $outText .= '</div><ul>';
1338
1339 foreach ( $templates as $titleObj ) {
1340 $r = $titleObj->getRestrictions( 'edit' );
1341 if ( in_array( 'sysop', $r ) ) {
1342 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1343 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1344 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1345 } else {
1346 $protected = '';
1347 }
1348 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1349 }
1350 $outText .= '</ul>';
1351 }
1352 wfProfileOut( __METHOD__ );
1353 return $outText;
1354 }
1355
1356 /**
1357 * Format a size in bytes for output, using an appropriate
1358 * unit (B, KB, MB or GB) according to the magnitude in question
1359 *
1360 * @param $size Size to format
1361 * @return string
1362 */
1363 public function formatSize( $size ) {
1364 global $wgLang;
1365 return htmlspecialchars( $wgLang->formatSize( $size ) );
1366 }
1367
1368 /**
1369 * Given the id of an interface element, constructs the appropriate title
1370 * and accesskey attributes from the system messages. (Note, this is usu-
1371 * ally the id but isn't always, because sometimes the accesskey needs to
1372 * go on a different element than the id, for reverse-compatibility, etc.)
1373 *
1374 * @param string $name Id of the element, minus prefixes.
1375 * @return string title and accesskey attributes, ready to drop in an
1376 * element (e.g., ' title="This does something [x]" accesskey="x"').
1377 */
1378 public function tooltipAndAccesskey($name) {
1379 $fname="Linker::tooltipAndAccesskey";
1380 wfProfileIn($fname);
1381 $out = '';
1382
1383 $tooltip = wfMsg('tooltip-'.$name);
1384 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1385 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1386 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1387 $out .= ' title="'.htmlspecialchars($tooltip);
1388 }
1389 $accesskey = wfMsg('accesskey-'.$name);
1390 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1391 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1392 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1393 } elseif ($out) {
1394 $out .= '"';
1395 }
1396 wfProfileOut($fname);
1397 return $out;
1398 }
1399
1400 /**
1401 * Given the id of an interface element, constructs the appropriate title
1402 * attribute from the system messages. (Note, this is usually the id but
1403 * isn't always, because sometimes the accesskey needs to go on a different
1404 * element than the id, for reverse-compatibility, etc.)
1405 *
1406 * @param string $name Id of the element, minus prefixes.
1407 * @return string title attribute, ready to drop in an element
1408 * (e.g., ' title="This does something"').
1409 */
1410 public function tooltip($name) {
1411 $out = '';
1412
1413 $tooltip = wfMsg('tooltip-'.$name);
1414 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1415 $out = ' title="'.htmlspecialchars($tooltip).'"';
1416 }
1417
1418 return $out;
1419 }
1420 }