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