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