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