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