3485889992a80d49b0a2916836a82c4860a93d66
[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 $comment = htmlspecialchars( $comment );
1164
1165 # Render autocomments and make links:
1166 $comment = $this->formatAutoComments( $comment, $title, $local );
1167 $comment = $this->formatLinksInComment( $comment );
1168
1169 wfProfileOut( __METHOD__ );
1170 return $comment;
1171 }
1172
1173 /**
1174 * The pattern for autogen comments is / * foo * /, which makes for
1175 * some nasty regex.
1176 * We look for all comments, match any text before and after the comment,
1177 * add a separator where needed and format the comment itself with CSS
1178 * Called by Linker::formatComment.
1179 *
1180 * @param string $comment Comment text
1181 * @param object $title An optional title object used to links to sections
1182 * @return string $comment formatted comment
1183 *
1184 * @todo Document the $local parameter.
1185 */
1186 private function formatAutocomments( $comment, $title = null, $local = false ) {
1187 // Bah!
1188 $this->autocommentTitle = $title;
1189 $this->autocommentLocal = $local;
1190 $comment = preg_replace_callback(
1191 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1192 array( $this, 'formatAutocommentsCallback' ),
1193 $comment );
1194 unset( $this->autocommentTitle );
1195 unset( $this->autocommentLocal );
1196 return $comment;
1197 }
1198
1199 private function formatAutocommentsCallback( $match ) {
1200 $title = $this->autocommentTitle;
1201 $local = $this->autocommentLocal;
1202
1203 $pre=$match[1];
1204 $auto=$match[2];
1205 $post=$match[3];
1206 $link='';
1207 if( $title ) {
1208 $section = $auto;
1209
1210 # Generate a valid anchor name from the section title.
1211 # Hackish, but should generally work - we strip wiki
1212 # syntax, including the magic [[: that is used to
1213 # "link rather than show" in case of images and
1214 # interlanguage links.
1215 $section = str_replace( '[[:', '', $section );
1216 $section = str_replace( '[[', '', $section );
1217 $section = str_replace( ']]', '', $section );
1218 if ( $local ) {
1219 $sectionTitle = Title::newFromText( '#' . $section );
1220 } else {
1221 $sectionTitle = clone( $title );
1222 $sectionTitle->mFragment = $section;
1223 }
1224 $link = $this->link( $sectionTitle,
1225 wfMsgForContent( 'sectionlink' ), array(), array(),
1226 'noclasses' );
1227 }
1228 $auto = $link . $auto;
1229 if( $pre ) {
1230 # written summary $presep autocomment (summary /* section */)
1231 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1232 }
1233 if( $post ) {
1234 # autocomment $postsep written summary (/* section */ summary)
1235 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1236 }
1237 $auto = '<span class="autocomment">' . $auto . '</span>';
1238 $comment = $pre . $auto . $post;
1239 return $comment;
1240 }
1241
1242 /**
1243 * Formats wiki links and media links in text; all other wiki formatting
1244 * is ignored
1245 *
1246 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1247 * @param string $comment Text to format links in
1248 * @return string
1249 */
1250 public function formatLinksInComment( $comment ) {
1251 return preg_replace_callback(
1252 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1253 array( $this, 'formatLinksInCommentCallback' ),
1254 $comment );
1255 }
1256
1257 protected function formatLinksInCommentCallback( $match ) {
1258 global $wgContLang;
1259
1260 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1261 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1262
1263 $comment = $match[0];
1264
1265 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1266 if( strpos( $match[1], '%' ) !== false ) {
1267 $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1268 }
1269
1270 # Handle link renaming [[foo|text]] will show link as "text"
1271 if( "" != $match[3] ) {
1272 $text = $match[3];
1273 } else {
1274 $text = $match[1];
1275 }
1276 $submatch = array();
1277 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1278 # Media link; trail not supported.
1279 $linkRegexp = '/\[\[(.*?)\]\]/';
1280 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1281 } else {
1282 # Other kind of link
1283 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1284 $trail = $submatch[1];
1285 } else {
1286 $trail = "";
1287 }
1288 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1289 if (isset($match[1][0]) && $match[1][0] == ':')
1290 $match[1] = substr($match[1], 1);
1291 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1292 }
1293 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1294
1295 return $comment;
1296 }
1297
1298 /**
1299 * Wrap a comment in standard punctuation and formatting if
1300 * it's non-empty, otherwise return empty string.
1301 *
1302 * @param string $comment
1303 * @param mixed $title Title object (to generate link to section in autocomment) or null
1304 * @param bool $local Whether section links should refer to local page
1305 *
1306 * @return string
1307 */
1308 function commentBlock( $comment, $title = NULL, $local = false ) {
1309 // '*' used to be the comment inserted by the software way back
1310 // in antiquity in case none was provided, here for backwards
1311 // compatability, acc. to brion -ævar
1312 if( $comment == '' || $comment == '*' ) {
1313 return '';
1314 } else {
1315 $formatted = $this->formatComment( $comment, $title, $local );
1316 return " <span class=\"comment\">($formatted)</span>";
1317 }
1318 }
1319
1320 /**
1321 * Wrap and format the given revision's comment block, if the current
1322 * user is allowed to view it.
1323 *
1324 * @param Revision $rev
1325 * @param bool $local Whether section links should refer to local page
1326 * @param $isPublic, show only if all users can see it
1327 * @return string HTML
1328 */
1329 function revComment( Revision $rev, $local = false, $isPublic = false ) {
1330 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1331 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1332 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1333 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1334 } else {
1335 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1336 }
1337 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1338 return " <span class=\"history-deleted\">$block</span>";
1339 }
1340 return $block;
1341 }
1342
1343 public function formatRevisionSize( $size ) {
1344 if ( $size == 0 ) {
1345 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1346 } else {
1347 global $wgLang;
1348 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1349 $stxt = "($stxt)";
1350 }
1351 $stxt = htmlspecialchars( $stxt );
1352 return "<span class=\"history-size\">$stxt</span>";
1353 }
1354
1355 /** @todo document */
1356 function tocIndent() {
1357 return "\n<ul>";
1358 }
1359
1360 /** @todo document */
1361 function tocUnindent($level) {
1362 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1363 }
1364
1365 /**
1366 * parameter level defines if we are on an indentation level
1367 */
1368 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1369 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1370 $anchor . '"><span class="tocnumber">' .
1371 $tocnumber . '</span> <span class="toctext">' .
1372 $tocline . '</span></a>';
1373 }
1374
1375 /** @todo document */
1376 function tocLineEnd() {
1377 return "</li>\n";
1378 }
1379
1380 /** @todo document */
1381 function tocList($toc) {
1382 global $wgJsMimeType;
1383 $title = wfMsgHtml('toc') ;
1384 return
1385 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1386 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1387 . $toc
1388 # no trailing newline, script should not be wrapped in a
1389 # paragraph
1390 . "</ul>\n</td></tr></table>"
1391 . '<script type="' . $wgJsMimeType . '">'
1392 . ' if (window.showTocToggle) {'
1393 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1394 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1395 . ' showTocToggle();'
1396 . ' } '
1397 . "</script>\n";
1398 }
1399
1400 /**
1401 * Used to generate section edit links that point to "other" pages
1402 * (sections that are really part of included pages).
1403 *
1404 * @param $title Title string.
1405 * @param $section Integer: section number.
1406 */
1407 public function editSectionLinkForOther( $title, $section ) {
1408 wfDeprecated( __METHOD__ );
1409 $title = Title::newFromText( $title );
1410 return $this->doEditSectionLink( $title, $section );
1411 }
1412
1413 /**
1414 * @param $nt Title object.
1415 * @param $section Integer: section number.
1416 * @param $hint Link String: title, or default if omitted or empty
1417 */
1418 public function editSectionLink( Title $nt, $section, $hint = '' ) {
1419 wfDeprecated( __METHOD__ );
1420 if( $hint === '' ) {
1421 # No way to pass an actual empty $hint here! The new interface al-
1422 # lows this, so we have to do this for compatibility.
1423 $hint = null;
1424 }
1425 return $this->doEditSectionLink( $nt, $section, $hint );
1426 }
1427
1428 /**
1429 * Create a section edit link. This supersedes editSectionLink() and
1430 * editSectionLinkForOther().
1431 *
1432 * @param $nt Title The title being linked to (may not be the same as
1433 * $wgTitle, if the section is included from a template)
1434 * @param $section string The designation of the section being pointed to,
1435 * to be included in the link, like "&section=$section"
1436 * @param $tooltip string The tooltip to use for the link: will be escaped
1437 * and wrapped in the 'editsectionhint' message
1438 * @return string HTML to use for edit link
1439 */
1440 public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1441 $attribs = array();
1442 if( !is_null( $tooltip ) ) {
1443 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1444 }
1445 $url = $this->link( $nt, wfMsg('editsection'),
1446 $attribs,
1447 array( 'action' => 'edit', 'section' => $section ),
1448 array( 'noclasses', 'known' )
1449 );
1450
1451 # Run the old hook. This takes up half of the function . . . hopefully
1452 # we can rid of it someday.
1453 $attribs = '';
1454 if( $tooltip ) {
1455 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1456 $attribs = " title=\"$attribs\"";
1457 }
1458 $result = null;
1459 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $url, &$result ) );
1460 if( !is_null( $result ) ) {
1461 # For reverse compatibility, add the brackets *after* the hook is
1462 # run, and even add them to hook-provided text. (This is the main
1463 # reason that the EditSectionLink hook is deprecated in favor of
1464 # DoEditSectionLink: it can't change the brackets or the span.)
1465 $result = wfMsgHtml( 'editsection-brackets', $url );
1466 return "<span class=\"editsection\">$result</span>";
1467 }
1468
1469 # Add the brackets and the span, and *then* run the nice new hook, with
1470 # clean and non-redundant arguments.
1471 $result = wfMsgHtml( 'editsection-brackets', $url );
1472 $result = "<span class=\"editsection\">$result</span>";
1473
1474 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1475 return $result;
1476 }
1477
1478 /**
1479 * Create a headline for content
1480 *
1481 * @param int $level The level of the headline (1-6)
1482 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1483 * This *must* be at least '>' for no attribs
1484 * @param string $anchor The anchor to give the headline (the bit after the #)
1485 * @param string $text The text of the header
1486 * @param string $link HTML to add for the section edit link
1487 *
1488 * @return string HTML headline
1489 */
1490 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1491 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1492 }
1493
1494 /**
1495 * Split a link trail, return the "inside" portion and the remainder of the trail
1496 * as a two-element array
1497 *
1498 * @static
1499 */
1500 static function splitTrail( $trail ) {
1501 static $regex = false;
1502 if ( $regex === false ) {
1503 global $wgContLang;
1504 $regex = $wgContLang->linkTrail();
1505 }
1506 $inside = '';
1507 if ( '' != $trail ) {
1508 $m = array();
1509 if ( preg_match( $regex, $trail, $m ) ) {
1510 $inside = $m[1];
1511 $trail = $m[2];
1512 }
1513 }
1514 return array( $inside, $trail );
1515 }
1516
1517 /**
1518 * Generate a rollback link for a given revision. Currently it's the
1519 * caller's responsibility to ensure that the revision is the top one. If
1520 * it's not, of course, the user will get an error message.
1521 *
1522 * If the calling page is called with the parameter &bot=1, all rollback
1523 * links also get that parameter. It causes the edit itself and the rollback
1524 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1525 * changes, so this allows sysops to combat a busy vandal without bothering
1526 * other users.
1527 *
1528 * @param Revision $rev
1529 */
1530 function generateRollback( $rev ) {
1531 return '<span class="mw-rollback-link">['
1532 . $this->buildRollbackLink( $rev )
1533 . ']</span>';
1534 }
1535
1536 /**
1537 * Build a raw rollback link, useful for collections of "tool" links
1538 *
1539 * @param Revision $rev
1540 * @return string
1541 */
1542 public function buildRollbackLink( $rev ) {
1543 global $wgRequest, $wgUser;
1544 $title = $rev->getTitle();
1545 $query = array(
1546 'action' => 'rollback',
1547 'from' => $rev->getUserText()
1548 );
1549 if( $wgRequest->getBool( 'bot' ) ) {
1550 $query['bot'] = '1';
1551 }
1552 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1553 $rev->getUserText() ) );
1554 return $this->link( $title, wfMsgHtml( 'rollbacklink' ), array(),
1555 $query, array( 'known', 'noclasses' ) );
1556 }
1557
1558 /**
1559 * Returns HTML for the "templates used on this page" list.
1560 *
1561 * @param array $templates Array of templates from Article::getUsedTemplate
1562 * or similar
1563 * @param bool $preview Whether this is for a preview
1564 * @param bool $section Whether this is for a section edit
1565 * @return string HTML output
1566 */
1567 public function formatTemplates( $templates, $preview = false, $section = false) {
1568 global $wgUser;
1569 wfProfileIn( __METHOD__ );
1570
1571 $sk = $wgUser->getSkin();
1572
1573 $outText = '';
1574 if ( count( $templates ) > 0 ) {
1575 # Do a batch existence check
1576 $batch = new LinkBatch;
1577 foreach( $templates as $title ) {
1578 $batch->addObj( $title );
1579 }
1580 $batch->execute();
1581
1582 # Construct the HTML
1583 $outText = '<div class="mw-templatesUsedExplanation">';
1584 if ( $preview ) {
1585 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1586 } elseif ( $section ) {
1587 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1588 } else {
1589 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1590 }
1591 $outText .= '</div><ul>';
1592
1593 usort( $templates, array( 'Title', 'compare' ) );
1594 foreach ( $templates as $titleObj ) {
1595 $r = $titleObj->getRestrictions( 'edit' );
1596 if ( in_array( 'sysop', $r ) ) {
1597 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1598 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1599 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1600 } else {
1601 $protected = '';
1602 }
1603 $outText .= '<li>' . $sk->link( $titleObj ) . ' ' . $protected . '</li>';
1604 }
1605 $outText .= '</ul>';
1606 }
1607 wfProfileOut( __METHOD__ );
1608 return $outText;
1609 }
1610
1611 /**
1612 * Returns HTML for the "hidden categories on this page" list.
1613 *
1614 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1615 * or similar
1616 * @return string HTML output
1617 */
1618 public function formatHiddenCategories( $hiddencats) {
1619 global $wgUser, $wgLang;
1620 wfProfileIn( __METHOD__ );
1621
1622 $sk = $wgUser->getSkin();
1623
1624 $outText = '';
1625 if ( count( $hiddencats ) > 0 ) {
1626 # Construct the HTML
1627 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1628 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1629 $outText .= '</div><ul>';
1630
1631 foreach ( $hiddencats as $titleObj ) {
1632 $outText .= '<li>' . $sk->link( $titleObj, null, array(), array(), 'known' ) . '</li>'; # If it's hidden, it must exist - no need to check with a LinkBatch
1633 }
1634 $outText .= '</ul>';
1635 }
1636 wfProfileOut( __METHOD__ );
1637 return $outText;
1638 }
1639
1640 /**
1641 * Format a size in bytes for output, using an appropriate
1642 * unit (B, KB, MB or GB) according to the magnitude in question
1643 *
1644 * @param $size Size to format
1645 * @return string
1646 */
1647 public function formatSize( $size ) {
1648 global $wgLang;
1649 return htmlspecialchars( $wgLang->formatSize( $size ) );
1650 }
1651
1652 /**
1653 * Given the id of an interface element, constructs the appropriate title
1654 * and accesskey attributes from the system messages. (Note, this is usu-
1655 * ally the id but isn't always, because sometimes the accesskey needs to
1656 * go on a different element than the id, for reverse-compatibility, etc.)
1657 *
1658 * @param string $name Id of the element, minus prefixes.
1659 * @return string title and accesskey attributes, ready to drop in an
1660 * element (e.g., ' title="This does something [x]" accesskey="x"').
1661 */
1662 public function tooltipAndAccesskey( $name ) {
1663 wfProfileIn( __METHOD__ );
1664 $attribs = array();
1665
1666 $tooltip = wfMsg( "tooltip-$name" );
1667 if( !wfEmptyMsg( "tooltip-$name", $tooltip ) && $tooltip != '-' ) {
1668 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1669 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1670 $attribs['title'] = $tooltip;
1671 }
1672
1673 $accesskey = wfMsg( "accesskey-$name" );
1674 if( $accesskey && $accesskey != '-' &&
1675 !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1676 if( isset( $attribs['title'] ) ) {
1677 $attribs['title'] .= " [$accesskey]";
1678 }
1679 $attribs['accesskey'] = $accesskey;
1680 }
1681
1682 $ret = Xml::expandAttributes( $attribs );
1683 wfProfileOut( __METHOD__ );
1684 return $ret;
1685 }
1686
1687 /**
1688 * Given the id of an interface element, constructs the appropriate title
1689 * attribute from the system messages. (Note, this is usually the id but
1690 * isn't always, because sometimes the accesskey needs to go on a different
1691 * element than the id, for reverse-compatibility, etc.)
1692 *
1693 * @param string $name Id of the element, minus prefixes.
1694 * @param mixed $options null or the string 'withaccess' to add an access-
1695 * key hint
1696 * @return string title attribute, ready to drop in an element
1697 * (e.g., ' title="This does something"').
1698 */
1699 public function tooltip( $name, $options = null ) {
1700 wfProfileIn( __METHOD__ );
1701
1702 $attribs = array();
1703
1704 $tooltip = wfMsg( "tooltip-$name" );
1705 if( !wfEmptyMsg( "tooltip-$name", $tooltip ) && $tooltip != '-' ) {
1706 $attribs['title'] = $tooltip;
1707 }
1708
1709 if( isset( $attribs['title'] ) && $options == 'withaccess' ) {
1710 $accesskey = wfMsg( "accesskey-$name" );
1711 if( $accesskey && $accesskey != '-' &&
1712 !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1713 $attribs['title'] .= " [$accesskey]";
1714 }
1715 }
1716
1717 $ret = Xml::expandAttributes( $attribs );
1718 wfProfileOut( __METHOD__ );
1719 return $ret;
1720 }
1721 }