Fix breakage from last commit caused by insufficiently paranoid spot-checking.
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Split off some of the internal bits from Skin.php.
4 * These functions are used for primarily page content:
5 * links, embedded images, table of contents. Links are
6 * also used in the skin.
7 * For the moment, Skin is a descendent class of Linker.
8 * In the future, it should probably be further split
9 * so that ever other bit of the wiki doesn't have to
10 * go loading up Skin to get at it.
11 *
12 * @addtogroup Skins
13 */
14 class Linker {
15 function __construct() {}
16
17 /**
18 * @deprecated
19 */
20 function postParseLinkColour( $s = NULL ) {
21 return NULL;
22 }
23
24 /** @todo document */
25 function getExternalLinkAttributes( $link, $text, $class='' ) {
26 $link = htmlspecialchars( $link );
27
28 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
29
30 $r .= " title=\"{$link}\"";
31 return $r;
32 }
33
34 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
35 global $wgContLang;
36
37 $link = urldecode( $link );
38 $link = $wgContLang->checkTitleEncoding( $link );
39 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
40 $link = htmlspecialchars( $link );
41
42 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
43
44 $r .= " title=\"{$link}\"";
45 return $r;
46 }
47
48 /** @todo document */
49 function getInternalLinkAttributes( $link, $text, $broken = false ) {
50 $link = urldecode( $link );
51 $link = str_replace( '_', ' ', $link );
52 $link = htmlspecialchars( $link );
53
54 if( $broken == 'stub' ) {
55 $r = ' class="stub"';
56 } else if ( $broken == 'yes' ) {
57 $r = ' class="new"';
58 } else {
59 $r = '';
60 }
61
62 $r .= " title=\"{$link}\"";
63 return $r;
64 }
65
66 /**
67 * @param $nt Title object.
68 * @param $text String: FIXME
69 * @param $broken Boolean: FIXME, default 'false'.
70 */
71 function getInternalLinkAttributesObj( &$nt, $text, $broken = false ) {
72 if( $broken == 'stub' ) {
73 $r = ' class="stub"';
74 } else if ( $broken == 'yes' ) {
75 $r = ' class="new"';
76 } else {
77 $r = '';
78 }
79
80 $r .= ' title="' . $nt->getEscapedText() . '"';
81 return $r;
82 }
83
84 /**
85 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
86 * it if you already have a title object handy. See makeLinkObj for further documentation.
87 *
88 * @param $title String: the text of the title
89 * @param $text String: link text
90 * @param $query String: optional query part
91 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
92 * be included in the link text. Other characters will be appended after
93 * the end of the link.
94 */
95 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
96 wfProfileIn( 'Linker::makeLink' );
97 $nt = Title::newFromText( $title );
98 if ($nt) {
99 $result = $this->makeLinkObj( Title::newFromText( $title ), $text, $query, $trail );
100 } else {
101 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
102 $result = $text == "" ? $title : $text;
103 }
104
105 wfProfileOut( 'Linker::makeLink' );
106 return $result;
107 }
108
109 /**
110 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
111 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
112 *
113 * @param $title String: the text of the title
114 * @param $text String: link text
115 * @param $query String: optional query part
116 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
117 * be included in the link text. Other characters will be appended after
118 * the end of the link.
119 */
120 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
121 $nt = Title::newFromText( $title );
122 if ($nt) {
123 return $this->makeKnownLinkObj( Title::newFromText( $title ), $text, $query, $trail, $prefix , $aprops );
124 } else {
125 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
126 return $text == '' ? $title : $text;
127 }
128 }
129
130 /**
131 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
132 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
133 *
134 * @param string $title The text of the title
135 * @param string $text Link text
136 * @param string $query Optional query part
137 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
138 * be included in the link text. Other characters will be appended after
139 * the end of the link.
140 */
141 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
142 $nt = Title::newFromText( $title );
143 if ($nt) {
144 return $this->makeBrokenLinkObj( Title::newFromText( $title ), $text, $query, $trail );
145 } else {
146 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
147 return $text == '' ? $title : $text;
148 }
149 }
150
151 /**
152 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
153 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
154 *
155 * @param $title String: the text of the title
156 * @param $text String: link text
157 * @param $query String: optional query part
158 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
159 * be included in the link text. Other characters will be appended after
160 * the end of the link.
161 */
162 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
163 $nt = Title::newFromText( $title );
164 if ($nt) {
165 return $this->makeStubLinkObj( Title::newFromText( $title ), $text, $query, $trail );
166 } else {
167 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
168 return $text == '' ? $title : $text;
169 }
170 }
171
172 /**
173 * Make a link for a title which may or may not be in the database. If you need to
174 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
175 * call to this will result in a DB query.
176 *
177 * @param $nt Title: the title object to make the link from, e.g. from
178 * Title::newFromText.
179 * @param $text String: link text
180 * @param $query String: optional query part
181 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
182 * be included in the link text. Other characters will be appended after
183 * the end of the link.
184 * @param $prefix String: optional prefix. As trail, only before instead of after.
185 */
186 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
187 global $wgUser;
188 $fname = 'Linker::makeLinkObj';
189 wfProfileIn( $fname );
190
191 # Fail gracefully
192 if ( ! is_object($nt) ) {
193 # throw new MWException();
194 wfProfileOut( $fname );
195 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
196 }
197
198 if ( $nt->isExternal() ) {
199 $u = $nt->getFullURL();
200 $link = $nt->getPrefixedURL();
201 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
202 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
203
204 $inside = '';
205 if ( '' != $trail ) {
206 $m = array();
207 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
208 $inside = $m[1];
209 $trail = $m[2];
210 }
211 }
212 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
213
214 wfProfileOut( $fname );
215 return $t;
216 } elseif ( $nt->isAlwaysKnown() ) {
217 # Image links, special page links and self-links with fragements are always known.
218 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
219 } else {
220 wfProfileIn( $fname.'-immediate' );
221 # Work out link colour immediately
222 $aid = $nt->getArticleID() ;
223 if ( 0 == $aid ) {
224 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
225 } else {
226 $threshold = $wgUser->getOption('stubthreshold') ;
227 if ( $threshold > 0 ) {
228 $dbr = wfGetDB( DB_SLAVE );
229 $s = $dbr->selectRow(
230 array( 'page' ),
231 array( 'page_len',
232 'page_namespace',
233 'page_is_redirect' ),
234 array( 'page_id' => $aid ), $fname ) ;
235 if ( $s !== false ) {
236 $size = $s->page_len;
237 if ( $s->page_is_redirect OR $s->page_namespace != NS_MAIN ) {
238 $size = $threshold*2 ; # Really big
239 }
240 } else {
241 $size = $threshold*2 ; # Really big
242 }
243 } else {
244 $size = 1 ;
245 }
246 if ( $size < $threshold ) {
247 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
248 } else {
249 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
250 }
251 }
252 wfProfileOut( $fname.'-immediate' );
253 }
254 wfProfileOut( $fname );
255 return $retVal;
256 }
257
258 /**
259 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
260 * it doesn't have to do a database query. It's also valid for interwiki titles and special
261 * pages.
262 *
263 * @param $nt Title object of target page
264 * @param $text String: text to replace the title
265 * @param $query String: link target
266 * @param $trail String: text after link
267 * @param $prefix String: text before link text
268 * @param $aprops String: extra attributes to the a-element
269 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
270 * @return the a-element
271 */
272 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
273
274 $fname = 'Linker::makeKnownLinkObj';
275 wfProfileIn( $fname );
276
277 if ( !is_object( $nt ) ) {
278 wfProfileOut( $fname );
279 return $text;
280 }
281
282 $u = $nt->escapeLocalURL( $query );
283 if ( $nt->getFragment() != '' ) {
284 if( $nt->getPrefixedDbkey() == '' ) {
285 $u = '';
286 if ( '' == $text ) {
287 $text = htmlspecialchars( $nt->getFragment() );
288 }
289 }
290 $u .= $nt->getFragmentForURL();
291 }
292 if ( $text == '' ) {
293 $text = htmlspecialchars( $nt->getPrefixedText() );
294 }
295 if ( $style == '' ) {
296 $style = $this->getInternalLinkAttributesObj( $nt, $text );
297 }
298
299 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
300
301 list( $inside, $trail ) = Linker::splitTrail( $trail );
302 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
303 wfProfileOut( $fname );
304 return $r;
305 }
306
307 /**
308 * Make a red link to the edit page of a given title.
309 *
310 * @param $title String: The text of the title
311 * @param $text String: Link text
312 * @param $query String: Optional query part
313 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
314 * be included in the link text. Other characters will be appended after
315 * the end of the link.
316 */
317 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
318 # Fail gracefully
319 if ( ! isset($nt) ) {
320 # throw new MWException();
321 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
322 }
323
324 $fname = 'Linker::makeBrokenLinkObj';
325 wfProfileIn( $fname );
326
327 if ( '' == $query ) {
328 $q = 'action=edit';
329 } else {
330 $q = 'action=edit&'.$query;
331 }
332 $u = $nt->escapeLocalURL( $q );
333
334 if ( '' == $text ) {
335 $text = htmlspecialchars( $nt->getPrefixedText() );
336 }
337 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
338
339 list( $inside, $trail ) = Linker::splitTrail( $trail );
340 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
341
342 wfProfileOut( $fname );
343 return $s;
344 }
345
346 /**
347 * Make a brown link to a short article.
348 *
349 * @param $title String: the text of the title
350 * @param $text String: link text
351 * @param $query String: optional query part
352 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
353 * be included in the link text. Other characters will be appended after
354 * the end of the link.
355 */
356 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
357 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
358 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
359 }
360
361 /**
362 * Generate either a normal exists-style link or a stub link, depending
363 * on the given page size.
364 *
365 * @param $size Integer
366 * @param $nt Title object.
367 * @param $text String
368 * @param $query String
369 * @param $trail String
370 * @param $prefix String
371 * @return string HTML of link
372 */
373 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
374 global $wgUser;
375 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
376 if( $size < $threshold ) {
377 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
378 } else {
379 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
380 }
381 }
382
383 /**
384 * Make appropriate markup for a link to the current article. This is currently rendered
385 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
386 * despite $query not being used.
387 */
388 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
389 if ( '' == $text ) {
390 $text = htmlspecialchars( $nt->getPrefixedText() );
391 }
392 list( $inside, $trail ) = Linker::splitTrail( $trail );
393 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
394 }
395
396 /** @todo document */
397 function fnamePart( $url ) {
398 $basename = strrchr( $url, '/' );
399 if ( false === $basename ) {
400 $basename = $url;
401 } else {
402 $basename = substr( $basename, 1 );
403 }
404 return htmlspecialchars( $basename );
405 }
406
407 /** Obsolete alias */
408 function makeImage( $url, $alt = '' ) {
409 return $this->makeExternalImage( $url, $alt );
410 }
411
412 /** @todo document */
413 function makeExternalImage( $url, $alt = '' ) {
414 if ( '' == $alt ) {
415 $alt = $this->fnamePart( $url );
416 }
417 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
418 return $s;
419 }
420
421 /** @todo document */
422 function makeImageLinkObj( $nt, $label, $alt, $align = '', $params = array(), $framed = false,
423 $thumb = false, $manual_thumb = '', $valign = '' )
424 {
425 global $wgContLang, $wgUser, $wgThumbLimits;
426
427 $img = new Image( $nt );
428
429 if ( !$img->allowInlineDisplay() && $img->exists() ) {
430 return $this->makeKnownLinkObj( $nt );
431 }
432
433 $error = $prefix = $postfix = '';
434 $page = isset( $params['page'] ) ? $params['page'] : false;
435
436 if ( 'center' == $align )
437 {
438 $prefix = '<div class="center">';
439 $postfix = '</div>';
440 $align = 'none';
441 }
442
443 if ( !isset( $params['width'] ) ) {
444 $params['width'] = $img->getWidth( $page );
445 if( $thumb || $framed ) {
446 $wopt = $wgUser->getOption( 'thumbsize' );
447
448 if( !isset( $wgThumbLimits[$wopt] ) ) {
449 $wopt = User::getDefaultOption( 'thumbsize' );
450 }
451
452 $params['width'] = min( $params['width'], $wgThumbLimits[$wopt] );
453 }
454 }
455
456 if ( $thumb || $framed ) {
457
458 # Create a thumbnail. Alignment depends on language
459 # writing direction, # right aligned for left-to-right-
460 # languages ("Western languages"), left-aligned
461 # for right-to-left-languages ("Semitic languages")
462 #
463 # If thumbnail width has not been provided, it is set
464 # to the default user option as specified in Language*.php
465 if ( $align == '' ) {
466 $align = $wgContLang->isRTL() ? 'left' : 'right';
467 }
468 return $prefix.$this->makeThumbLinkObj( $img, $label, $alt, $align, $params, $framed, $manual_thumb ).$postfix;
469 }
470
471 if ( $params['width'] && $img->exists() ) {
472 # Create a resized image, without the additional thumbnail features
473 $thumb = $img->transform( $params );
474 } else {
475 $thumb = false;
476 }
477
478 if ( $page ) {
479 $query = 'page=' . urlencode( $page );
480 } else {
481 $query = '';
482 }
483 $u = $nt->getLocalURL( $query );
484 $imgAttribs = array(
485 'alt' => $alt,
486 'longdesc' => $u
487 );
488 if ( $valign ) {
489 $imgAttribs['style'] = "vertical-align: $valign";
490 }
491 $linkAttribs = array(
492 'href' => $u,
493 'class' => 'image',
494 'title' => $alt
495 );
496
497 if ( !$thumb ) {
498 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
499 } else {
500 $s = $thumb->toHtml( $imgAttribs, $linkAttribs );
501 }
502 if ( '' != $align ) {
503 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
504 }
505 return str_replace("\n", ' ',$prefix.$s.$postfix);
506 }
507
508 /**
509 * Make HTML for a thumbnail including image, border and caption
510 * $img is an Image object
511 */
512 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manual_thumb = "" ) {
513 global $wgStylePath, $wgContLang;
514 $thumbUrl = '';
515 $error = '';
516
517 $page = isset( $params['page'] ) ? $params['page'] : false;
518
519 if ( empty( $params['width'] ) ) {
520 $params['width'] = 180;
521 }
522 $thumb = false;
523 if ( $manual_thumb != '' ) {
524 # Use manually specified thumbnail
525 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb );
526 if( $manual_title ) {
527 $manual_img = new Image( $manual_title );
528 $thumb = $manual_img->getUnscaledThumb();
529 }
530 } elseif ( $framed ) {
531 // Use image dimensions, don't scale
532 $thumb = $img->getUnscaledThumb( $page );
533 } else {
534 $thumb = $img->transform( $params );
535 }
536
537 if ( $thumb ) {
538 $outerWidth = $thumb->getWidth() + 2;
539 } else {
540 $outerWidth = $params['width'] + 2;
541 }
542
543 $query = $page ? 'page=' . urlencode( $page ) : '';
544 $u = $img->getTitle()->getLocalURL( $query );
545
546 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
547 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
548 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
549
550 $s = "<div class=\"thumb t{$align}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
551 if ( !$thumb ) {
552 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
553 $zoomicon = '';
554 } elseif( !$img->exists() ) {
555 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
556 $zoomicon = '';
557 } else {
558 $imgAttribs = array(
559 'alt' => $alt,
560 'longdesc' => $u,
561 'class' => 'thumbimage'
562 );
563 $linkAttribs = array(
564 'href' => $u,
565 'class' => 'internal',
566 'title' => $alt
567 );
568
569 $s .= $thumb->toHtml( $imgAttribs, $linkAttribs );
570 if ( $framed ) {
571 $zoomicon="";
572 } else {
573 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
574 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
575 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
576 'width="15" height="11" alt="" /></a></div>';
577 }
578 }
579 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
580 return str_replace("\n", ' ', $s);
581 }
582
583 /**
584 * Pass a title object, not a title string
585 */
586 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
587 # Fail gracefully
588 if ( ! isset($nt) ) {
589 # throw new MWException();
590 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
591 }
592
593 $fname = 'Linker::makeBrokenImageLinkObj';
594 wfProfileIn( $fname );
595
596 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
597 if ( '' != $query ) {
598 $q .= "&$query";
599 }
600 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
601 $url = $uploadTitle->escapeLocalURL( $q );
602
603 if ( '' == $text ) {
604 $text = htmlspecialchars( $nt->getPrefixedText() );
605 }
606 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
607 list( $inside, $trail ) = Linker::splitTrail( $trail );
608 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
609
610 wfProfileOut( $fname );
611 return $s;
612 }
613
614 /** @todo document */
615 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
616 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
617 return $this->makeMediaLinkObj( $nt, $alt );
618 }
619
620 /**
621 * Create a direct link to a given uploaded file.
622 *
623 * @param $title Title object.
624 * @param $text String: pre-sanitized HTML
625 * @return string HTML
626 *
627 * @public
628 * @todo Handle invalid or missing images better.
629 */
630 function makeMediaLinkObj( $title, $text = '' ) {
631 if( is_null( $title ) ) {
632 ### HOTFIX. Instead of breaking, return empty string.
633 return $text;
634 } else {
635 $img = new Image( $title );
636 if( $img->exists() ) {
637 $url = $img->getURL();
638 $class = 'internal';
639 } else {
640 $upload = SpecialPage::getTitleFor( 'Upload' );
641 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
642 $class = 'new';
643 }
644 $alt = htmlspecialchars( $title->getText() );
645 if( $text == '' ) {
646 $text = $alt;
647 }
648 $u = htmlspecialchars( $url );
649 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
650 }
651 }
652
653 /** @todo document */
654 function specialLink( $name, $key = '' ) {
655 global $wgContLang;
656
657 if ( '' == $key ) { $key = strtolower( $name ); }
658 $pn = $wgContLang->ucfirst( $name );
659 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
660 wfMsg( $key ) );
661 }
662
663 /** @todo document */
664 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
665 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
666 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
667 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
668 $style .= ' rel="nofollow"';
669 }
670 $url = htmlspecialchars( $url );
671 if( $escape ) {
672 $text = htmlspecialchars( $text );
673 }
674 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
675 }
676
677 /**
678 * Make user link (or user contributions for unregistered users)
679 * @param $userId Integer: user id in database.
680 * @param $userText String: user name in database
681 * @return string HTML fragment
682 * @private
683 */
684 function userLink( $userId, $userText ) {
685 $encName = htmlspecialchars( $userText );
686 if( $userId == 0 ) {
687 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
688 return $this->makeKnownLinkObj( $contribsPage,
689 $encName);
690 } else {
691 $userPage = Title::makeTitle( NS_USER, $userText );
692 return $this->makeLinkObj( $userPage, $encName );
693 }
694 }
695
696 /**
697 * @param $userId Integer: user id in database.
698 * @param $userText String: user name in database.
699 * @param $redContribsWhenNoEdits Bool: return a red contribs link when the user had no edits and this is true.
700 * @return string HTML fragment with talk and/or block links
701 */
702 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false ) {
703 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
704 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
705 $blockable = ( $wgSysopUserBans || 0 == $userId );
706
707 $items = array();
708 if( $talkable ) {
709 $items[] = $this->userTalkLink( $userId, $userText );
710 }
711 if( $userId ) {
712 // check if the user has an edit
713 if( $redContribsWhenNoEdits && User::edits( $userId ) == 0 ) {
714 $style = "class='new'";
715 } else {
716 $style = '';
717 }
718 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
719
720 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
721 }
722 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
723 $items[] = $this->blockLink( $userId, $userText );
724 }
725
726 if( $items ) {
727 return ' (' . implode( ' | ', $items ) . ')';
728 } else {
729 return '';
730 }
731 }
732
733 /**
734 * Alias for userToolLinks( $userId, $userText, true );
735 */
736 public function userToolLinksRedContribs( $userId, $userText ) {
737 return $this->userToolLinks( $userId, $userText, true );
738 }
739
740
741 /**
742 * @param $userId Integer: user id in database.
743 * @param $userText String: user name in database.
744 * @return string HTML fragment with user talk link
745 * @private
746 */
747 function userTalkLink( $userId, $userText ) {
748 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
749 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
750 return $userTalkLink;
751 }
752
753 /**
754 * @param $userId Integer: userid
755 * @param $userText String: user name in database.
756 * @return string HTML fragment with block link
757 * @private
758 */
759 function blockLink( $userId, $userText ) {
760 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
761 $blockLink = $this->makeKnownLinkObj( $blockPage,
762 wfMsgHtml( 'blocklink' ) );
763 return $blockLink;
764 }
765
766 /**
767 * Generate a user link if the current user is allowed to view it
768 * @param $rev Revision object.
769 * @return string HTML
770 */
771 function revUserLink( $rev ) {
772 if( $rev->userCan( Revision::DELETED_USER ) ) {
773 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
774 } else {
775 $link = wfMsgHtml( 'rev-deleted-user' );
776 }
777 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
778 return '<span class="history-deleted">' . $link . '</span>';
779 }
780 return $link;
781 }
782
783 /**
784 * Generate a user tool link cluster if the current user is allowed to view it
785 * @param $rev Revision object.
786 * @return string HTML
787 */
788 function revUserTools( $rev ) {
789 if( $rev->userCan( Revision::DELETED_USER ) ) {
790 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
791 ' ' .
792 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
793 } else {
794 $link = wfMsgHtml( 'rev-deleted-user' );
795 }
796 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
797 return '<span class="history-deleted">' . $link . '</span>';
798 }
799 return $link;
800 }
801
802 /**
803 * This function is called by all recent changes variants, by the page history,
804 * and by the user contributions list. It is responsible for formatting edit
805 * comments. It escapes any HTML in the comment, but adds some CSS to format
806 * auto-generated comments (from section editing) and formats [[wikilinks]].
807 *
808 * @author Erik Moeller <moeller@scireview.de>
809 *
810 * Note: there's not always a title to pass to this function.
811 * Since you can't set a default parameter for a reference, I've turned it
812 * temporarily to a value pass. Should be adjusted further. --brion
813 *
814 * @param string $comment
815 * @param mixed $title Title object (to generate link to the section in autocomment) or null
816 * @param bool $local Whether section links should refer to local page
817 */
818 function formatComment($comment, $title = NULL, $local = false) {
819 wfProfileIn( __METHOD__ );
820
821 global $wgContLang;
822 $comment = str_replace( "\n", " ", $comment );
823 $comment = htmlspecialchars( $comment );
824
825 # The pattern for autogen comments is / * foo * /, which makes for
826 # some nasty regex.
827 # We look for all comments, match any text before and after the comment,
828 # add a separator where needed and format the comment itself with CSS
829 $match = array();
830 while (preg_match('/(.*)\/\*\s*(.*?)\s*\*\/(.*)/', $comment,$match)) {
831 $pre=$match[1];
832 $auto=$match[2];
833 $post=$match[3];
834 $link='';
835 if( $title ) {
836 $section = $auto;
837
838 # Generate a valid anchor name from the section title.
839 # Hackish, but should generally work - we strip wiki
840 # syntax, including the magic [[: that is used to
841 # "link rather than show" in case of images and
842 # interlanguage links.
843 $section = str_replace( '[[:', '', $section );
844 $section = str_replace( '[[', '', $section );
845 $section = str_replace( ']]', '', $section );
846 if ( $local ) {
847 $sectionTitle = Title::newFromText( '#' . $section);
848 } else {
849 $sectionTitle = wfClone( $title );
850 $sectionTitle->mFragment = $section;
851 }
852 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
853 }
854 $sep='-';
855 $auto=$link.$auto;
856 if($pre) { $auto = $sep.' '.$auto; }
857 if($post) { $auto .= ' '.$sep; }
858 $auto='<span class="autocomment">'.$auto.'</span>';
859 $comment=$pre.$auto.$post;
860 }
861
862 # format regular and media links - all other wiki formatting
863 # is ignored
864 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
865 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
866 while(preg_match('/\[\[:?(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
867 # Handle link renaming [[foo|text]] will show link as "text"
868 if( "" != $match[3] ) {
869 $text = $match[3];
870 } else {
871 $text = $match[1];
872 }
873 $submatch = array();
874 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
875 # Media link; trail not supported.
876 $linkRegexp = '/\[\[(.*?)\]\]/';
877 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
878 } else {
879 # Other kind of link
880 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
881 $trail = $submatch[1];
882 } else {
883 $trail = "";
884 }
885 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
886 if (isset($match[1][0]) && $match[1][0] == ':')
887 $match[1] = substr($match[1], 1);
888 $thelink = $this->makeLink( $match[1], $text, "", $trail );
889 }
890 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
891 }
892 wfProfileOut( __METHOD__ );
893 return $comment;
894 }
895
896 /**
897 * Wrap a comment in standard punctuation and formatting if
898 * it's non-empty, otherwise return empty string.
899 *
900 * @param string $comment
901 * @param mixed $title Title object (to generate link to section in autocomment) or null
902 * @param bool $local Whether section links should refer to local page
903 *
904 * @return string
905 */
906 function commentBlock( $comment, $title = NULL, $local = false ) {
907 // '*' used to be the comment inserted by the software way back
908 // in antiquity in case none was provided, here for backwards
909 // compatability, acc. to brion -ævar
910 if( $comment == '' || $comment == '*' ) {
911 return '';
912 } else {
913 $formatted = $this->formatComment( $comment, $title, $local );
914 return " <span class=\"comment\">($formatted)</span>";
915 }
916 }
917
918 /**
919 * Wrap and format the given revision's comment block, if the current
920 * user is allowed to view it.
921 *
922 * @param Revision $rev
923 * @param bool $local Whether section links should refer to local page
924 * @return string HTML
925 */
926 function revComment( Revision $rev, $local = false ) {
927 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
928 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
929 } else {
930 $block = " <span class=\"comment\">" .
931 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
932 }
933 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
934 return " <span class=\"history-deleted\">$block</span>";
935 }
936 return $block;
937 }
938
939 /** @todo document */
940 function tocIndent() {
941 return "\n<ul>";
942 }
943
944 /** @todo document */
945 function tocUnindent($level) {
946 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
947 }
948
949 /**
950 * parameter level defines if we are on an indentation level
951 */
952 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
953 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
954 $anchor . '"><span class="tocnumber">' .
955 $tocnumber . '</span> <span class="toctext">' .
956 $tocline . '</span></a>';
957 }
958
959 /** @todo document */
960 function tocLineEnd() {
961 return "</li>\n";
962 }
963
964 /** @todo document */
965 function tocList($toc) {
966 global $wgJsMimeType;
967 $title = wfMsgHtml('toc') ;
968 return
969 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
970 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
971 . $toc
972 # no trailing newline, script should not be wrapped in a
973 # paragraph
974 . "</ul>\n</td></tr></table>"
975 . '<script type="' . $wgJsMimeType . '">'
976 . ' if (window.showTocToggle) {'
977 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
978 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
979 . ' showTocToggle();'
980 . ' } '
981 . "</script>\n";
982 }
983
984 /** @todo document */
985 public function editSectionLinkForOther( $title, $section ) {
986 global $wgContLang;
987
988 $title = Title::newFromText( $title );
989 $editurl = '&section='.$section;
990 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
991
992 return "<span class=\"editsection\">[".$url."]</span>";
993
994 }
995
996 /**
997 * @param $title Title object.
998 * @param $section Integer: section number.
999 * @param $hint Link String: title, or default if omitted or empty
1000 */
1001 public function editSectionLink( $nt, $section, $hint='' ) {
1002 global $wgContLang;
1003
1004 $editurl = '&section='.$section;
1005 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1006 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1007
1008 return "<span class=\"editsection\">[".$url."]</span>";
1009 }
1010
1011 /**
1012 * Create a headline for content
1013 *
1014 * @param int $level The level of the headline (1-6)
1015 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1016 * This *must* be at least '>' for no attribs
1017 * @param string $anchor The anchor to give the headline (the bit after the #)
1018 * @param string $text The text of the header
1019 * @param string $link HTML to add for the section edit link
1020 *
1021 * @return string HTML headline
1022 */
1023 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1024 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1025 }
1026
1027 /**
1028 * Split a link trail, return the "inside" portion and the remainder of the trail
1029 * as a two-element array
1030 *
1031 * @static
1032 */
1033 static function splitTrail( $trail ) {
1034 static $regex = false;
1035 if ( $regex === false ) {
1036 global $wgContLang;
1037 $regex = $wgContLang->linkTrail();
1038 }
1039 $inside = '';
1040 if ( '' != $trail ) {
1041 $m = array();
1042 if ( preg_match( $regex, $trail, $m ) ) {
1043 $inside = $m[1];
1044 $trail = $m[2];
1045 }
1046 }
1047 return array( $inside, $trail );
1048 }
1049
1050 /**
1051 * Generate a rollback link for a given revision. Currently it's the
1052 * caller's responsibility to ensure that the revision is the top one. If
1053 * it's not, of course, the user will get an error message.
1054 *
1055 * If the calling page is called with the parameter &bot=1, all rollback
1056 * links also get that parameter. It causes the edit itself and the rollback
1057 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1058 * changes, so this allows sysops to combat a busy vandal without bothering
1059 * other users.
1060 *
1061 * @param Revision $rev
1062 */
1063 function generateRollback( $rev ) {
1064 global $wgUser, $wgRequest;
1065 $title = $rev->getTitle();
1066
1067 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1068 $extraRollback .= '&token=' . urlencode(
1069 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1070 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1071 wfMsg('rollbacklink'),
1072 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1073 }
1074
1075 /**
1076 * Returns HTML for the "templates used on this page" list.
1077 *
1078 * @param array $templates Array of templates from Article::getUsedTemplate
1079 * or similar
1080 * @param bool $preview Whether this is for a preview
1081 * @param bool $section Whether this is for a section edit
1082 * @return string HTML output
1083 */
1084 public function formatTemplates( $templates, $preview = false, $section = false) {
1085 global $wgUser;
1086 wfProfileIn( __METHOD__ );
1087
1088 $sk = $wgUser->getSkin();
1089
1090 $outText = '';
1091 if ( count( $templates ) > 0 ) {
1092 # Do a batch existence check
1093 $batch = new LinkBatch;
1094 foreach( $templates as $title ) {
1095 $batch->addObj( $title );
1096 }
1097 $batch->execute();
1098
1099 # Construct the HTML
1100 $outText = '<div class="mw-templatesUsedExplanation">';
1101 if ( $preview ) {
1102 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1103 } elseif ( $section ) {
1104 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1105 } else {
1106 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1107 }
1108 $outText .= '</div><ul>';
1109
1110 foreach ( $templates as $titleObj ) {
1111 $r = $titleObj->getRestrictions( 'edit' );
1112 if ( in_array( 'sysop', $r ) ) {
1113 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1114 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1115 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1116 } else {
1117 $protected = '';
1118 }
1119 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1120 }
1121 $outText .= '</ul>';
1122 }
1123 wfProfileOut( __METHOD__ );
1124 return $outText;
1125 }
1126
1127 /**
1128 * Format a size in bytes for output, using an appropriate
1129 * unit (B, KB, MB or GB) according to the magnitude in question
1130 *
1131 * @param $size Size to format
1132 * @return string
1133 */
1134 public function formatSize( $size ) {
1135 global $wgLang;
1136 // For small sizes no decimal places necessary
1137 $round = 0;
1138 if( $size > 1024 ) {
1139 $size = $size / 1024;
1140 if( $size > 1024 ) {
1141 $size = $size / 1024;
1142 // For MB and bigger two decimal places are smarter
1143 $round = 2;
1144 if( $size > 1024 ) {
1145 $size = $size / 1024;
1146 $msg = 'size-gigabytes';
1147 } else {
1148 $msg = 'size-megabytes';
1149 }
1150 } else {
1151 $msg = 'size-kilobytes';
1152 }
1153 } else {
1154 $msg = 'size-bytes';
1155 }
1156 $size = round( $size, $round );
1157 return wfMsgHtml( $msg, $wgLang->formatNum( $size ) );
1158 }
1159
1160 /**
1161 * Given the id of an interface element, constructs the appropriate title
1162 * and accesskey attributes from the system messages. (Note, this is usu-
1163 * ally the id but isn't always, because sometimes the accesskey needs to
1164 * go on a different element than the id, for reverse-compatibility, etc.)
1165 *
1166 * @param string $name Id of the element, minus prefixes.
1167 * @return string title and accesskey attributes, ready to drop in an
1168 * element (e.g., ' title="This does something [x]" accesskey="x"').
1169 */
1170 public function tooltipAndAccesskey($name) {
1171 $out = '';
1172
1173 $tooltip = wfMsg('tooltip-'.$name);
1174 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1175 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1176 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1177 $out .= ' title="'.htmlspecialchars($tooltip);
1178 }
1179 $accesskey = wfMsg('accesskey-'.$name);
1180 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1181 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1182 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1183 } elseif ($out) {
1184 $out .= '"';
1185 }
1186 return $out;
1187 }
1188
1189 /**
1190 * Given the id of an interface element, constructs the appropriate title
1191 * attribute from the system messages. (Note, this is usually the id but
1192 * isn't always, because sometimes the accesskey needs to go on a different
1193 * element than the id, for reverse-compatibility, etc.)
1194 *
1195 * @param string $name Id of the element, minus prefixes.
1196 * @return string title attribute, ready to drop in an element
1197 * (e.g., ' title="This does something"').
1198 */
1199 public function tooltip($name) {
1200 $out = '';
1201
1202 $tooltip = wfMsg('tooltip-'.$name);
1203 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1204 $out = ' title="'.htmlspecialchars($tooltip).'"';
1205 }
1206
1207 return $out;
1208 }
1209 }
1210
1211 ?>