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