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