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