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