As Brion points out, Linker::linkUrl() duplicates wfArrayToCGI. Fix that, and also...
[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 && $t->getLength() < $threshold && MWNamespace::isContent( $t->getNamespace() ) ) {
128 # Page is a stub
129 $colour = 'stub';
130 }
131 return $colour;
132 }
133
134 /**
135 * This function returns an HTML link to the given target. It serves a few
136 * purposes:
137 * 1) If $target is a Title, the correct URL to link to will be figured
138 * out automatically.
139 * 2) It automatically adds the usual classes for various types of link
140 * targets: "new" for red links, "stub" for short articles, etc.
141 * 3) It escapes all attribute values safely so there's no risk of XSS.
142 * 4) It provides a default tooltip if the target is a Title (the page
143 * name of the target).
144 * link() replaces the old functions in the makeLink() family.
145 *
146 * @param $target Title Can currently only be a Title, but this may
147 * change to support Images, literal URLs, etc.
148 * @param $text string The HTML contents of the <a> element, i.e.,
149 * the link text. This is raw HTML and will not be escaped. If null,
150 * defaults to the page name of the Title.
151 * @param $query array The query string to append to the URL
152 * you're linking to, in key => value array form. Query keys and values
153 * will be URL-encoded.
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 $options mixed String or array of strings:
160 * 'known': Page is known to exist, so don't check if it does.
161 * 'broken': Page is known not to exist, so don't check if it does.
162 * 'noclasses': Don't add any classes automatically (includes "new", "stub", "mw-redirect"). Only use the class attribute provided, if any.
163 * @return string HTML <a> attribute
164 */
165 public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
166 wfProfileIn( __METHOD__ );
167 if( !($target instanceof Title) ) {
168 throw new MWException( 'Linker::link passed invalid target' );
169 }
170 $options = (array)$options;
171
172 # Normalize the Title if it's a special page
173 if( $target->getNamespace() == NS_SPECIAL ) {
174 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $target->getDBkey() );
175 if( $name ) {
176 $target = SpecialPage::getTitleFor( $name, $subpage );
177 }
178 }
179
180 # If we don't know whether the page exists, let's find out.
181 if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
182 if( $target->getNamespace() == NS_SPECIAL ) {
183 if( SpecialPage::exists( $target->getDbKey() ) ) {
184 $options []= 'known';
185 } else {
186 $options []= 'broken';
187 }
188 } elseif( $target->isAlwaysKnown() or
189 ($target->getPrefixedText() == '' and $target->getFragment() != '')
190 or $target->exists() ) {
191 $options []= 'known';
192 } else {
193 # Either it exists
194 $options []= 'broken';
195 }
196 }
197
198 # Note: we want the href attribute first, for prettiness.
199 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
200 $attribs = array_merge(
201 $attribs,
202 $this->linkAttribs( $target, $customAttribs, $options )
203 );
204 if( is_null( $text ) ) {
205 $text = $this->linkText( $target, $options );
206 }
207
208 $ret = Xml::element( 'a', $attribs, $text, false );
209
210 wfProfileOut( __METHOD__ );
211 return $ret;
212 }
213
214 private function linkUrl( $target, $query, $options ) {
215 # If it's a broken link, add the appropriate query pieces. This over-
216 # writes the default action!
217 if( in_array( 'broken', $options ) ) {
218 $query['action'] = 'edit';
219 $query['redlink'] = '1';
220 }
221
222 return $target->getLocalURL( wfArrayToCGI( $query ) );
223 }
224
225 private function linkAttribs( $target, $attribs, $options ) {
226 global $wgUser;
227 $defaults = array();
228
229 # First get a default title attribute.
230 if( in_array( 'known', $options ) ) {
231 $defaults['title'] = $target->getPrefixedText();
232 } else {
233 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
234 }
235
236 if( !in_array( 'noclasses', $options ) ) {
237 # Now build the classes. This is the bulk of what we're doing.
238 $classes = array();
239
240 if( in_array( 'broken', $options ) ) {
241 $classes []= 'new';
242 }
243
244 # Note that redirects never count as stubs here.
245 if ( $target->isRedirect() ) {
246 $classes []= 'mw-redirect';
247 } elseif( $target->isContentPage() ) {
248 $threshold = $wgUser->getOption( 'stubthreshold' );
249 if( $threshold > 0 and $target->getLength() < $threshold ) {
250 $classes []= 'stub';
251 }
252 }
253 if( $classes != array() ) {
254 $defaults['class'] = implode( ' ', $classes );
255 }
256 }
257
258 # Finally, merge the custom attribs with the default ones, and iterate
259 # over that, deleting all "false" attributes.
260 if( !empty( $attribs['class'] ) and !empty( $defaults['class'] ) ) {
261 $attribs['class'] .= ' '.$defaults['class'];
262 }
263 $ret = array();
264 foreach( array_merge( $defaults, $attribs ) as $key => $val ) {
265 # A false value suppresses the attribute, and we don't want the
266 # href attribute to be overridden.
267 if( $key != 'href' and $val !== false ) {
268 $ret[$key] = $val;
269 }
270 }
271 return $ret;
272 }
273
274 private function linkText( $target, $options ) {
275 # If the target is just a fragment, with no title, we return the frag-
276 # ment text. Otherwise, we return the title text itself.
277 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
278 return htmlspecialchars( $target->getFragment() );
279 }
280 return htmlspecialchars( $target->getPrefixedText() );
281 }
282
283 /**
284 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
285 * it if you already have a title object handy. See makeLinkObj for further documentation.
286 *
287 * @param $title String: the text of the title
288 * @param $text String: link text
289 * @param $query String: optional query part
290 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
291 * be included in the link text. Other characters will be appended after
292 * the end of the link.
293 */
294 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
295 wfProfileIn( __METHOD__ );
296 $nt = Title::newFromText( $title );
297 if ( $nt instanceof Title ) {
298 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
299 } else {
300 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
301 $result = $text == "" ? $title : $text;
302 }
303
304 wfProfileOut( __METHOD__ );
305 return $result;
306 }
307
308 /**
309 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
310 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
311 *
312 * @param $title String: the text of the title
313 * @param $text String: link text
314 * @param $query String: optional query part
315 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
316 * be included in the link text. Other characters will be appended after
317 * the end of the link.
318 */
319 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
320 $nt = Title::newFromText( $title );
321 if ( $nt instanceof Title ) {
322 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
323 } else {
324 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
325 return $text == '' ? $title : $text;
326 }
327 }
328
329 /**
330 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
331 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
332 *
333 * @param string $title The text of the title
334 * @param string $text Link text
335 * @param string $query Optional query part
336 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
337 * be included in the link text. Other characters will be appended after
338 * the end of the link.
339 */
340 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
341 $nt = Title::newFromText( $title );
342 if ( $nt instanceof Title ) {
343 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
344 } else {
345 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
346 return $text == '' ? $title : $text;
347 }
348 }
349
350 /**
351 * @deprecated use makeColouredLinkObj
352 *
353 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
354 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
355 *
356 * @param $title String: the text of the title
357 * @param $text String: link text
358 * @param $query String: optional query part
359 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
360 * be included in the link text. Other characters will be appended after
361 * the end of the link.
362 */
363 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
364 $nt = Title::newFromText( $title );
365 if ( $nt instanceof Title ) {
366 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
367 } else {
368 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
369 return $text == '' ? $title : $text;
370 }
371 }
372
373 /**
374 * Make a link for a title which may or may not be in the database. If you need to
375 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
376 * call to this will result in a DB query.
377 *
378 * @param $nt Title: the title object to make the link from, e.g. from
379 * Title::newFromText.
380 * @param $text String: link text
381 * @param $query String: optional query part
382 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
383 * be included in the link text. Other characters will be appended after
384 * the end of the link.
385 * @param $prefix String: optional prefix. As trail, only before instead of after.
386 */
387 function makeLinkObj( Title $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
388 global $wgUser;
389 wfProfileIn( __METHOD__ );
390
391 if ( $nt->isExternal() ) {
392 $u = $nt->getFullURL();
393 $link = $nt->getPrefixedURL();
394 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
395 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
396
397 $inside = '';
398 if ( '' != $trail ) {
399 $m = array();
400 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
401 $inside = $m[1];
402 $trail = $m[2];
403 }
404 }
405 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
406
407 wfProfileOut( __METHOD__ );
408 return $t;
409 } elseif ( $nt->isAlwaysKnown() ) {
410 # Image links, special page links and self-links with fragments are always known.
411 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
412 } else {
413 wfProfileIn( __METHOD__.'-immediate' );
414
415 # Handles links to special pages which do not exist in the database:
416 if( $nt->getNamespace() == NS_SPECIAL ) {
417 if( SpecialPage::exists( $nt->getDBkey() ) ) {
418 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
419 } else {
420 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
421 }
422 wfProfileOut( __METHOD__.'-immediate' );
423 wfProfileOut( __METHOD__ );
424 return $retVal;
425 }
426
427 # Work out link colour immediately
428 $aid = $nt->getArticleID() ;
429 if ( 0 == $aid ) {
430 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
431 } else {
432 $colour = '';
433 if ( $nt->isContentPage() ) {
434 $threshold = $wgUser->getOption('stubthreshold');
435 $colour = $this->getLinkColour( $nt, $threshold );
436 }
437 $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
438 }
439 wfProfileOut( __METHOD__.'-immediate' );
440 }
441 wfProfileOut( __METHOD__ );
442 return $retVal;
443 }
444
445 /**
446 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
447 * it doesn't have to do a database query. It's also valid for interwiki titles and special
448 * pages.
449 *
450 * @param $nt Title object of target page
451 * @param $text String: text to replace the title
452 * @param $query String: link target
453 * @param $trail String: text after link
454 * @param $prefix String: text before link text
455 * @param $aprops String: extra attributes to the a-element
456 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
457 * @return the a-element
458 */
459 function makeKnownLinkObj( Title $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
460 wfProfileIn( __METHOD__ );
461
462 $nt = $this->normaliseSpecialPage( $title );
463
464 $u = $nt->escapeLocalURL( $query );
465 if ( $nt->getFragment() != '' ) {
466 if( $nt->getPrefixedDbkey() == '' ) {
467 $u = '';
468 if ( '' == $text ) {
469 $text = htmlspecialchars( $nt->getFragment() );
470 }
471 }
472 $u .= $nt->getFragmentForURL();
473 }
474 if ( $text == '' ) {
475 $text = htmlspecialchars( $nt->getPrefixedText() );
476 }
477 if ( $style == '' ) {
478 $style = $this->getInternalLinkAttributesObj( $nt, $text );
479 }
480
481 if ( $aprops !== '' ) $aprops = " $aprops";
482
483 list( $inside, $trail ) = Linker::splitTrail( $trail );
484 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
485 wfProfileOut( __METHOD__ );
486 return $r;
487 }
488
489 /**
490 * Make a red link to the edit page of a given title.
491 *
492 * @param $nt Title object of the target page
493 * @param $text String: Link text
494 * @param $query String: Optional query part
495 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
496 * be included in the link text. Other characters will be appended after
497 * the end of the link.
498 */
499 function makeBrokenLinkObj( Title $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
500 wfProfileIn( __METHOD__ );
501
502 $nt = $this->normaliseSpecialPage( $title );
503
504 if( $nt->getNamespace() == NS_SPECIAL ) {
505 $q = $query;
506 } else if ( '' == $query ) {
507 $q = 'action=edit&redlink=1';
508 } else {
509 $q = 'action=edit&redlink=1&'.$query;
510 }
511 $u = $nt->escapeLocalURL( $q );
512
513 $titleText = $nt->getPrefixedText();
514 if ( '' == $text ) {
515 $text = htmlspecialchars( $titleText );
516 }
517 $titleAttr = wfMsg( 'red-link-title', $titleText );
518 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new', $titleAttr );
519 list( $inside, $trail ) = Linker::splitTrail( $trail );
520
521 wfRunHooks( 'BrokenLink', array( &$this, $nt, $query, &$u, &$style, &$prefix, &$text, &$inside, &$trail ) );
522 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
523
524 wfProfileOut( __METHOD__ );
525 return $s;
526 }
527
528 /**
529 * @deprecated use makeColouredLinkObj
530 *
531 * Make a brown link to a short article.
532 *
533 * @param $nt Title object of the target page
534 * @param $text String: link text
535 * @param $query String: optional query part
536 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
537 * be included in the link text. Other characters will be appended after
538 * the end of the link.
539 */
540 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
541 wfDeprecated( __METHOD__ );
542 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
543 }
544
545 /**
546 * Make a coloured link.
547 *
548 * @param $nt Title object of the target page
549 * @param $colour Integer: colour of the link
550 * @param $text String: link text
551 * @param $query String: optional query part
552 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
553 * be included in the link text. Other characters will be appended after
554 * the end of the link.
555 */
556 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
557 if($colour != ''){
558 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
559 } else $style = '';
560 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
561 }
562
563 /**
564 * Generate either a normal exists-style link or a stub link, depending
565 * on the given page size.
566 *
567 * @param $size Integer
568 * @param $nt Title object.
569 * @param $text String
570 * @param $query String
571 * @param $trail String
572 * @param $prefix String
573 * @return string HTML of link
574 */
575 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
576 global $wgUser;
577 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
578 $colour = ( $size < $threshold ) ? 'stub' : '';
579 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
580 }
581
582 /**
583 * Make appropriate markup for a link to the current article. This is currently rendered
584 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
585 * despite $query not being used.
586 */
587 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
588 if ( '' == $text ) {
589 $text = htmlspecialchars( $nt->getPrefixedText() );
590 }
591 list( $inside, $trail ) = Linker::splitTrail( $trail );
592 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
593 }
594
595 function normaliseSpecialPage( Title $title ) {
596 if ( $title->getNamespace() == NS_SPECIAL ) {
597 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
598 if ( !$name ) return $title;
599 return SpecialPage::getTitleFor( $name, $subpage );
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 = '', $ns = null ) {
1004 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
1005 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1006 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
1007 $style .= ' rel="nofollow"';
1008 }
1009 $url = htmlspecialchars( $url );
1010 if( $escape ) {
1011 $text = htmlspecialchars( $text );
1012 }
1013 $link = '';
1014 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link ) );
1015 if(!$success) {
1016 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}", true);
1017 return $link;
1018 }
1019 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
1020 }
1021
1022 /**
1023 * Make user link (or user contributions for unregistered users)
1024 * @param $userId Integer: user id in database.
1025 * @param $userText String: user name in database
1026 * @return string HTML fragment
1027 * @private
1028 */
1029 function userLink( $userId, $userText ) {
1030 $encName = htmlspecialchars( $userText );
1031 if( $userId == 0 ) {
1032 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
1033 } else {
1034 $page = Title::makeTitle( NS_USER, $userText );
1035 }
1036 return $this->link( $page, $encName );
1037 }
1038
1039 /**
1040 * Generate standard user tool links (talk, contributions, block link, etc.)
1041 *
1042 * @param int $userId User identifier
1043 * @param string $userText User name or IP address
1044 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
1045 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
1046 * @param int $edits, user edit count (optional, for performance)
1047 * @return string
1048 */
1049 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
1050 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
1051 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1052 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
1053
1054 $items = array();
1055 if( $talkable ) {
1056 $items[] = $this->userTalkLink( $userId, $userText );
1057 }
1058 if( $userId ) {
1059 // check if the user has an edit
1060 $attribs = array();
1061 if( $redContribsWhenNoEdits ) {
1062 $count = !is_null($edits) ? $edits : User::edits( $userId );
1063 if( $count == 0 ) {
1064 $attribs['class'] = 'new';
1065 }
1066 }
1067 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1068
1069 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1070 }
1071 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
1072 $items[] = $this->blockLink( $userId, $userText );
1073 }
1074
1075 if( $items ) {
1076 return ' (' . implode( ' | ', $items ) . ')';
1077 } else {
1078 return '';
1079 }
1080 }
1081
1082 /**
1083 * Alias for userToolLinks( $userId, $userText, true );
1084 * @param int $userId User identifier
1085 * @param string $userText User name or IP address
1086 * @param int $edits, user edit count (optional, for performance)
1087 */
1088 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
1089 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
1090 }
1091
1092
1093 /**
1094 * @param $userId Integer: user id in database.
1095 * @param $userText String: user name in database.
1096 * @return string HTML fragment with user talk link
1097 * @private
1098 */
1099 function userTalkLink( $userId, $userText ) {
1100 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1101 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1102 return $userTalkLink;
1103 }
1104
1105 /**
1106 * @param $userId Integer: userid
1107 * @param $userText String: user name in database.
1108 * @return string HTML fragment with block link
1109 * @private
1110 */
1111 function blockLink( $userId, $userText ) {
1112 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
1113 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
1114 return $blockLink;
1115 }
1116
1117 /**
1118 * Generate a user link if the current user is allowed to view it
1119 * @param $rev Revision object.
1120 * @param $isPublic, bool, show only if all users can see it
1121 * @return string HTML
1122 */
1123 function revUserLink( $rev, $isPublic = false ) {
1124 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1125 $link = wfMsgHtml( 'rev-deleted-user' );
1126 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1127 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
1128 } else {
1129 $link = wfMsgHtml( 'rev-deleted-user' );
1130 }
1131 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1132 return '<span class="history-deleted">' . $link . '</span>';
1133 }
1134 return $link;
1135 }
1136
1137 /**
1138 * Generate a user tool link cluster if the current user is allowed to view it
1139 * @param $rev Revision object.
1140 * @param $isPublic, bool, show only if all users can see it
1141 * @return string HTML
1142 */
1143 function revUserTools( $rev, $isPublic = false ) {
1144 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1145 $link = wfMsgHtml( 'rev-deleted-user' );
1146 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
1147 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
1148 ' ' . $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
1149 } else {
1150 $link = wfMsgHtml( 'rev-deleted-user' );
1151 }
1152 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
1153 return ' <span class="history-deleted">' . $link . '</span>';
1154 }
1155 return $link;
1156 }
1157
1158 /**
1159 * This function is called by all recent changes variants, by the page history,
1160 * and by the user contributions list. It is responsible for formatting edit
1161 * comments. It escapes any HTML in the comment, but adds some CSS to format
1162 * auto-generated comments (from section editing) and formats [[wikilinks]].
1163 *
1164 * @author Erik Moeller <moeller@scireview.de>
1165 *
1166 * Note: there's not always a title to pass to this function.
1167 * Since you can't set a default parameter for a reference, I've turned it
1168 * temporarily to a value pass. Should be adjusted further. --brion
1169 *
1170 * @param string $comment
1171 * @param mixed $title Title object (to generate link to the section in autocomment) or null
1172 * @param bool $local Whether section links should refer to local page
1173 */
1174 function formatComment($comment, $title = NULL, $local = false) {
1175 wfProfileIn( __METHOD__ );
1176
1177 # Sanitize text a bit:
1178 $comment = str_replace( "\n", " ", $comment );
1179 $comment = htmlspecialchars( $comment );
1180
1181 # Render autocomments and make links:
1182 $comment = $this->formatAutoComments( $comment, $title, $local );
1183 $comment = $this->formatLinksInComment( $comment );
1184
1185 wfProfileOut( __METHOD__ );
1186 return $comment;
1187 }
1188
1189 /**
1190 * The pattern for autogen comments is / * foo * /, which makes for
1191 * some nasty regex.
1192 * We look for all comments, match any text before and after the comment,
1193 * add a separator where needed and format the comment itself with CSS
1194 * Called by Linker::formatComment.
1195 *
1196 * @param string $comment Comment text
1197 * @param object $title An optional title object used to links to sections
1198 * @return string $comment formatted comment
1199 *
1200 * @todo Document the $local parameter.
1201 */
1202 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
1203 $match = array();
1204 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
1205 $pre=$match[1];
1206 $auto=$match[2];
1207 $post=$match[3];
1208 $link='';
1209 if( $title ) {
1210 $section = $auto;
1211
1212 # Generate a valid anchor name from the section title.
1213 # Hackish, but should generally work - we strip wiki
1214 # syntax, including the magic [[: that is used to
1215 # "link rather than show" in case of images and
1216 # interlanguage links.
1217 $section = str_replace( '[[:', '', $section );
1218 $section = str_replace( '[[', '', $section );
1219 $section = str_replace( ']]', '', $section );
1220 if ( $local ) {
1221 $sectionTitle = Title::newFromText( '#' . $section);
1222 } else {
1223 $sectionTitle = wfClone( $title );
1224 $sectionTitle->mFragment = $section;
1225 }
1226 $link = $this->link( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1227 }
1228 $auto = $link . $auto;
1229 if( $pre ) {
1230 # written summary $presep autocomment (summary /* section */)
1231 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1232 }
1233 if( $post ) {
1234 # autocomment $postsep written summary (/* section */ summary)
1235 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1236 }
1237 $auto = '<span class="autocomment">' . $auto . '</span>';
1238 $comment = $pre . $auto . $post;
1239 }
1240
1241 return $comment;
1242 }
1243
1244 /**
1245 * Formats wiki links and media links in text; all other wiki formatting
1246 * is ignored
1247 *
1248 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1249 * @param string $comment Text to format links in
1250 * @return string
1251 */
1252 public function formatLinksInComment( $comment ) {
1253 return preg_replace_callback(
1254 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1255 array( $this, 'formatLinksInCommentCallback' ),
1256 $comment );
1257 }
1258
1259 protected function formatLinksInCommentCallback( $match ) {
1260 global $wgContLang;
1261
1262 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1263 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1264
1265 $comment = $match[0];
1266
1267 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1268 if( strpos( $match[1], '%' ) !== false ) {
1269 $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1270 }
1271
1272 # Handle link renaming [[foo|text]] will show link as "text"
1273 if( "" != $match[3] ) {
1274 $text = $match[3];
1275 } else {
1276 $text = $match[1];
1277 }
1278 $submatch = array();
1279 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1280 # Media link; trail not supported.
1281 $linkRegexp = '/\[\[(.*?)\]\]/';
1282 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1283 } else {
1284 # Other kind of link
1285 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1286 $trail = $submatch[1];
1287 } else {
1288 $trail = "";
1289 }
1290 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1291 if (isset($match[1][0]) && $match[1][0] == ':')
1292 $match[1] = substr($match[1], 1);
1293 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1294 }
1295 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1296
1297 return $comment;
1298 }
1299
1300 /**
1301 * Wrap a comment in standard punctuation and formatting if
1302 * it's non-empty, otherwise return empty string.
1303 *
1304 * @param string $comment
1305 * @param mixed $title Title object (to generate link to section in autocomment) or null
1306 * @param bool $local Whether section links should refer to local page
1307 *
1308 * @return string
1309 */
1310 function commentBlock( $comment, $title = NULL, $local = false ) {
1311 // '*' used to be the comment inserted by the software way back
1312 // in antiquity in case none was provided, here for backwards
1313 // compatability, acc. to brion -ævar
1314 if( $comment == '' || $comment == '*' ) {
1315 return '';
1316 } else {
1317 $formatted = $this->formatComment( $comment, $title, $local );
1318 return " <span class=\"comment\">($formatted)</span>";
1319 }
1320 }
1321
1322 /**
1323 * Wrap and format the given revision's comment block, if the current
1324 * user is allowed to view it.
1325 *
1326 * @param Revision $rev
1327 * @param bool $local Whether section links should refer to local page
1328 * @param $isPublic, show only if all users can see it
1329 * @return string HTML
1330 */
1331 function revComment( Revision $rev, $local = false, $isPublic = false ) {
1332 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1333 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1334 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1335 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1336 } else {
1337 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1338 }
1339 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1340 return " <span class=\"history-deleted\">$block</span>";
1341 }
1342 return $block;
1343 }
1344
1345 public function formatRevisionSize( $size ) {
1346 if ( $size == 0 ) {
1347 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1348 } else {
1349 global $wgLang;
1350 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1351 $stxt = "($stxt)";
1352 }
1353 $stxt = htmlspecialchars( $stxt );
1354 return "<span class=\"history-size\">$stxt</span>";
1355 }
1356
1357 /** @todo document */
1358 function tocIndent() {
1359 return "\n<ul>";
1360 }
1361
1362 /** @todo document */
1363 function tocUnindent($level) {
1364 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1365 }
1366
1367 /**
1368 * parameter level defines if we are on an indentation level
1369 */
1370 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1371 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1372 $anchor . '"><span class="tocnumber">' .
1373 $tocnumber . '</span> <span class="toctext">' .
1374 $tocline . '</span></a>';
1375 }
1376
1377 /** @todo document */
1378 function tocLineEnd() {
1379 return "</li>\n";
1380 }
1381
1382 /** @todo document */
1383 function tocList($toc) {
1384 global $wgJsMimeType;
1385 $title = wfMsgHtml('toc') ;
1386 return
1387 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1388 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1389 . $toc
1390 # no trailing newline, script should not be wrapped in a
1391 # paragraph
1392 . "</ul>\n</td></tr></table>"
1393 . '<script type="' . $wgJsMimeType . '">'
1394 . ' if (window.showTocToggle) {'
1395 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1396 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1397 . ' showTocToggle();'
1398 . ' } '
1399 . "</script>\n";
1400 }
1401
1402 /**
1403 * Used to generate section edit links that point to "other" pages
1404 * (sections that are really part of included pages).
1405 *
1406 * @param $title Title string.
1407 * @param $section Integer: section number.
1408 */
1409 public function editSectionLinkForOther( $title, $section ) {
1410 wfDeprecated( __METHOD__ );
1411 $title = Title::newFromText( $title );
1412 return $this->doEditSectionLink( $title, $section );
1413 }
1414
1415 /**
1416 * @param $nt Title object.
1417 * @param $section Integer: section number.
1418 * @param $hint Link String: title, or default if omitted or empty
1419 */
1420 public function editSectionLink( Title $nt, $section, $hint = '' ) {
1421 wfDeprecated( __METHOD__ );
1422 if( $hint === '' ) {
1423 # No way to pass an actual empty $hint here! The new interface al-
1424 # lows this, so we have to do this for compatibility.
1425 $hint = null;
1426 }
1427 return $this->doEditSectionLink( $nt, $section, $hint );
1428 }
1429
1430 /**
1431 * Create a section edit link. This supersedes editSectionLink() and
1432 * editSectionLinkForOther().
1433 *
1434 * @param $nt Title The title being linked to (may not be the same as
1435 * $wgTitle, if the section is included from a template)
1436 * @param $section string The designation of the section being pointed to,
1437 * to be included in the link, like "&section=$section"
1438 * @param $tooltip string The tooltip to use for the link: will be escaped
1439 * and wrapped in the 'editsectionhint' message
1440 * @return string HTML to use for edit link
1441 */
1442 public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1443 $attribs = array();
1444 if( !is_null( $tooltip ) ) {
1445 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1446 }
1447 $url = $this->link( $nt, wfMsg('editsection'),
1448 $attribs,
1449 array( 'action' => 'edit', 'section' => $section ),
1450 array( 'noclasses', 'known' )
1451 );
1452
1453 # Run the old hook. This takes up half of the function . . . hopefully
1454 # we can rid of it someday.
1455 $attribs = '';
1456 if( $tooltip ) {
1457 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1458 $attribs = " title=\"$attribs\"";
1459 }
1460 $result = null;
1461 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $url, &$result ) );
1462 if( !is_null( $result ) ) {
1463 # For reverse compatibility, add the brackets *after* the hook is
1464 # run, and even add them to hook-provided text. (This is the main
1465 # reason that the EditSectionLink hook is deprecated in favor of
1466 # DoEditSectionLink: it can't change the brackets or the span.)
1467 $result = wfMsgHtml( 'editsection-brackets', $url );
1468 return "<span class=\"editsection\">$result</span>";
1469 }
1470
1471 # Add the brackets and the span, and *then* run the nice new hook, with
1472 # clean and non-redundant arguments.
1473 $result = wfMsgHtml( 'editsection-brackets', $url );
1474 $result = "<span class=\"editsection\">$result</span>";
1475
1476 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1477 return $result;
1478 }
1479
1480 /**
1481 * Create a headline for content
1482 *
1483 * @param int $level The level of the headline (1-6)
1484 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1485 * This *must* be at least '>' for no attribs
1486 * @param string $anchor The anchor to give the headline (the bit after the #)
1487 * @param string $text The text of the header
1488 * @param string $link HTML to add for the section edit link
1489 *
1490 * @return string HTML headline
1491 */
1492 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1493 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1494 }
1495
1496 /**
1497 * Split a link trail, return the "inside" portion and the remainder of the trail
1498 * as a two-element array
1499 *
1500 * @static
1501 */
1502 static function splitTrail( $trail ) {
1503 static $regex = false;
1504 if ( $regex === false ) {
1505 global $wgContLang;
1506 $regex = $wgContLang->linkTrail();
1507 }
1508 $inside = '';
1509 if ( '' != $trail ) {
1510 $m = array();
1511 if ( preg_match( $regex, $trail, $m ) ) {
1512 $inside = $m[1];
1513 $trail = $m[2];
1514 }
1515 }
1516 return array( $inside, $trail );
1517 }
1518
1519 /**
1520 * Generate a rollback link for a given revision. Currently it's the
1521 * caller's responsibility to ensure that the revision is the top one. If
1522 * it's not, of course, the user will get an error message.
1523 *
1524 * If the calling page is called with the parameter &bot=1, all rollback
1525 * links also get that parameter. It causes the edit itself and the rollback
1526 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1527 * changes, so this allows sysops to combat a busy vandal without bothering
1528 * other users.
1529 *
1530 * @param Revision $rev
1531 */
1532 function generateRollback( $rev ) {
1533 return '<span class="mw-rollback-link">['
1534 . $this->buildRollbackLink( $rev )
1535 . ']</span>';
1536 }
1537
1538 /**
1539 * Build a raw rollback link, useful for collections of "tool" links
1540 *
1541 * @param Revision $rev
1542 * @return string
1543 */
1544 public function buildRollbackLink( $rev ) {
1545 global $wgRequest, $wgUser;
1546 $title = $rev->getTitle();
1547 $query = array( 'action' => 'rollback' );
1548 if( $wgRequest->getBool( 'bot' ) ) {
1549 $query['bot'] = '1';
1550 }
1551 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1552 $rev->getUserText() ) );
1553 return $this->link( $title, wfMsgHtml( 'rollbacklink' ), array(),
1554 $query, 'known' );
1555 }
1556
1557 /**
1558 * Returns HTML for the "templates used on this page" list.
1559 *
1560 * @param array $templates Array of templates from Article::getUsedTemplate
1561 * or similar
1562 * @param bool $preview Whether this is for a preview
1563 * @param bool $section Whether this is for a section edit
1564 * @return string HTML output
1565 */
1566 public function formatTemplates( $templates, $preview = false, $section = false) {
1567 global $wgUser;
1568 wfProfileIn( __METHOD__ );
1569
1570 $sk = $wgUser->getSkin();
1571
1572 $outText = '';
1573 if ( count( $templates ) > 0 ) {
1574 # Do a batch existence check
1575 $batch = new LinkBatch;
1576 foreach( $templates as $title ) {
1577 $batch->addObj( $title );
1578 }
1579 $batch->execute();
1580
1581 # Construct the HTML
1582 $outText = '<div class="mw-templatesUsedExplanation">';
1583 if ( $preview ) {
1584 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1585 } elseif ( $section ) {
1586 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1587 } else {
1588 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1589 }
1590 $outText .= '</div><ul>';
1591
1592 usort( $templates, array( 'Title', 'compare' ) );
1593 foreach ( $templates as $titleObj ) {
1594 $r = $titleObj->getRestrictions( 'edit' );
1595 if ( in_array( 'sysop', $r ) ) {
1596 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1597 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1598 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1599 } else {
1600 $protected = '';
1601 }
1602 $outText .= '<li>' . $sk->link( $titleObj ) . ' ' . $protected . '</li>';
1603 }
1604 $outText .= '</ul>';
1605 }
1606 wfProfileOut( __METHOD__ );
1607 return $outText;
1608 }
1609
1610 /**
1611 * Returns HTML for the "hidden categories on this page" list.
1612 *
1613 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1614 * or similar
1615 * @return string HTML output
1616 */
1617 public function formatHiddenCategories( $hiddencats) {
1618 global $wgUser, $wgLang;
1619 wfProfileIn( __METHOD__ );
1620
1621 $sk = $wgUser->getSkin();
1622
1623 $outText = '';
1624 if ( count( $hiddencats ) > 0 ) {
1625 # Construct the HTML
1626 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1627 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1628 $outText .= '</div><ul>';
1629
1630 foreach ( $hiddencats as $titleObj ) {
1631 $outText .= '<li>' . $sk->link( $titleObj, null, array(), array(), 'known' ) . '</li>'; # If it's hidden, it must exist - no need to check with a LinkBatch
1632 }
1633 $outText .= '</ul>';
1634 }
1635 wfProfileOut( __METHOD__ );
1636 return $outText;
1637 }
1638
1639 /**
1640 * Format a size in bytes for output, using an appropriate
1641 * unit (B, KB, MB or GB) according to the magnitude in question
1642 *
1643 * @param $size Size to format
1644 * @return string
1645 */
1646 public function formatSize( $size ) {
1647 global $wgLang;
1648 return htmlspecialchars( $wgLang->formatSize( $size ) );
1649 }
1650
1651 /**
1652 * Given the id of an interface element, constructs the appropriate title
1653 * and accesskey attributes from the system messages. (Note, this is usu-
1654 * ally the id but isn't always, because sometimes the accesskey needs to
1655 * go on a different element than the id, for reverse-compatibility, etc.)
1656 *
1657 * @param string $name Id of the element, minus prefixes.
1658 * @return string title and accesskey attributes, ready to drop in an
1659 * element (e.g., ' title="This does something [x]" accesskey="x"').
1660 */
1661 public function tooltipAndAccesskey($name) {
1662 $fname="Linker::tooltipAndAccesskey";
1663 wfProfileIn($fname);
1664 $out = '';
1665
1666 $tooltip = wfMsg('tooltip-'.$name);
1667 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1668 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1669 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1670 $out .= ' title="'.htmlspecialchars($tooltip);
1671 }
1672 $accesskey = wfMsg('accesskey-'.$name);
1673 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1674 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1675 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1676 } elseif ($out) {
1677 $out .= '"';
1678 }
1679 wfProfileOut($fname);
1680 return $out;
1681 }
1682
1683 /**
1684 * Given the id of an interface element, constructs the appropriate title
1685 * attribute from the system messages. (Note, this is usually the id but
1686 * isn't always, because sometimes the accesskey needs to go on a different
1687 * element than the id, for reverse-compatibility, etc.)
1688 *
1689 * @param string $name Id of the element, minus prefixes.
1690 * @return string title attribute, ready to drop in an element
1691 * (e.g., ' title="This does something"').
1692 */
1693 public function tooltip($name) {
1694 $out = '';
1695
1696 $tooltip = wfMsg('tooltip-'.$name);
1697 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1698 $out = ' title="'.htmlspecialchars($tooltip).'"';
1699 }
1700
1701 return $out;
1702 }
1703 }