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