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