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