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