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