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