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