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