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