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