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