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