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