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