(bug 14771) Thumbnail links to individual DjVu pages have two "page" parameters
[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 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
886 # So we don't need to pass it here in $query. However, the URL for the
887 # zoom icon still needs it, so we make a unique query for it. See bug 14771
888 $url = $title->getLocalURL( $query );
889 if( $page ) {
890 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
891 }
892
893 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
894
895 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
896 if( !$exists ) {
897 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
898 $zoomicon = '';
899 } elseif ( !$thumb ) {
900 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
901 $zoomicon = '';
902 } else {
903 $s .= $thumb->toHtml( array(
904 'alt' => $fp['alt'],
905 'title' => $fp['title'],
906 'img-class' => 'thumbimage',
907 'desc-link' => true,
908 'desc-query' => $query ) );
909 if ( isset( $fp['framed'] ) ) {
910 $zoomicon="";
911 } else {
912 $zoomicon = '<div class="magnify">'.
913 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
914 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
915 'width="15" height="11" alt="" /></a></div>';
916 }
917 }
918 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
919 return str_replace("\n", ' ', $s);
920 }
921
922 /**
923 * Make a "broken" link to an image
924 *
925 * @param Title $title Image title
926 * @param string $text Link label
927 * @param string $query Query string
928 * @param string $trail Link trail
929 * @param string $prefix Link prefix
930 * @param bool $time, a file of a certain timestamp was requested
931 * @return string
932 */
933 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
934 global $wgEnableUploads;
935 if( $title instanceof Title ) {
936 wfProfileIn( __METHOD__ );
937 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
938 if( $wgEnableUploads && !$currentExists ) {
939 $upload = SpecialPage::getTitleFor( 'Upload' );
940 if( $text == '' )
941 $text = htmlspecialchars( $title->getPrefixedText() );
942 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
943 if( $redir ) {
944 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
945 }
946 $q = 'wpDestFile=' . $title->getPartialUrl();
947 if( $query != '' )
948 $q .= '&' . $query;
949 list( $inside, $trail ) = self::splitTrail( $trail );
950 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
951 wfProfileOut( __METHOD__ );
952 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
953 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
954 } else {
955 wfProfileOut( __METHOD__ );
956 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
957 }
958 } else {
959 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
960 }
961 }
962
963 /** @deprecated use Linker::makeMediaLinkObj() */
964 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
965 $nt = Title::makeTitleSafe( NS_FILE, $name );
966 return $this->makeMediaLinkObj( $nt, $text, $time );
967 }
968
969 /**
970 * Create a direct link to a given uploaded file.
971 *
972 * @param $title Title object.
973 * @param $text String: pre-sanitized HTML
974 * @param $time string: time image was created
975 * @return string HTML
976 *
977 * @public
978 * @todo Handle invalid or missing images better.
979 */
980 function makeMediaLinkObj( $title, $text = '', $time = false ) {
981 if( is_null( $title ) ) {
982 ### HOTFIX. Instead of breaking, return empty string.
983 return $text;
984 } else {
985 $img = wfFindFile( $title, $time );
986 if( $img ) {
987 $url = $img->getURL();
988 $class = 'internal';
989 } else {
990 $upload = SpecialPage::getTitleFor( 'Upload' );
991 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
992 $class = 'new';
993 }
994 $alt = htmlspecialchars( $title->getText() );
995 if( $text == '' ) {
996 $text = $alt;
997 }
998 $u = htmlspecialchars( $url );
999 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
1000 }
1001 }
1002
1003 /** @todo document */
1004 function specialLink( $name, $key = '' ) {
1005 global $wgContLang;
1006
1007 if ( '' == $key ) { $key = strtolower( $name ); }
1008 $pn = $wgContLang->ucfirst( $name );
1009 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
1010 wfMsg( $key ) );
1011 }
1012
1013 /**
1014 * Make an external link
1015 * @param String $url URL to link to
1016 * @param String $text text of link
1017 * @param boolean $escape Do we escape the link text?
1018 * @param String $linktype Type of external link. Gets added to the classes
1019 * @param array $attribs Array of extra attributes to <a>
1020 *
1021 * @TODO! @FIXME! This is a really crappy implementation. $linktype and
1022 * 'external' are mashed into the class attrib for the link (which is made
1023 * into a string). Then, if we've got additional params in $attribs, we
1024 * add to it. People using this might want to change the classes (or other
1025 * default link attributes), but passing $attribsText is just messy. Would
1026 * make a lot more sense to make put the classes into $attribs, let the
1027 * hook play with them, *then* expand it all at once.
1028 */
1029 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
1030 $attribsText = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
1031 $url = htmlspecialchars( $url );
1032 if( $escape ) {
1033 $text = htmlspecialchars( $text );
1034 }
1035 $link = '';
1036 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
1037 if(!$success) {
1038 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true);
1039 return $link;
1040 }
1041 if ( $attribs ) {
1042 $attribsText .= Xml::expandAttributes( $attribs );
1043 }
1044 return '<a href="'.$url.'"'.$attribsText.'>'.$text.'</a>';
1045 }
1046
1047 /**
1048 * Make user link (or user contributions for unregistered users)
1049 * @param $userId Integer: user id in database.
1050 * @param $userText String: user name in database
1051 * @return string HTML fragment
1052 * @private
1053 */
1054 function userLink( $userId, $userText ) {
1055 if( $userId == 0 ) {
1056 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
1057 } else {
1058 $page = Title::makeTitle( NS_USER, $userText );
1059 }
1060 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
1061 }
1062
1063 /**
1064 * Generate standard user tool links (talk, contributions, block link, etc.)
1065 *
1066 * @param int $userId User identifier
1067 * @param string $userText User name or IP address
1068 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
1069 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
1070 * @param int $edits, user edit count (optional, for performance)
1071 * @return string
1072 */
1073 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
1074 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
1075 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1076 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
1077
1078 $items = array();
1079 if( $talkable ) {
1080 $items[] = $this->userTalkLink( $userId, $userText );
1081 }
1082 if( $userId ) {
1083 // check if the user has an edit
1084 $attribs = array();
1085 if( $redContribsWhenNoEdits ) {
1086 $count = !is_null($edits) ? $edits : User::edits( $userId );
1087 if( $count == 0 ) {
1088 $attribs['class'] = 'new';
1089 }
1090 }
1091 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1092
1093 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1094 }
1095 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
1096 $items[] = $this->blockLink( $userId, $userText );
1097 }
1098
1099 if( $items ) {
1100 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
1101 } else {
1102 return '';
1103 }
1104 }
1105
1106 /**
1107 * Alias for userToolLinks( $userId, $userText, true );
1108 * @param int $userId User identifier
1109 * @param string $userText User name or IP address
1110 * @param int $edits, user edit count (optional, for performance)
1111 */
1112 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
1113 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
1114 }
1115
1116
1117 /**
1118 * @param $userId Integer: user id in database.
1119 * @param $userText String: user name in database.
1120 * @return string HTML fragment with user talk link
1121 * @private
1122 */
1123 function userTalkLink( $userId, $userText ) {
1124 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1125 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1126 return $userTalkLink;
1127 }
1128
1129 /**
1130 * @param $userId Integer: userid
1131 * @param $userText String: user name in database.
1132 * @return string HTML fragment with block link
1133 * @private
1134 */
1135 function blockLink( $userId, $userText ) {
1136 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
1137 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
1138 return $blockLink;
1139 }
1140
1141 /**
1142 * Generate a user link if the current user is allowed to view it
1143 * @param $rev Revision object.
1144 * @param $isPublic, bool, show only if all users can see it
1145 * @return string HTML
1146 */
1147 function revUserLink( $rev, $isPublic = false ) {
1148 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1149 $link = wfMsgHtml( 'rev-deleted-user' );
1150 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1151 $link = $this->userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1152 $rev->getUserText( Revision::FOR_THIS_USER ) );
1153 } else {
1154 $link = wfMsgHtml( 'rev-deleted-user' );
1155 }
1156 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1157 return '<span class="history-deleted">' . $link . '</span>';
1158 }
1159 return $link;
1160 }
1161
1162 /**
1163 * Generate a user tool link cluster if the current user is allowed to view it
1164 * @param $rev Revision object.
1165 * @param $isPublic, bool, show only if all users can see it
1166 * @return string HTML
1167 */
1168 function revUserTools( $rev, $isPublic = false ) {
1169 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1170 $link = wfMsgHtml( 'rev-deleted-user' );
1171 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1172 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1173 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1174 $link = $this->userLink( $userId, $userText ) .
1175 ' ' . $this->userToolLinks( $userId, $userText );
1176 } else {
1177 $link = wfMsgHtml( 'rev-deleted-user' );
1178 }
1179 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1180 return ' <span class="history-deleted">' . $link . '</span>';
1181 }
1182 return $link;
1183 }
1184
1185 /**
1186 * This function is called by all recent changes variants, by the page history,
1187 * and by the user contributions list. It is responsible for formatting edit
1188 * comments. It escapes any HTML in the comment, but adds some CSS to format
1189 * auto-generated comments (from section editing) and formats [[wikilinks]].
1190 *
1191 * @author Erik Moeller <moeller@scireview.de>
1192 *
1193 * Note: there's not always a title to pass to this function.
1194 * Since you can't set a default parameter for a reference, I've turned it
1195 * temporarily to a value pass. Should be adjusted further. --brion
1196 *
1197 * @param string $comment
1198 * @param mixed $title Title object (to generate link to the section in autocomment) or null
1199 * @param bool $local Whether section links should refer to local page
1200 */
1201 function formatComment($comment, $title = NULL, $local = false) {
1202 wfProfileIn( __METHOD__ );
1203
1204 # Sanitize text a bit:
1205 $comment = str_replace( "\n", " ", $comment );
1206 # Allow HTML entities (for bug 13815)
1207 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1208
1209 # Render autocomments and make links:
1210 $comment = $this->formatAutoComments( $comment, $title, $local );
1211 $comment = $this->formatLinksInComment( $comment );
1212
1213 wfProfileOut( __METHOD__ );
1214 return $comment;
1215 }
1216
1217 /**
1218 * The pattern for autogen comments is / * foo * /, which makes for
1219 * some nasty regex.
1220 * We look for all comments, match any text before and after the comment,
1221 * add a separator where needed and format the comment itself with CSS
1222 * Called by Linker::formatComment.
1223 *
1224 * @param string $comment Comment text
1225 * @param object $title An optional title object used to links to sections
1226 * @return string $comment formatted comment
1227 *
1228 * @todo Document the $local parameter.
1229 */
1230 private function formatAutocomments( $comment, $title = null, $local = false ) {
1231 // Bah!
1232 $this->autocommentTitle = $title;
1233 $this->autocommentLocal = $local;
1234 $comment = preg_replace_callback(
1235 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1236 array( $this, 'formatAutocommentsCallback' ),
1237 $comment );
1238 unset( $this->autocommentTitle );
1239 unset( $this->autocommentLocal );
1240 return $comment;
1241 }
1242
1243 private function formatAutocommentsCallback( $match ) {
1244 $title = $this->autocommentTitle;
1245 $local = $this->autocommentLocal;
1246
1247 $pre=$match[1];
1248 $auto=$match[2];
1249 $post=$match[3];
1250 $link='';
1251 if( $title ) {
1252 $section = $auto;
1253
1254 # Generate a valid anchor name from the section title.
1255 # Hackish, but should generally work - we strip wiki
1256 # syntax, including the magic [[: that is used to
1257 # "link rather than show" in case of images and
1258 # interlanguage links.
1259 $section = str_replace( '[[:', '', $section );
1260 $section = str_replace( '[[', '', $section );
1261 $section = str_replace( ']]', '', $section );
1262 if ( $local ) {
1263 $sectionTitle = Title::newFromText( '#' . $section );
1264 } else {
1265 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1266 $title->getDBkey(), $section );
1267 }
1268 if ( $sectionTitle ) {
1269 $link = $this->link( $sectionTitle,
1270 wfMsgForContent( 'sectionlink' ), array(), array(),
1271 'noclasses' );
1272 } else {
1273 $link = '';
1274 }
1275 }
1276 $auto = "$link$auto";
1277 if( $pre ) {
1278 # written summary $presep autocomment (summary /* section */)
1279 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1280 }
1281 if( $post ) {
1282 # autocomment $postsep written summary (/* section */ summary)
1283 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1284 }
1285 $auto = '<span class="autocomment">' . $auto . '</span>';
1286 $comment = $pre . $auto . $post;
1287 return $comment;
1288 }
1289
1290 /**
1291 * Formats wiki links and media links in text; all other wiki formatting
1292 * is ignored
1293 *
1294 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1295 * @param string $comment Text to format links in
1296 * @return string
1297 */
1298 public function formatLinksInComment( $comment ) {
1299 return preg_replace_callback(
1300 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1301 array( $this, 'formatLinksInCommentCallback' ),
1302 $comment );
1303 }
1304
1305 protected function formatLinksInCommentCallback( $match ) {
1306 global $wgContLang;
1307
1308 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1309 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1310
1311 $comment = $match[0];
1312
1313 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1314 if( strpos( $match[1], '%' ) !== false ) {
1315 $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1316 }
1317
1318 # Handle link renaming [[foo|text]] will show link as "text"
1319 if( "" != $match[3] ) {
1320 $text = $match[3];
1321 } else {
1322 $text = $match[1];
1323 }
1324 $submatch = array();
1325 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1326 # Media link; trail not supported.
1327 $linkRegexp = '/\[\[(.*?)\]\]/';
1328 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1329 } else {
1330 # Other kind of link
1331 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1332 $trail = $submatch[1];
1333 } else {
1334 $trail = "";
1335 }
1336 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1337 if (isset($match[1][0]) && $match[1][0] == ':')
1338 $match[1] = substr($match[1], 1);
1339 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1340 }
1341 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1342
1343 return $comment;
1344 }
1345
1346 /**
1347 * Wrap a comment in standard punctuation and formatting if
1348 * it's non-empty, otherwise return empty string.
1349 *
1350 * @param string $comment
1351 * @param mixed $title Title object (to generate link to section in autocomment) or null
1352 * @param bool $local Whether section links should refer to local page
1353 *
1354 * @return string
1355 */
1356 function commentBlock( $comment, $title = NULL, $local = false ) {
1357 // '*' used to be the comment inserted by the software way back
1358 // in antiquity in case none was provided, here for backwards
1359 // compatability, acc. to brion -ævar
1360 if( $comment == '' || $comment == '*' ) {
1361 return '';
1362 } else {
1363 $formatted = $this->formatComment( $comment, $title, $local );
1364 return " <span class=\"comment\">($formatted)</span>";
1365 }
1366 }
1367
1368 /**
1369 * Wrap and format the given revision's comment block, if the current
1370 * user is allowed to view it.
1371 *
1372 * @param Revision $rev
1373 * @param bool $local Whether section links should refer to local page
1374 * @param $isPublic, show only if all users can see it
1375 * @return string HTML
1376 */
1377 function revComment( Revision $rev, $local = false, $isPublic = false ) {
1378 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1379 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1380 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1381 $block = $this->commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1382 $rev->getTitle(), $local );
1383 } else {
1384 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1385 }
1386 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1387 return " <span class=\"history-deleted\">$block</span>";
1388 }
1389 return $block;
1390 }
1391
1392 public function formatRevisionSize( $size ) {
1393 if ( $size == 0 ) {
1394 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1395 } else {
1396 global $wgLang;
1397 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1398 $stxt = "($stxt)";
1399 }
1400 $stxt = htmlspecialchars( $stxt );
1401 return "<span class=\"history-size\">$stxt</span>";
1402 }
1403
1404 /** @todo document */
1405 function tocIndent() {
1406 return "\n<ul>";
1407 }
1408
1409 /** @todo document */
1410 function tocUnindent($level) {
1411 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1412 }
1413
1414 /**
1415 * parameter level defines if we are on an indentation level
1416 */
1417 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1418 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1419 $anchor . '"><span class="tocnumber">' .
1420 $tocnumber . '</span> <span class="toctext">' .
1421 $tocline . '</span></a>';
1422 }
1423
1424 /** @todo document */
1425 function tocLineEnd() {
1426 return "</li>\n";
1427 }
1428
1429 /** @todo document */
1430 function tocList($toc) {
1431 global $wgJsMimeType;
1432 $title = wfMsgHtml('toc') ;
1433 return
1434 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1435 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1436 . $toc
1437 # no trailing newline, script should not be wrapped in a
1438 # paragraph
1439 . "</ul>\n</td></tr></table>"
1440 . '<script type="' . $wgJsMimeType . '">'
1441 . ' if (window.showTocToggle) {'
1442 . ' var tocShowText = "' . Xml::escapeJsString( wfMsg('showtoc') ) . '";'
1443 . ' var tocHideText = "' . Xml::escapeJsString( wfMsg('hidetoc') ) . '";'
1444 . ' showTocToggle();'
1445 . ' } '
1446 . "</script>\n";
1447 }
1448
1449 /**
1450 * Used to generate section edit links that point to "other" pages
1451 * (sections that are really part of included pages).
1452 *
1453 * @param $title Title string.
1454 * @param $section Integer: section number.
1455 */
1456 public function editSectionLinkForOther( $title, $section ) {
1457 wfDeprecated( __METHOD__ );
1458 $title = Title::newFromText( $title );
1459 return $this->doEditSectionLink( $title, $section );
1460 }
1461
1462 /**
1463 * @param $nt Title object.
1464 * @param $section Integer: section number.
1465 * @param $hint Link String: title, or default if omitted or empty
1466 */
1467 public function editSectionLink( Title $nt, $section, $hint = '' ) {
1468 wfDeprecated( __METHOD__ );
1469 if( $hint === '' ) {
1470 # No way to pass an actual empty $hint here! The new interface al-
1471 # lows this, so we have to do this for compatibility.
1472 $hint = null;
1473 }
1474 return $this->doEditSectionLink( $nt, $section, $hint );
1475 }
1476
1477 /**
1478 * Create a section edit link. This supersedes editSectionLink() and
1479 * editSectionLinkForOther().
1480 *
1481 * @param $nt Title The title being linked to (may not be the same as
1482 * $wgTitle, if the section is included from a template)
1483 * @param $section string The designation of the section being pointed to,
1484 * to be included in the link, like "&section=$section"
1485 * @param $tooltip string The tooltip to use for the link: will be escaped
1486 * and wrapped in the 'editsectionhint' message
1487 * @return string HTML to use for edit link
1488 */
1489 public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1490 $attribs = array();
1491 if( !is_null( $tooltip ) ) {
1492 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1493 }
1494 $link = $this->link( $nt, wfMsg('editsection'),
1495 $attribs,
1496 array( 'action' => 'edit', 'section' => $section ),
1497 array( 'noclasses', 'known' )
1498 );
1499
1500 # Run the old hook. This takes up half of the function . . . hopefully
1501 # we can rid of it someday.
1502 $attribs = '';
1503 if( $tooltip ) {
1504 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1505 $attribs = " title=\"$attribs\"";
1506 }
1507 $result = null;
1508 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result ) );
1509 if( !is_null( $result ) ) {
1510 # For reverse compatibility, add the brackets *after* the hook is
1511 # run, and even add them to hook-provided text. (This is the main
1512 # reason that the EditSectionLink hook is deprecated in favor of
1513 # DoEditSectionLink: it can't change the brackets or the span.)
1514 $result = wfMsgHtml( 'editsection-brackets', $result );
1515 return "<span class=\"editsection\">$result</span>";
1516 }
1517
1518 # Add the brackets and the span, and *then* run the nice new hook, with
1519 # clean and non-redundant arguments.
1520 $result = wfMsgHtml( 'editsection-brackets', $link );
1521 $result = "<span class=\"editsection\">$result</span>";
1522
1523 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1524 return $result;
1525 }
1526
1527 /**
1528 * Create a headline for content
1529 *
1530 * @param int $level The level of the headline (1-6)
1531 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1532 * This *must* be at least '>' for no attribs
1533 * @param string $anchor The anchor to give the headline (the bit after the #)
1534 * @param string $text The text of the header
1535 * @param string $link HTML to add for the section edit link
1536 * @param mixed $legacyAnchor A second, optional anchor to give for
1537 * backward compatibility (false to omit)
1538 *
1539 * @return string HTML headline
1540 */
1541 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1542 $ret = "<a name=\"$anchor\" id=\"$anchor\"></a>"
1543 . "<h$level$attribs"
1544 . $link
1545 . " <span class=\"mw-headline\">$text</span>"
1546 . "</h$level>";
1547 if ( $legacyAnchor !== false ) {
1548 $ret = "<a name=\"$legacyAnchor\" id=\"$legacyAnchor\"></a>$ret";
1549 }
1550 return $ret;
1551 }
1552
1553 /**
1554 * Split a link trail, return the "inside" portion and the remainder of the trail
1555 * as a two-element array
1556 *
1557 * @static
1558 */
1559 static function splitTrail( $trail ) {
1560 static $regex = false;
1561 if ( $regex === false ) {
1562 global $wgContLang;
1563 $regex = $wgContLang->linkTrail();
1564 }
1565 $inside = '';
1566 if ( '' != $trail ) {
1567 $m = array();
1568 if ( preg_match( $regex, $trail, $m ) ) {
1569 $inside = $m[1];
1570 $trail = $m[2];
1571 }
1572 }
1573 return array( $inside, $trail );
1574 }
1575
1576 /**
1577 * Generate a rollback link for a given revision. Currently it's the
1578 * caller's responsibility to ensure that the revision is the top one. If
1579 * it's not, of course, the user will get an error message.
1580 *
1581 * If the calling page is called with the parameter &bot=1, all rollback
1582 * links also get that parameter. It causes the edit itself and the rollback
1583 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1584 * changes, so this allows sysops to combat a busy vandal without bothering
1585 * other users.
1586 *
1587 * @param Revision $rev
1588 */
1589 function generateRollback( $rev ) {
1590 return '<span class="mw-rollback-link">['
1591 . $this->buildRollbackLink( $rev )
1592 . ']</span>';
1593 }
1594
1595 /**
1596 * Build a raw rollback link, useful for collections of "tool" links
1597 *
1598 * @param Revision $rev
1599 * @return string
1600 */
1601 public function buildRollbackLink( $rev ) {
1602 global $wgRequest, $wgUser;
1603 $title = $rev->getTitle();
1604 $query = array(
1605 'action' => 'rollback',
1606 'from' => $rev->getUserText()
1607 );
1608 if( $wgRequest->getBool( 'bot' ) ) {
1609 $query['bot'] = '1';
1610 $query['hidediff'] = '1'; // bug 15999
1611 }
1612 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1613 $rev->getUserText() ) );
1614 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1615 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1616 $query, array( 'known', 'noclasses' ) );
1617 }
1618
1619 /**
1620 * Returns HTML for the "templates used on this page" list.
1621 *
1622 * @param array $templates Array of templates from Article::getUsedTemplate
1623 * or similar
1624 * @param bool $preview Whether this is for a preview
1625 * @param bool $section Whether this is for a section edit
1626 * @return string HTML output
1627 */
1628 public function formatTemplates( $templates, $preview = false, $section = false ) {
1629 wfProfileIn( __METHOD__ );
1630
1631 $outText = '';
1632 if ( count( $templates ) > 0 ) {
1633 # Do a batch existence check
1634 $batch = new LinkBatch;
1635 foreach( $templates as $title ) {
1636 $batch->addObj( $title );
1637 }
1638 $batch->execute();
1639
1640 # Construct the HTML
1641 $outText = '<div class="mw-templatesUsedExplanation">';
1642 if ( $preview ) {
1643 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1644 } elseif ( $section ) {
1645 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1646 } else {
1647 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1648 }
1649 $outText .= "</div><ul>\n";
1650
1651 usort( $templates, array( 'Title', 'compare' ) );
1652 foreach ( $templates as $titleObj ) {
1653 $r = $titleObj->getRestrictions( 'edit' );
1654 if ( in_array( 'sysop', $r ) ) {
1655 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1656 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1657 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1658 } else {
1659 $protected = '';
1660 }
1661 if( $titleObj->quickUserCan( 'edit' ) ) {
1662 $editLink = $this->makeLinkObj( $titleObj, wfMsg('editlink'), 'action=edit' );
1663 } else {
1664 $editLink = $this->makeLinkObj( $titleObj, wfMsg('viewsourcelink'), 'action=edit' );
1665 }
1666 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1667 }
1668 $outText .= '</ul>';
1669 }
1670 wfProfileOut( __METHOD__ );
1671 return $outText;
1672 }
1673
1674 /**
1675 * Returns HTML for the "hidden categories on this page" list.
1676 *
1677 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1678 * or similar
1679 * @return string HTML output
1680 */
1681 public function formatHiddenCategories( $hiddencats ) {
1682 global $wgLang;
1683 wfProfileIn( __METHOD__ );
1684
1685 $outText = '';
1686 if ( count( $hiddencats ) > 0 ) {
1687 # Construct the HTML
1688 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1689 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1690 $outText .= "</div><ul>\n";
1691
1692 foreach ( $hiddencats as $titleObj ) {
1693 $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
1694 }
1695 $outText .= '</ul>';
1696 }
1697 wfProfileOut( __METHOD__ );
1698 return $outText;
1699 }
1700
1701 /**
1702 * Format a size in bytes for output, using an appropriate
1703 * unit (B, KB, MB or GB) according to the magnitude in question
1704 *
1705 * @param $size Size to format
1706 * @return string
1707 */
1708 public function formatSize( $size ) {
1709 global $wgLang;
1710 return htmlspecialchars( $wgLang->formatSize( $size ) );
1711 }
1712
1713 /**
1714 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
1715 */
1716 public function tooltipAndAccesskey( $name ) {
1717 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1718 # no attribute" instead of "output '' as value for attribute", this
1719 # would be three lines.
1720 $attribs = array(
1721 'title' => $this->titleAttrib( $name, 'withaccess' ),
1722 'accesskey' => $this->accesskey( $name )
1723 );
1724 if ( $attribs['title'] === false ) {
1725 unset( $attribs['title'] );
1726 }
1727 if ( $attribs['accesskey'] === false ) {
1728 unset( $attribs['accesskey'] );
1729 }
1730 return Xml::expandAttributes( $attribs );
1731 }
1732
1733 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
1734 public function tooltip( $name, $options = null ) {
1735 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1736 # no attribute" instead of "output '' as value for attribute", this
1737 # would be two lines.
1738 $tooltip = $this->titleAttrib( $name, $options );
1739 if ( $tooltip === false ) {
1740 return '';
1741 }
1742 return Xml::expandAttributes( array(
1743 'title' => $this->titleAttrib( $name, $options )
1744 ) );
1745 }
1746
1747 /**
1748 * Given the id of an interface element, constructs the appropriate title
1749 * attribute from the system messages. (Note, this is usually the id but
1750 * isn't always, because sometimes the accesskey needs to go on a different
1751 * element than the id, for reverse-compatibility, etc.)
1752 *
1753 * @param string $name Id of the element, minus prefixes.
1754 * @param mixed $options null or the string 'withaccess' to add an access-
1755 * key hint
1756 * @return string Contents of the title attribute (which you must HTML-
1757 * escape), or false for no title attribute
1758 */
1759 public function titleAttrib( $name, $options = null ) {
1760 wfProfileIn( __METHOD__ );
1761
1762 $tooltip = wfMsg( "tooltip-$name" );
1763 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1764 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1765
1766 # Message equal to '-' means suppress it.
1767 if ( wfEmptyMsg( "tooltip-$name", $tooltip ) || $tooltip == '-' ) {
1768 $tooltip = false;
1769 }
1770
1771 if ( $options == 'withaccess' ) {
1772 $accesskey = $this->accesskey( $name );
1773 if( $accesskey !== false ) {
1774 if ( $tooltip === false || $tooltip === '' ) {
1775 $tooltip = "[$accesskey]";
1776 } else {
1777 $tooltip .= " [$accesskey]";
1778 }
1779 }
1780 }
1781
1782 wfProfileOut( __METHOD__ );
1783 return $tooltip;
1784 }
1785
1786 /**
1787 * Given the id of an interface element, constructs the appropriate
1788 * accesskey attribute from the system messages. (Note, this is usually
1789 * the id but isn't always, because sometimes the accesskey needs to go on
1790 * a different element than the id, for reverse-compatibility, etc.)
1791 *
1792 * @param string $name Id of the element, minus prefixes.
1793 * @return string Contents of the accesskey attribute (which you must HTML-
1794 * escape), or false for no accesskey attribute
1795 */
1796 public function accesskey( $name ) {
1797 wfProfileIn( __METHOD__ );
1798
1799 $accesskey = wfMsg( "accesskey-$name" );
1800
1801 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1802 # attribute, but this is broken for accesskey: that might be a useful
1803 # value.
1804 if( $accesskey != '' && $accesskey != '-' && !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1805 wfProfileOut( __METHOD__ );
1806 return $accesskey;
1807 }
1808
1809 wfProfileOut( __METHOD__ );
1810 return false;
1811 }
1812
1813 /**
1814 * Creates a (show/hide) link for deleting revisions/log entries
1815 *
1816 * @param array $query Query parameters to be passed to link()
1817 * @param bool $restricted Set to true to use a <strong> instead of a <span>
1818 *
1819 * @return string HTML <a> link to Special:Revisiondelete, wrapped in a
1820 * span to allow for customization of appearance with CSS
1821 */
1822 public function revDeleteLink( $query = array(), $restricted = false ) {
1823 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1824 $text = wfMsgHtml( 'rev-delundel' );
1825 $tag = $restricted ? 'strong' : 'span';
1826 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1827 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1828 }
1829 }