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