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