e7a776cf76b60f5e1342c3cd097c30cfa731d8b8
[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 $stub = false;
227 if ( $nt->isContentPage() ) {
228 $threshold = $wgUser->getOption('stubthreshold');
229 if ( $threshold > 0 ) {
230 $dbr = wfGetDB( DB_SLAVE );
231 $s = $dbr->selectRow(
232 array( 'page' ),
233 array( 'page_len',
234 'page_is_redirect' ),
235 array( 'page_id' => $aid ), $fname ) ;
236 $stub = ( $s !== false && !$s->page_is_redirect &&
237 $s->page_len < $threshold );
238 }
239 }
240 if ( $stub ) {
241 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
242 } else {
243 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
244 }
245 }
246 wfProfileOut( $fname.'-immediate' );
247 }
248 wfProfileOut( $fname );
249 return $retVal;
250 }
251
252 /**
253 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
254 * it doesn't have to do a database query. It's also valid for interwiki titles and special
255 * pages.
256 *
257 * @param $nt Title object of target page
258 * @param $text String: text to replace the title
259 * @param $query String: link target
260 * @param $trail String: text after link
261 * @param $prefix String: text before link text
262 * @param $aprops String: extra attributes to the a-element
263 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
264 * @return the a-element
265 */
266 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
267
268 $fname = 'Linker::makeKnownLinkObj';
269 wfProfileIn( $fname );
270
271 if ( !is_object( $nt ) ) {
272 wfProfileOut( $fname );
273 return $text;
274 }
275
276 $u = $nt->escapeLocalURL( $query );
277 if ( $nt->getFragment() != '' ) {
278 if( $nt->getPrefixedDbkey() == '' ) {
279 $u = '';
280 if ( '' == $text ) {
281 $text = htmlspecialchars( $nt->getFragment() );
282 }
283 }
284 $u .= $nt->getFragmentForURL();
285 }
286 if ( $text == '' ) {
287 $text = htmlspecialchars( $nt->getPrefixedText() );
288 }
289 if ( $style == '' ) {
290 $style = $this->getInternalLinkAttributesObj( $nt, $text );
291 }
292
293 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
294
295 list( $inside, $trail ) = Linker::splitTrail( $trail );
296 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
297 wfProfileOut( $fname );
298 return $r;
299 }
300
301 /**
302 * Make a red link to the edit page of a given title.
303 *
304 * @param $title String: The text of the title
305 * @param $text String: Link text
306 * @param $query String: Optional query part
307 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
308 * be included in the link text. Other characters will be appended after
309 * the end of the link.
310 */
311 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
312 # Fail gracefully
313 if ( ! isset($nt) ) {
314 # throw new MWException();
315 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
316 }
317
318 $fname = 'Linker::makeBrokenLinkObj';
319 wfProfileIn( $fname );
320
321 if ( '' == $query ) {
322 $q = 'action=edit';
323 } else {
324 $q = 'action=edit&'.$query;
325 }
326 $u = $nt->escapeLocalURL( $q );
327
328 if ( '' == $text ) {
329 $text = htmlspecialchars( $nt->getPrefixedText() );
330 }
331 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
332
333 list( $inside, $trail ) = Linker::splitTrail( $trail );
334 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
335
336 wfProfileOut( $fname );
337 return $s;
338 }
339
340 /**
341 * Make a brown link to a short article.
342 *
343 * @param $title String: the text of the title
344 * @param $text String: link text
345 * @param $query String: optional query part
346 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
347 * be included in the link text. Other characters will be appended after
348 * the end of the link.
349 */
350 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
351 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
352 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
353 }
354
355 /**
356 * Generate either a normal exists-style link or a stub link, depending
357 * on the given page size.
358 *
359 * @param $size Integer
360 * @param $nt Title object.
361 * @param $text String
362 * @param $query String
363 * @param $trail String
364 * @param $prefix String
365 * @return string HTML of link
366 */
367 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
368 global $wgUser;
369 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
370 if( $size < $threshold ) {
371 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
372 } else {
373 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
374 }
375 }
376
377 /**
378 * Make appropriate markup for a link to the current article. This is currently rendered
379 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
380 * despite $query not being used.
381 */
382 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
383 if ( '' == $text ) {
384 $text = htmlspecialchars( $nt->getPrefixedText() );
385 }
386 list( $inside, $trail ) = Linker::splitTrail( $trail );
387 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
388 }
389
390 /** @todo document */
391 function fnamePart( $url ) {
392 $basename = strrchr( $url, '/' );
393 if ( false === $basename ) {
394 $basename = $url;
395 } else {
396 $basename = substr( $basename, 1 );
397 }
398 return htmlspecialchars( $basename );
399 }
400
401 /** Obsolete alias */
402 function makeImage( $url, $alt = '' ) {
403 return $this->makeExternalImage( $url, $alt );
404 }
405
406 /** @todo document */
407 function makeExternalImage( $url, $alt = '' ) {
408 if ( '' == $alt ) {
409 $alt = $this->fnamePart( $url );
410 }
411 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
412 return $s;
413 }
414
415 /** @todo document */
416 function makeImageLinkObj( $nt, $label, $alt, $align = '', $params = array(), $framed = false,
417 $thumb = false, $manual_thumb = '', $valign = '', $upright = false, $upright_factor = 0, $border = false, $frameless = false )
418 {
419 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
420
421 $img = new Image( $nt );
422
423 if ( !$img->allowInlineDisplay() && $img->exists() ) {
424 return $this->makeKnownLinkObj( $nt );
425 }
426
427 $error = $prefix = $postfix = '';
428 $page = isset( $params['page'] ) ? $params['page'] : false;
429
430 if ( 'center' == $align )
431 {
432 $prefix = '<div class="center">';
433 $postfix = '</div>';
434 $align = 'none';
435 }
436
437 if ( !isset( $params['width'] ) ) {
438 $params['width'] = $img->getWidth( $page );
439 if( $thumb || $framed || $frameless ) {
440 $wopt = $wgUser->getOption( 'thumbsize' );
441
442 if( !isset( $wgThumbLimits[$wopt] ) ) {
443 $wopt = User::getDefaultOption( 'thumbsize' );
444 }
445
446 // Reduce width for upright images when parameter 'upright' is used
447 if ( $upright_factor == 0 ) {
448 $upright_factor = $wgThumbUpright;
449 }
450 // Use width which is smaller: real image width or user preference width
451 // 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
452 $params['width'] = min( $params['width'], $upright ? round( $wgThumbLimits[$wopt] * $upright_factor, -1 ) : $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, $upright ).$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
489 if ( $valign ) {
490 $imgAttribs['style'] = "vertical-align: $valign";
491 }
492 if ( $border ) {
493 $imgAttribs['class'] = "thumbborder";
494 }
495 $linkAttribs = array(
496 'href' => $u,
497 'class' => 'image',
498 'title' => $alt
499 );
500
501 if ( !$thumb ) {
502 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
503 } else {
504 $s = $thumb->toHtml( $imgAttribs, $linkAttribs );
505 }
506 if ( '' != $align ) {
507 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
508 }
509 return str_replace("\n", ' ',$prefix.$s.$postfix);
510 }
511
512 /**
513 * Make HTML for a thumbnail including image, border and caption
514 * $img is an Image object
515 */
516 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manual_thumb = "", $upright = false ) {
517 global $wgStylePath, $wgContLang;
518
519 $page = isset( $params['page'] ) ? $params['page'] : false;
520
521 if ( empty( $params['width'] ) ) {
522 // Reduce width for upright images when parameter 'upright' is used
523 $params['width'] = $upright ? 130 : 180;
524 }
525 $thumb = false;
526 if ( $manual_thumb != '' ) {
527 # Use manually specified thumbnail
528 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb );
529 if( $manual_title ) {
530 $manual_img = new Image( $manual_title );
531 $thumb = $manual_img->getUnscaledThumb();
532 }
533 } elseif ( $framed ) {
534 // Use image dimensions, don't scale
535 $thumb = $img->getUnscaledThumb( $page );
536 } else {
537 # Do not present an image bigger than the source, for bitmap-style images
538 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
539 $srcWidth = $img->getWidth( $page );
540 if ( $srcWidth && !$img->mustRender() && $params['width'] > $srcWidth ) {
541 $params['width'] = $srcWidth;
542 }
543 $thumb = $img->transform( $params );
544 }
545
546 if ( $thumb ) {
547 $outerWidth = $thumb->getWidth() + 2;
548 } else {
549 $outerWidth = $params['width'] + 2;
550 }
551
552 $query = $page ? 'page=' . urlencode( $page ) : '';
553 $u = $img->getTitle()->getLocalURL( $query );
554
555 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
556 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
557 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
558
559 $s = "<div class=\"thumb t{$align}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
560 if ( !$thumb ) {
561 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
562 $zoomicon = '';
563 } elseif( !$img->exists() ) {
564 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
565 $zoomicon = '';
566 } else {
567 $imgAttribs = array(
568 'alt' => $alt,
569 'longdesc' => $u,
570 'class' => 'thumbimage'
571 );
572 $linkAttribs = array(
573 'href' => $u,
574 'class' => 'internal',
575 'title' => $alt
576 );
577
578 $s .= $thumb->toHtml( $imgAttribs, $linkAttribs );
579 if ( $framed ) {
580 $zoomicon="";
581 } else {
582 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
583 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
584 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
585 'width="15" height="11" alt="" /></a></div>';
586 }
587 }
588 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
589 return str_replace("\n", ' ', $s);
590 }
591
592 /**
593 * Pass a title object, not a title string
594 */
595 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
596 # Fail gracefully
597 if ( ! isset($nt) ) {
598 # throw new MWException();
599 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
600 }
601
602 $fname = 'Linker::makeBrokenImageLinkObj';
603 wfProfileIn( $fname );
604
605 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
606 if ( '' != $query ) {
607 $q .= "&$query";
608 }
609 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
610 $url = $uploadTitle->escapeLocalURL( $q );
611
612 if ( '' == $text ) {
613 $text = htmlspecialchars( $nt->getPrefixedText() );
614 }
615 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
616 list( $inside, $trail ) = Linker::splitTrail( $trail );
617 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
618
619 wfProfileOut( $fname );
620 return $s;
621 }
622
623 /** @todo document */
624 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
625 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
626 return $this->makeMediaLinkObj( $nt, $alt );
627 }
628
629 /**
630 * Create a direct link to a given uploaded file.
631 *
632 * @param $title Title object.
633 * @param $text String: pre-sanitized HTML
634 * @return string HTML
635 *
636 * @public
637 * @todo Handle invalid or missing images better.
638 */
639 function makeMediaLinkObj( $title, $text = '' ) {
640 if( is_null( $title ) ) {
641 ### HOTFIX. Instead of breaking, return empty string.
642 return $text;
643 } else {
644 $img = new Image( $title );
645 if( $img->exists() ) {
646 $url = $img->getURL();
647 $class = 'internal';
648 } else {
649 $upload = SpecialPage::getTitleFor( 'Upload' );
650 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
651 $class = 'new';
652 }
653 $alt = htmlspecialchars( $title->getText() );
654 if( $text == '' ) {
655 $text = $alt;
656 }
657 $u = htmlspecialchars( $url );
658 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
659 }
660 }
661
662 /** @todo document */
663 function specialLink( $name, $key = '' ) {
664 global $wgContLang;
665
666 if ( '' == $key ) { $key = strtolower( $name ); }
667 $pn = $wgContLang->ucfirst( $name );
668 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
669 wfMsg( $key ) );
670 }
671
672 /** @todo document */
673 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
674 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
675 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
676 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
677 $style .= ' rel="nofollow"';
678 }
679 $url = htmlspecialchars( $url );
680 if( $escape ) {
681 $text = htmlspecialchars( $text );
682 }
683 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
684 }
685
686 /**
687 * Make user link (or user contributions for unregistered users)
688 * @param $userId Integer: user id in database.
689 * @param $userText String: user name in database
690 * @return string HTML fragment
691 * @private
692 */
693 function userLink( $userId, $userText ) {
694 $encName = htmlspecialchars( $userText );
695 if( $userId == 0 ) {
696 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
697 return $this->makeKnownLinkObj( $contribsPage,
698 $encName);
699 } else {
700 $userPage = Title::makeTitle( NS_USER, $userText );
701 return $this->makeLinkObj( $userPage, $encName );
702 }
703 }
704
705 /**
706 * @param $userId Integer: user id in database.
707 * @param $userText String: user name in database.
708 * @param $redContribsWhenNoEdits Bool: return a red contribs link when the user had no edits and this is true.
709 * @return string HTML fragment with talk and/or block links
710 */
711 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false ) {
712 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
713 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
714 $blockable = ( $wgSysopUserBans || 0 == $userId );
715
716 $items = array();
717 if( $talkable ) {
718 $items[] = $this->userTalkLink( $userId, $userText );
719 }
720 if( $userId ) {
721 // check if the user has an edit
722 if( $redContribsWhenNoEdits && User::edits( $userId ) == 0 ) {
723 $style = "class='new'";
724 } else {
725 $style = '';
726 }
727 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
728
729 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
730 }
731 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
732 $items[] = $this->blockLink( $userId, $userText );
733 }
734
735 if( $items ) {
736 return ' (' . implode( ' | ', $items ) . ')';
737 } else {
738 return '';
739 }
740 }
741
742 /**
743 * Alias for userToolLinks( $userId, $userText, true );
744 */
745 public function userToolLinksRedContribs( $userId, $userText ) {
746 return $this->userToolLinks( $userId, $userText, true );
747 }
748
749
750 /**
751 * @param $userId Integer: user id in database.
752 * @param $userText String: user name in database.
753 * @return string HTML fragment with user talk link
754 * @private
755 */
756 function userTalkLink( $userId, $userText ) {
757 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
758 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
759 return $userTalkLink;
760 }
761
762 /**
763 * @param $userId Integer: userid
764 * @param $userText String: user name in database.
765 * @return string HTML fragment with block link
766 * @private
767 */
768 function blockLink( $userId, $userText ) {
769 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
770 $blockLink = $this->makeKnownLinkObj( $blockPage,
771 wfMsgHtml( 'blocklink' ) );
772 return $blockLink;
773 }
774
775 /**
776 * Generate a user link if the current user is allowed to view it
777 * @param $rev Revision object.
778 * @return string HTML
779 */
780 function revUserLink( $rev ) {
781 if( $rev->userCan( Revision::DELETED_USER ) ) {
782 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
783 } else {
784 $link = wfMsgHtml( 'rev-deleted-user' );
785 }
786 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
787 return '<span class="history-deleted">' . $link . '</span>';
788 }
789 return $link;
790 }
791
792 /**
793 * Generate a user tool link cluster if the current user is allowed to view it
794 * @param $rev Revision object.
795 * @return string HTML
796 */
797 function revUserTools( $rev ) {
798 if( $rev->userCan( Revision::DELETED_USER ) ) {
799 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
800 ' ' .
801 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
802 } else {
803 $link = wfMsgHtml( 'rev-deleted-user' );
804 }
805 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
806 return '<span class="history-deleted">' . $link . '</span>';
807 }
808 return $link;
809 }
810
811 /**
812 * This function is called by all recent changes variants, by the page history,
813 * and by the user contributions list. It is responsible for formatting edit
814 * comments. It escapes any HTML in the comment, but adds some CSS to format
815 * auto-generated comments (from section editing) and formats [[wikilinks]].
816 *
817 * @author Erik Moeller <moeller@scireview.de>
818 *
819 * Note: there's not always a title to pass to this function.
820 * Since you can't set a default parameter for a reference, I've turned it
821 * temporarily to a value pass. Should be adjusted further. --brion
822 *
823 * @param string $comment
824 * @param mixed $title Title object (to generate link to the section in autocomment) or null
825 * @param bool $local Whether section links should refer to local page
826 */
827 function formatComment($comment, $title = NULL, $local = false) {
828 wfProfileIn( __METHOD__ );
829
830 # Sanitize text a bit:
831 $comment = str_replace( "\n", " ", $comment );
832 $comment = htmlspecialchars( $comment );
833
834 # Render autocomments and make links:
835 $comment = $this->formatAutoComments( $comment, $title, $local );
836 $comment = $this->formatLinksInComment( $comment );
837
838 wfProfileOut( __METHOD__ );
839 return $comment;
840 }
841
842 /**
843 * The pattern for autogen comments is / * foo * /, which makes for
844 * some nasty regex.
845 * We look for all comments, match any text before and after the comment,
846 * add a separator where needed and format the comment itself with CSS
847 * Called by Linker::formatComment.
848 *
849 * @param $comment Comment text
850 * @param $title An optional title object used to links to sections
851 *
852 * @todo Document the $local parameter.
853 */
854 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
855 $match = array();
856 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
857 $pre=$match[1];
858 $auto=$match[2];
859 $post=$match[3];
860 $link='';
861 if( $title ) {
862 $section = $auto;
863
864 # Generate a valid anchor name from the section title.
865 # Hackish, but should generally work - we strip wiki
866 # syntax, including the magic [[: that is used to
867 # "link rather than show" in case of images and
868 # interlanguage links.
869 $section = str_replace( '[[:', '', $section );
870 $section = str_replace( '[[', '', $section );
871 $section = str_replace( ']]', '', $section );
872 if ( $local ) {
873 $sectionTitle = Title::newFromText( '#' . $section);
874 } else {
875 $sectionTitle = wfClone( $title );
876 $sectionTitle->mFragment = $section;
877 }
878 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
879 }
880 $sep='-';
881 $auto=$link.$auto;
882 if($pre) { $auto = $sep.' '.$auto; }
883 if($post) { $auto .= ' '.$sep; }
884 $auto='<span class="autocomment">'.$auto.'</span>';
885 $comment=$pre.$auto.$post;
886 }
887
888 return $comment;
889 }
890
891 /**
892 * Format regular and media links - all other wiki formatting is ignored
893 * Called by Linker::formatComment.
894 * @param $comment The comment text.
895 * @return Comment text with links using HTML.
896 */
897 private function formatLinksInComment( $comment ) {
898 global $wgContLang;
899
900 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
901 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
902
903 while(preg_match('/\[\[:?(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
904 # Handle link renaming [[foo|text]] will show link as "text"
905 if( "" != $match[3] ) {
906 $text = $match[3];
907 } else {
908 $text = $match[1];
909 }
910 $submatch = array();
911 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
912 # Media link; trail not supported.
913 $linkRegexp = '/\[\[(.*?)\]\]/';
914 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
915 } else {
916 # Other kind of link
917 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
918 $trail = $submatch[1];
919 } else {
920 $trail = "";
921 }
922 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
923 if (isset($match[1][0]) && $match[1][0] == ':')
924 $match[1] = substr($match[1], 1);
925 $thelink = $this->makeLink( $match[1], $text, "", $trail );
926 }
927 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
928 }
929
930 return $comment;
931 }
932
933 /**
934 * Wrap a comment in standard punctuation and formatting if
935 * it's non-empty, otherwise return empty string.
936 *
937 * @param string $comment
938 * @param mixed $title Title object (to generate link to section in autocomment) or null
939 * @param bool $local Whether section links should refer to local page
940 *
941 * @return string
942 */
943 function commentBlock( $comment, $title = NULL, $local = false ) {
944 // '*' used to be the comment inserted by the software way back
945 // in antiquity in case none was provided, here for backwards
946 // compatability, acc. to brion -ævar
947 if( $comment == '' || $comment == '*' ) {
948 return '';
949 } else {
950 $formatted = $this->formatComment( $comment, $title, $local );
951 return " <span class=\"comment\">($formatted)</span>";
952 }
953 }
954
955 /**
956 * Wrap and format the given revision's comment block, if the current
957 * user is allowed to view it.
958 *
959 * @param Revision $rev
960 * @param bool $local Whether section links should refer to local page
961 * @return string HTML
962 */
963 function revComment( Revision $rev, $local = false ) {
964 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
965 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
966 } else {
967 $block = " <span class=\"comment\">" .
968 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
969 }
970 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
971 return " <span class=\"history-deleted\">$block</span>";
972 }
973 return $block;
974 }
975
976 /** @todo document */
977 function tocIndent() {
978 return "\n<ul>";
979 }
980
981 /** @todo document */
982 function tocUnindent($level) {
983 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
984 }
985
986 /**
987 * parameter level defines if we are on an indentation level
988 */
989 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
990 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
991 $anchor . '"><span class="tocnumber">' .
992 $tocnumber . '</span> <span class="toctext">' .
993 $tocline . '</span></a>';
994 }
995
996 /** @todo document */
997 function tocLineEnd() {
998 return "</li>\n";
999 }
1000
1001 /** @todo document */
1002 function tocList($toc) {
1003 global $wgJsMimeType;
1004 $title = wfMsgHtml('toc') ;
1005 return
1006 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1007 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1008 . $toc
1009 # no trailing newline, script should not be wrapped in a
1010 # paragraph
1011 . "</ul>\n</td></tr></table>"
1012 . '<script type="' . $wgJsMimeType . '">'
1013 . ' if (window.showTocToggle) {'
1014 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1015 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1016 . ' showTocToggle();'
1017 . ' } '
1018 . "</script>\n";
1019 }
1020
1021 /** @todo document */
1022 public function editSectionLinkForOther( $title, $section ) {
1023 global $wgContLang;
1024
1025 $title = Title::newFromText( $title );
1026 $editurl = '&section='.$section;
1027 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
1028
1029 return "<span class=\"editsection\">[".$url."]</span>";
1030
1031 }
1032
1033 /**
1034 * @param $title Title object.
1035 * @param $section Integer: section number.
1036 * @param $hint Link String: title, or default if omitted or empty
1037 */
1038 public function editSectionLink( $nt, $section, $hint='' ) {
1039 global $wgContLang;
1040
1041 $editurl = '&section='.$section;
1042 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1043 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1044
1045 return "<span class=\"editsection\">[".$url."]</span>";
1046 }
1047
1048 /**
1049 * Create a headline for content
1050 *
1051 * @param int $level The level of the headline (1-6)
1052 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1053 * This *must* be at least '>' for no attribs
1054 * @param string $anchor The anchor to give the headline (the bit after the #)
1055 * @param string $text The text of the header
1056 * @param string $link HTML to add for the section edit link
1057 *
1058 * @return string HTML headline
1059 */
1060 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1061 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1062 }
1063
1064 /**
1065 * Split a link trail, return the "inside" portion and the remainder of the trail
1066 * as a two-element array
1067 *
1068 * @static
1069 */
1070 static function splitTrail( $trail ) {
1071 static $regex = false;
1072 if ( $regex === false ) {
1073 global $wgContLang;
1074 $regex = $wgContLang->linkTrail();
1075 }
1076 $inside = '';
1077 if ( '' != $trail ) {
1078 $m = array();
1079 if ( preg_match( $regex, $trail, $m ) ) {
1080 $inside = $m[1];
1081 $trail = $m[2];
1082 }
1083 }
1084 return array( $inside, $trail );
1085 }
1086
1087 /**
1088 * Generate a rollback link for a given revision. Currently it's the
1089 * caller's responsibility to ensure that the revision is the top one. If
1090 * it's not, of course, the user will get an error message.
1091 *
1092 * If the calling page is called with the parameter &bot=1, all rollback
1093 * links also get that parameter. It causes the edit itself and the rollback
1094 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1095 * changes, so this allows sysops to combat a busy vandal without bothering
1096 * other users.
1097 *
1098 * @param Revision $rev
1099 */
1100 function generateRollback( $rev ) {
1101 global $wgUser, $wgRequest;
1102 $title = $rev->getTitle();
1103
1104 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1105 $extraRollback .= '&token=' . urlencode(
1106 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1107 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1108 wfMsg('rollbacklink'),
1109 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1110 }
1111
1112 /**
1113 * Returns HTML for the "templates used on this page" list.
1114 *
1115 * @param array $templates Array of templates from Article::getUsedTemplate
1116 * or similar
1117 * @param bool $preview Whether this is for a preview
1118 * @param bool $section Whether this is for a section edit
1119 * @return string HTML output
1120 */
1121 public function formatTemplates( $templates, $preview = false, $section = false) {
1122 global $wgUser;
1123 wfProfileIn( __METHOD__ );
1124
1125 $sk = $wgUser->getSkin();
1126
1127 $outText = '';
1128 if ( count( $templates ) > 0 ) {
1129 # Do a batch existence check
1130 $batch = new LinkBatch;
1131 foreach( $templates as $title ) {
1132 $batch->addObj( $title );
1133 }
1134 $batch->execute();
1135
1136 # Construct the HTML
1137 $outText = '<div class="mw-templatesUsedExplanation">';
1138 if ( $preview ) {
1139 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1140 } elseif ( $section ) {
1141 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1142 } else {
1143 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1144 }
1145 $outText .= '</div><ul>';
1146
1147 foreach ( $templates as $titleObj ) {
1148 $r = $titleObj->getRestrictions( 'edit' );
1149 if ( in_array( 'sysop', $r ) ) {
1150 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1151 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1152 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1153 } else {
1154 $protected = '';
1155 }
1156 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1157 }
1158 $outText .= '</ul>';
1159 }
1160 wfProfileOut( __METHOD__ );
1161 return $outText;
1162 }
1163
1164 /**
1165 * Format a size in bytes for output, using an appropriate
1166 * unit (B, KB, MB or GB) according to the magnitude in question
1167 *
1168 * @param $size Size to format
1169 * @return string
1170 */
1171 public function formatSize( $size ) {
1172 global $wgLang;
1173 // For small sizes no decimal places necessary
1174 $round = 0;
1175 if( $size > 1024 ) {
1176 $size = $size / 1024;
1177 if( $size > 1024 ) {
1178 $size = $size / 1024;
1179 // For MB and bigger two decimal places are smarter
1180 $round = 2;
1181 if( $size > 1024 ) {
1182 $size = $size / 1024;
1183 $msg = 'size-gigabytes';
1184 } else {
1185 $msg = 'size-megabytes';
1186 }
1187 } else {
1188 $msg = 'size-kilobytes';
1189 }
1190 } else {
1191 $msg = 'size-bytes';
1192 }
1193 $size = round( $size, $round );
1194 return wfMsgHtml( $msg, $wgLang->formatNum( $size ) );
1195 }
1196
1197 /**
1198 * Given the id of an interface element, constructs the appropriate title
1199 * and accesskey attributes from the system messages. (Note, this is usu-
1200 * ally the id but isn't always, because sometimes the accesskey needs to
1201 * go on a different element than the id, for reverse-compatibility, etc.)
1202 *
1203 * @param string $name Id of the element, minus prefixes.
1204 * @return string title and accesskey attributes, ready to drop in an
1205 * element (e.g., ' title="This does something [x]" accesskey="x"').
1206 */
1207 public function tooltipAndAccesskey($name) {
1208 $out = '';
1209
1210 $tooltip = wfMsg('tooltip-'.$name);
1211 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1212 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1213 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1214 $out .= ' title="'.htmlspecialchars($tooltip);
1215 }
1216 $accesskey = wfMsg('accesskey-'.$name);
1217 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1218 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1219 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1220 } elseif ($out) {
1221 $out .= '"';
1222 }
1223 return $out;
1224 }
1225
1226 /**
1227 * Given the id of an interface element, constructs the appropriate title
1228 * attribute from the system messages. (Note, this is usually the id but
1229 * isn't always, because sometimes the accesskey needs to go on a different
1230 * element than the id, for reverse-compatibility, etc.)
1231 *
1232 * @param string $name Id of the element, minus prefixes.
1233 * @return string title attribute, ready to drop in an element
1234 * (e.g., ' title="This does something"').
1235 */
1236 public function tooltip($name) {
1237 $out = '';
1238
1239 $tooltip = wfMsg('tooltip-'.$name);
1240 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1241 $out = ' title="'.htmlspecialchars($tooltip).'"';
1242 }
1243
1244 return $out;
1245 }
1246 }
1247
1248 ?>