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