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