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