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