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