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