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