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