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