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