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