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