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