Fix regression from r38325 -- caused first character of section name in a history...
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Split off some of the internal bits from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin. For the moment, Skin is a descendent class of
6 * Linker. In the future, it should probably be further split so that every
7 * other bit of the wiki doesn't have to go loading up Skin to get at it.
8 *
9 * @ingroup Skins
10 */
11 class Linker {
12
13 /**
14 * Flags for userToolLinks()
15 */
16 const TOOL_LINKS_NOBLOCK = 1;
17
18 function __construct() {}
19
20 /**
21 * @deprecated
22 */
23 function postParseLinkColour( $s = null ) {
24 wfDeprecated( __METHOD__ );
25 return null;
26 }
27
28 /**
29 * Get the appropriate HTML attributes to add to the "a" element of an ex-
30 * ternal link, as created by [wikisyntax].
31 *
32 * @param string $title The (unescaped) title text for the link
33 * @param string $unused Unused
34 * @param string $class The contents of the class attribute; if an empty
35 * string is passed, which is the default value, defaults to 'external'.
36 */
37 function getExternalLinkAttributes( $title, $unused = null, $class='' ) {
38 return $this->getLinkAttributesInternal( $title, $class, 'external' );
39 }
40
41 /**
42 * Get the appropriate HTML attributes to add to the "a" element of an in-
43 * terwiki link.
44 *
45 * @param string $title The title text for the link, URL-encoded (???) but
46 * not HTML-escaped
47 * @param string $unused Unused
48 * @param string $class The contents of the class attribute; if an empty
49 * string is passed, which is the default value, defaults to 'external'.
50 */
51 function getInterwikiLinkAttributes( $title, $unused = null, $class='' ) {
52 global $wgContLang;
53
54 # FIXME: We have a whole bunch of handling here that doesn't happen in
55 # getExternalLinkAttributes, why?
56 $title = urldecode( $title );
57 $title = $wgContLang->checkTitleEncoding( $title );
58 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
59
60 return $this->getLinkAttributesInternal( $title, $class, 'external' );
61 }
62
63 /**
64 * Get the appropriate HTML attributes to add to the "a" element of an in-
65 * ternal link.
66 *
67 * @param string $title The title text for the link, URL-encoded (???) but
68 * not HTML-escaped
69 * @param string $unused Unused
70 * @param string $class The contents of the class attribute, default none
71 */
72 function getInternalLinkAttributes( $title, $unused = null, $class='' ) {
73 $title = urldecode( $title );
74 $title = str_replace( '_', ' ', $title );
75 return $this->getLinkAttributesInternal( $title, $class );
76 }
77
78 /**
79 * Get the appropriate HTML attributes to add to the "a" element of an in-
80 * ternal link, given the Title object for the page we want to link to.
81 *
82 * @param Title $nt The Title object
83 * @param string $unused Unused
84 * @param string $class The contents of the class attribute, default none
85 * @param mixed $title Optional (unescaped) string to use in the title
86 * attribute; if false, default to the name of the page we're linking to
87 */
88 function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
89 if( $title === false ) {
90 $title = $nt->getPrefixedText();
91 }
92 return $this->getLinkAttributesInternal( $title, $class );
93 }
94
95 /**
96 * Common code for getLinkAttributesX functions
97 */
98 private function getLinkAttributesInternal( $title, $class, $classDefault = false ) {
99 $title = htmlspecialchars( $title );
100 if( $class === '' and $classDefault !== false ) {
101 # FIXME: Parameter defaults the hard way! We should just have
102 # $class = 'external' or whatever as the default in the externally-
103 # exposed functions, not $class = ''.
104 $class = $classDefault;
105 }
106 $class = htmlspecialchars( $class );
107 $r = '';
108 if( $class !== '' ) {
109 $r .= " class=\"$class\"";
110 }
111 $r .= " title=\"$title\"";
112 return $r;
113 }
114
115 /**
116 * Return the CSS colour of a known link
117 *
118 * @param Title $t
119 * @param integer $threshold user defined threshold
120 * @return string CSS class
121 */
122 function getLinkColour( $t, $threshold ) {
123 $colour = '';
124 if ( $t->isRedirect() ) {
125 # Page is a redirect
126 $colour = 'mw-redirect';
127 } elseif ( $threshold > 0 && $t->getLength() < $threshold && MWNamespace::isContent( $t->getNamespace() ) ) {
128 # Page is a stub
129 $colour = 'stub';
130 }
131 return $colour;
132 }
133
134 /**
135 * This function returns an HTML link to the given target. It serves a few
136 * purposes:
137 * 1) If $target is a Title, the correct URL to link to will be figured
138 * out automatically.
139 * 2) It automatically adds the usual classes for various types of link
140 * targets: "new" for red links, "stub" for short articles, etc.
141 * 3) It escapes all attribute values safely so there's no risk of XSS.
142 * 4) It provides a default tooltip if the target is a Title (the page
143 * name of the target).
144 * link() replaces the old functions in the makeLink() family.
145 *
146 * @param $target Title Can currently only be a Title, but this may
147 * change to support Images, literal URLs, etc.
148 * @param $text string The HTML contents of the <a> element, i.e.,
149 * the link text. This is raw HTML and will not be escaped. If null,
150 * defaults to the prefixed text of the Title; or if the Title is just a
151 * fragment, the contents of the fragment.
152 * @param $query array The query string to append to the URL
153 * you're linking to, in key => value array form. Query keys and values
154 * will be URL-encoded.
155 * @param $customAttribs array A key => value array of extra HTML attri-
156 * butes, such as title and class. (href is ignored.) Classes will be
157 * merged with the default classes, while other attributes will replace
158 * default attributes. All passed attribute values will be HTML-escaped.
159 * A false attribute value means to suppress that attribute.
160 * @param $options mixed String or array of strings:
161 * 'known': Page is known to exist, so don't check if it does.
162 * 'broken': Page is known not to exist, so don't check if it does.
163 * 'noclasses': Don't add any classes automatically (includes "new",
164 * "stub", "mw-redirect"). Only use the class attribute provided, if
165 * any.
166 * @return string HTML <a> attribute
167 */
168 public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
169 wfProfileIn( __METHOD__ );
170 if( !($target instanceof Title) ) {
171 throw new MWException( 'Linker::link passed invalid target' );
172 }
173 $options = (array)$options;
174
175 # Normalize the Title if it's a special page
176 if( $target->getNamespace() == NS_SPECIAL ) {
177 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $target->getDBkey() );
178 if( $name ) {
179 $target = SpecialPage::getTitleFor( $name, $subpage );
180 }
181 }
182
183 # If we don't know whether the page exists, let's find out.
184 if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
185 if( $target->getNamespace() == NS_SPECIAL ) {
186 if( SpecialPage::exists( $target->getDbKey() ) ) {
187 $options []= 'known';
188 } else {
189 $options []= 'broken';
190 }
191 } elseif( $target->isAlwaysKnown() or
192 ($target->getPrefixedText() == '' and $target->getFragment() != '')
193 or $target->exists() ) {
194 $options []= 'known';
195 } else {
196 # Either it exists
197 $options []= 'broken';
198 }
199 }
200
201 # Note: we want the href attribute first, for prettiness.
202 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
203 $attribs = array_merge(
204 $attribs,
205 $this->linkAttribs( $target, $customAttribs, $options )
206 );
207 if( is_null( $text ) ) {
208 $text = $this->linkText( $target, $options );
209 }
210
211 $ret = Xml::element( 'a', $attribs, $text, false );
212
213 wfProfileOut( __METHOD__ );
214 return $ret;
215 }
216
217 private function linkUrl( $target, $query, $options ) {
218 # If it's a broken link, add the appropriate query pieces. This over-
219 # writes the default action!
220 if( in_array( 'broken', $options ) ) {
221 $query['action'] = 'edit';
222 $query['redlink'] = '1';
223 }
224 # 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 htmlspecialchars( $target->getFragment() );
291 }
292 return htmlspecialchars( $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 $encName = htmlspecialchars( $userText );
1043 if( $userId == 0 ) {
1044 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
1045 } else {
1046 $page = Title::makeTitle( NS_USER, $userText );
1047 }
1048 return $this->link( $page, $encName );
1049 }
1050
1051 /**
1052 * Generate standard user tool links (talk, contributions, block link, etc.)
1053 *
1054 * @param int $userId User identifier
1055 * @param string $userText User name or IP address
1056 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
1057 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
1058 * @param int $edits, user edit count (optional, for performance)
1059 * @return string
1060 */
1061 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
1062 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
1063 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1064 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
1065
1066 $items = array();
1067 if( $talkable ) {
1068 $items[] = $this->userTalkLink( $userId, $userText );
1069 }
1070 if( $userId ) {
1071 // check if the user has an edit
1072 $attribs = array();
1073 if( $redContribsWhenNoEdits ) {
1074 $count = !is_null($edits) ? $edits : User::edits( $userId );
1075 if( $count == 0 ) {
1076 $attribs['class'] = 'new';
1077 }
1078 }
1079 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1080
1081 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1082 }
1083 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
1084 $items[] = $this->blockLink( $userId, $userText );
1085 }
1086
1087 if( $items ) {
1088 return ' (' . implode( ' | ', $items ) . ')';
1089 } else {
1090 return '';
1091 }
1092 }
1093
1094 /**
1095 * Alias for userToolLinks( $userId, $userText, true );
1096 * @param int $userId User identifier
1097 * @param string $userText User name or IP address
1098 * @param int $edits, user edit count (optional, for performance)
1099 */
1100 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
1101 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
1102 }
1103
1104
1105 /**
1106 * @param $userId Integer: user id in database.
1107 * @param $userText String: user name in database.
1108 * @return string HTML fragment with user talk link
1109 * @private
1110 */
1111 function userTalkLink( $userId, $userText ) {
1112 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1113 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1114 return $userTalkLink;
1115 }
1116
1117 /**
1118 * @param $userId Integer: userid
1119 * @param $userText String: user name in database.
1120 * @return string HTML fragment with block link
1121 * @private
1122 */
1123 function blockLink( $userId, $userText ) {
1124 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
1125 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
1126 return $blockLink;
1127 }
1128
1129 /**
1130 * Generate a user link if the current user is allowed to view it
1131 * @param $rev Revision object.
1132 * @param $isPublic, bool, show only if all users can see it
1133 * @return string HTML
1134 */
1135 function revUserLink( $rev, $isPublic = false ) {
1136 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1137 $link = wfMsgHtml( 'rev-deleted-user' );
1138 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1139 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
1140 } else {
1141 $link = wfMsgHtml( 'rev-deleted-user' );
1142 }
1143 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1144 return '<span class="history-deleted">' . $link . '</span>';
1145 }
1146 return $link;
1147 }
1148
1149 /**
1150 * Generate a user tool link cluster if the current user is allowed to view it
1151 * @param $rev Revision object.
1152 * @param $isPublic, bool, show only if all users can see it
1153 * @return string HTML
1154 */
1155 function revUserTools( $rev, $isPublic = false ) {
1156 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1157 $link = wfMsgHtml( 'rev-deleted-user' );
1158 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1159 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
1160 ' ' . $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
1161 } else {
1162 $link = wfMsgHtml( 'rev-deleted-user' );
1163 }
1164 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1165 return ' <span class="history-deleted">' . $link . '</span>';
1166 }
1167 return $link;
1168 }
1169
1170 /**
1171 * This function is called by all recent changes variants, by the page history,
1172 * and by the user contributions list. It is responsible for formatting edit
1173 * comments. It escapes any HTML in the comment, but adds some CSS to format
1174 * auto-generated comments (from section editing) and formats [[wikilinks]].
1175 *
1176 * @author Erik Moeller <moeller@scireview.de>
1177 *
1178 * Note: there's not always a title to pass to this function.
1179 * Since you can't set a default parameter for a reference, I've turned it
1180 * temporarily to a value pass. Should be adjusted further. --brion
1181 *
1182 * @param string $comment
1183 * @param mixed $title Title object (to generate link to the section in autocomment) or null
1184 * @param bool $local Whether section links should refer to local page
1185 */
1186 function formatComment($comment, $title = NULL, $local = false) {
1187 wfProfileIn( __METHOD__ );
1188
1189 # Sanitize text a bit:
1190 $comment = str_replace( "\n", " ", $comment );
1191 $comment = htmlspecialchars( $comment );
1192
1193 # Render autocomments and make links:
1194 $comment = $this->formatAutoComments( $comment, $title, $local );
1195 $comment = $this->formatLinksInComment( $comment );
1196
1197 wfProfileOut( __METHOD__ );
1198 return $comment;
1199 }
1200
1201 /**
1202 * The pattern for autogen comments is / * foo * /, which makes for
1203 * some nasty regex.
1204 * We look for all comments, match any text before and after the comment,
1205 * add a separator where needed and format the comment itself with CSS
1206 * Called by Linker::formatComment.
1207 *
1208 * @param string $comment Comment text
1209 * @param object $title An optional title object used to links to sections
1210 * @return string $comment formatted comment
1211 *
1212 * @todo Document the $local parameter.
1213 */
1214 private function formatAutocomments( $comment, $title = null, $local = false ) {
1215 $match = array();
1216 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
1217 $pre=$match[1];
1218 $auto=$match[2];
1219 $post=$match[3];
1220 $link='';
1221 if( $title ) {
1222 $section = $auto;
1223
1224 # Generate a valid anchor name from the section title.
1225 # Hackish, but should generally work - we strip wiki
1226 # syntax, including the magic [[: that is used to
1227 # "link rather than show" in case of images and
1228 # interlanguage links.
1229 $section = str_replace( '[[:', '', $section );
1230 $section = str_replace( '[[', '', $section );
1231 $section = str_replace( ']]', '', $section );
1232 if ( $local ) {
1233 $sectionTitle = Title::newFromText( '#' . $section );
1234 } else {
1235 $sectionTitle = wfClone( $title );
1236 $sectionTitle->mFragment = $section;
1237 }
1238 $link = $this->link( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1239 }
1240 $auto = $link . $auto;
1241 if( $pre ) {
1242 # written summary $presep autocomment (summary /* section */)
1243 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1244 }
1245 if( $post ) {
1246 # autocomment $postsep written summary (/* section */ summary)
1247 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1248 }
1249 $auto = '<span class="autocomment">' . $auto . '</span>';
1250 $comment = $pre . $auto . $post;
1251 }
1252
1253 return $comment;
1254 }
1255
1256 /**
1257 * Formats wiki links and media links in text; all other wiki formatting
1258 * is ignored
1259 *
1260 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1261 * @param string $comment Text to format links in
1262 * @return string
1263 */
1264 public function formatLinksInComment( $comment ) {
1265 return preg_replace_callback(
1266 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1267 array( $this, 'formatLinksInCommentCallback' ),
1268 $comment );
1269 }
1270
1271 protected function formatLinksInCommentCallback( $match ) {
1272 global $wgContLang;
1273
1274 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1275 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1276
1277 $comment = $match[0];
1278
1279 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1280 if( strpos( $match[1], '%' ) !== false ) {
1281 $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1282 }
1283
1284 # Handle link renaming [[foo|text]] will show link as "text"
1285 if( "" != $match[3] ) {
1286 $text = $match[3];
1287 } else {
1288 $text = $match[1];
1289 }
1290 $submatch = array();
1291 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1292 # Media link; trail not supported.
1293 $linkRegexp = '/\[\[(.*?)\]\]/';
1294 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1295 } else {
1296 # Other kind of link
1297 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1298 $trail = $submatch[1];
1299 } else {
1300 $trail = "";
1301 }
1302 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1303 if (isset($match[1][0]) && $match[1][0] == ':')
1304 $match[1] = substr($match[1], 1);
1305 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1306 }
1307 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1308
1309 return $comment;
1310 }
1311
1312 /**
1313 * Wrap a comment in standard punctuation and formatting if
1314 * it's non-empty, otherwise return empty string.
1315 *
1316 * @param string $comment
1317 * @param mixed $title Title object (to generate link to section in autocomment) or null
1318 * @param bool $local Whether section links should refer to local page
1319 *
1320 * @return string
1321 */
1322 function commentBlock( $comment, $title = NULL, $local = false ) {
1323 // '*' used to be the comment inserted by the software way back
1324 // in antiquity in case none was provided, here for backwards
1325 // compatability, acc. to brion -ævar
1326 if( $comment == '' || $comment == '*' ) {
1327 return '';
1328 } else {
1329 $formatted = $this->formatComment( $comment, $title, $local );
1330 return " <span class=\"comment\">($formatted)</span>";
1331 }
1332 }
1333
1334 /**
1335 * Wrap and format the given revision's comment block, if the current
1336 * user is allowed to view it.
1337 *
1338 * @param Revision $rev
1339 * @param bool $local Whether section links should refer to local page
1340 * @param $isPublic, show only if all users can see it
1341 * @return string HTML
1342 */
1343 function revComment( Revision $rev, $local = false, $isPublic = false ) {
1344 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1345 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1346 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1347 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1348 } else {
1349 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1350 }
1351 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1352 return " <span class=\"history-deleted\">$block</span>";
1353 }
1354 return $block;
1355 }
1356
1357 public function formatRevisionSize( $size ) {
1358 if ( $size == 0 ) {
1359 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1360 } else {
1361 global $wgLang;
1362 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1363 $stxt = "($stxt)";
1364 }
1365 $stxt = htmlspecialchars( $stxt );
1366 return "<span class=\"history-size\">$stxt</span>";
1367 }
1368
1369 /** @todo document */
1370 function tocIndent() {
1371 return "\n<ul>";
1372 }
1373
1374 /** @todo document */
1375 function tocUnindent($level) {
1376 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1377 }
1378
1379 /**
1380 * parameter level defines if we are on an indentation level
1381 */
1382 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1383 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1384 $anchor . '"><span class="tocnumber">' .
1385 $tocnumber . '</span> <span class="toctext">' .
1386 $tocline . '</span></a>';
1387 }
1388
1389 /** @todo document */
1390 function tocLineEnd() {
1391 return "</li>\n";
1392 }
1393
1394 /** @todo document */
1395 function tocList($toc) {
1396 global $wgJsMimeType;
1397 $title = wfMsgHtml('toc') ;
1398 return
1399 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1400 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1401 . $toc
1402 # no trailing newline, script should not be wrapped in a
1403 # paragraph
1404 . "</ul>\n</td></tr></table>"
1405 . '<script type="' . $wgJsMimeType . '">'
1406 . ' if (window.showTocToggle) {'
1407 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1408 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1409 . ' showTocToggle();'
1410 . ' } '
1411 . "</script>\n";
1412 }
1413
1414 /**
1415 * Used to generate section edit links that point to "other" pages
1416 * (sections that are really part of included pages).
1417 *
1418 * @param $title Title string.
1419 * @param $section Integer: section number.
1420 */
1421 public function editSectionLinkForOther( $title, $section ) {
1422 wfDeprecated( __METHOD__ );
1423 $title = Title::newFromText( $title );
1424 return $this->doEditSectionLink( $title, $section );
1425 }
1426
1427 /**
1428 * @param $nt Title object.
1429 * @param $section Integer: section number.
1430 * @param $hint Link String: title, or default if omitted or empty
1431 */
1432 public function editSectionLink( Title $nt, $section, $hint = '' ) {
1433 wfDeprecated( __METHOD__ );
1434 if( $hint === '' ) {
1435 # No way to pass an actual empty $hint here! The new interface al-
1436 # lows this, so we have to do this for compatibility.
1437 $hint = null;
1438 }
1439 return $this->doEditSectionLink( $nt, $section, $hint );
1440 }
1441
1442 /**
1443 * Create a section edit link. This supersedes editSectionLink() and
1444 * editSectionLinkForOther().
1445 *
1446 * @param $nt Title The title being linked to (may not be the same as
1447 * $wgTitle, if the section is included from a template)
1448 * @param $section string The designation of the section being pointed to,
1449 * to be included in the link, like "&section=$section"
1450 * @param $tooltip string The tooltip to use for the link: will be escaped
1451 * and wrapped in the 'editsectionhint' message
1452 * @return string HTML to use for edit link
1453 */
1454 public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1455 $attribs = array();
1456 if( !is_null( $tooltip ) ) {
1457 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1458 }
1459 $url = $this->link( $nt, wfMsg('editsection'),
1460 $attribs,
1461 array( 'action' => 'edit', 'section' => $section ),
1462 array( 'noclasses', 'known' )
1463 );
1464
1465 # Run the old hook. This takes up half of the function . . . hopefully
1466 # we can rid of it someday.
1467 $attribs = '';
1468 if( $tooltip ) {
1469 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1470 $attribs = " title=\"$attribs\"";
1471 }
1472 $result = null;
1473 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $url, &$result ) );
1474 if( !is_null( $result ) ) {
1475 # For reverse compatibility, add the brackets *after* the hook is
1476 # run, and even add them to hook-provided text. (This is the main
1477 # reason that the EditSectionLink hook is deprecated in favor of
1478 # DoEditSectionLink: it can't change the brackets or the span.)
1479 $result = wfMsgHtml( 'editsection-brackets', $url );
1480 return "<span class=\"editsection\">$result</span>";
1481 }
1482
1483 # Add the brackets and the span, and *then* run the nice new hook, with
1484 # clean and non-redundant arguments.
1485 $result = wfMsgHtml( 'editsection-brackets', $url );
1486 $result = "<span class=\"editsection\">$result</span>";
1487
1488 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1489 return $result;
1490 }
1491
1492 /**
1493 * Create a headline for content
1494 *
1495 * @param int $level The level of the headline (1-6)
1496 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1497 * This *must* be at least '>' for no attribs
1498 * @param string $anchor The anchor to give the headline (the bit after the #)
1499 * @param string $text The text of the header
1500 * @param string $link HTML to add for the section edit link
1501 *
1502 * @return string HTML headline
1503 */
1504 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1505 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1506 }
1507
1508 /**
1509 * Split a link trail, return the "inside" portion and the remainder of the trail
1510 * as a two-element array
1511 *
1512 * @static
1513 */
1514 static function splitTrail( $trail ) {
1515 static $regex = false;
1516 if ( $regex === false ) {
1517 global $wgContLang;
1518 $regex = $wgContLang->linkTrail();
1519 }
1520 $inside = '';
1521 if ( '' != $trail ) {
1522 $m = array();
1523 if ( preg_match( $regex, $trail, $m ) ) {
1524 $inside = $m[1];
1525 $trail = $m[2];
1526 }
1527 }
1528 return array( $inside, $trail );
1529 }
1530
1531 /**
1532 * Generate a rollback link for a given revision. Currently it's the
1533 * caller's responsibility to ensure that the revision is the top one. If
1534 * it's not, of course, the user will get an error message.
1535 *
1536 * If the calling page is called with the parameter &bot=1, all rollback
1537 * links also get that parameter. It causes the edit itself and the rollback
1538 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1539 * changes, so this allows sysops to combat a busy vandal without bothering
1540 * other users.
1541 *
1542 * @param Revision $rev
1543 */
1544 function generateRollback( $rev ) {
1545 return '<span class="mw-rollback-link">['
1546 . $this->buildRollbackLink( $rev )
1547 . ']</span>';
1548 }
1549
1550 /**
1551 * Build a raw rollback link, useful for collections of "tool" links
1552 *
1553 * @param Revision $rev
1554 * @return string
1555 */
1556 public function buildRollbackLink( $rev ) {
1557 global $wgRequest, $wgUser;
1558 $title = $rev->getTitle();
1559 $query = array(
1560 'action' => 'rollback',
1561 'from' => $rev->getUserText()
1562 );
1563 if( $wgRequest->getBool( 'bot' ) ) {
1564 $query['bot'] = '1';
1565 }
1566 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1567 $rev->getUserText() ) );
1568 return $this->link( $title, wfMsgHtml( 'rollbacklink' ), array(),
1569 $query, array( 'known', 'noclasses' ) );
1570 }
1571
1572 /**
1573 * Returns HTML for the "templates used on this page" list.
1574 *
1575 * @param array $templates Array of templates from Article::getUsedTemplate
1576 * or similar
1577 * @param bool $preview Whether this is for a preview
1578 * @param bool $section Whether this is for a section edit
1579 * @return string HTML output
1580 */
1581 public function formatTemplates( $templates, $preview = false, $section = false) {
1582 global $wgUser;
1583 wfProfileIn( __METHOD__ );
1584
1585 $sk = $wgUser->getSkin();
1586
1587 $outText = '';
1588 if ( count( $templates ) > 0 ) {
1589 # Do a batch existence check
1590 $batch = new LinkBatch;
1591 foreach( $templates as $title ) {
1592 $batch->addObj( $title );
1593 }
1594 $batch->execute();
1595
1596 # Construct the HTML
1597 $outText = '<div class="mw-templatesUsedExplanation">';
1598 if ( $preview ) {
1599 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1600 } elseif ( $section ) {
1601 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1602 } else {
1603 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1604 }
1605 $outText .= '</div><ul>';
1606
1607 usort( $templates, array( 'Title', 'compare' ) );
1608 foreach ( $templates as $titleObj ) {
1609 $r = $titleObj->getRestrictions( 'edit' );
1610 if ( in_array( 'sysop', $r ) ) {
1611 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1612 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1613 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1614 } else {
1615 $protected = '';
1616 }
1617 $outText .= '<li>' . $sk->link( $titleObj ) . ' ' . $protected . '</li>';
1618 }
1619 $outText .= '</ul>';
1620 }
1621 wfProfileOut( __METHOD__ );
1622 return $outText;
1623 }
1624
1625 /**
1626 * Returns HTML for the "hidden categories on this page" list.
1627 *
1628 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1629 * or similar
1630 * @return string HTML output
1631 */
1632 public function formatHiddenCategories( $hiddencats) {
1633 global $wgUser, $wgLang;
1634 wfProfileIn( __METHOD__ );
1635
1636 $sk = $wgUser->getSkin();
1637
1638 $outText = '';
1639 if ( count( $hiddencats ) > 0 ) {
1640 # Construct the HTML
1641 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1642 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1643 $outText .= '</div><ul>';
1644
1645 foreach ( $hiddencats as $titleObj ) {
1646 $outText .= '<li>' . $sk->link( $titleObj, null, array(), array(), 'known' ) . '</li>'; # If it's hidden, it must exist - no need to check with a LinkBatch
1647 }
1648 $outText .= '</ul>';
1649 }
1650 wfProfileOut( __METHOD__ );
1651 return $outText;
1652 }
1653
1654 /**
1655 * Format a size in bytes for output, using an appropriate
1656 * unit (B, KB, MB or GB) according to the magnitude in question
1657 *
1658 * @param $size Size to format
1659 * @return string
1660 */
1661 public function formatSize( $size ) {
1662 global $wgLang;
1663 return htmlspecialchars( $wgLang->formatSize( $size ) );
1664 }
1665
1666 /**
1667 * Given the id of an interface element, constructs the appropriate title
1668 * and accesskey attributes from the system messages. (Note, this is usu-
1669 * ally the id but isn't always, because sometimes the accesskey needs to
1670 * go on a different element than the id, for reverse-compatibility, etc.)
1671 *
1672 * @param string $name Id of the element, minus prefixes.
1673 * @return string title and accesskey attributes, ready to drop in an
1674 * element (e.g., ' title="This does something [x]" accesskey="x"').
1675 */
1676 public function tooltipAndAccesskey($name) {
1677 $fname="Linker::tooltipAndAccesskey";
1678 wfProfileIn($fname);
1679 $out = '';
1680
1681 $tooltip = wfMsg('tooltip-'.$name);
1682 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1683 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1684 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1685 $out .= ' title="'.htmlspecialchars($tooltip);
1686 }
1687 $accesskey = wfMsg('accesskey-'.$name);
1688 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1689 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1690 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1691 } elseif ($out) {
1692 $out .= '"';
1693 }
1694 wfProfileOut($fname);
1695 return $out;
1696 }
1697
1698 /**
1699 * Given the id of an interface element, constructs the appropriate title
1700 * attribute from the system messages. (Note, this is usually the id but
1701 * isn't always, because sometimes the accesskey needs to go on a different
1702 * element than the id, for reverse-compatibility, etc.)
1703 *
1704 * @param string $name Id of the element, minus prefixes.
1705 * @return string title attribute, ready to drop in an element
1706 * (e.g., ' title="This does something"').
1707 */
1708 public function tooltip($name) {
1709 $out = '';
1710
1711 $tooltip = wfMsg('tooltip-'.$name);
1712 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1713 $out = ' title="'.htmlspecialchars($tooltip).'"';
1714 }
1715
1716 return $out;
1717 }
1718 }