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