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