More sensible semantics for pipe trick with section links after r62076
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Split off some of the internal bits from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin. For the moment, Skin is a descendent class of
6 * Linker. In the future, it should probably be further split so that every
7 * other bit of the wiki doesn't have to go loading up Skin to get at it.
8 *
9 * @ingroup Skins
10 */
11 class Linker {
12
13 /**
14 * Flags for userToolLinks()
15 */
16 const TOOL_LINKS_NOBLOCK = 1;
17
18 function __construct() {}
19
20 /**
21 * Get the appropriate HTML attributes to add to the "a" element of an ex-
22 * ternal link, as created by [wikisyntax].
23 *
24 * @param string $class The contents of the class attribute; if an empty
25 * string is passed, which is the default value, defaults to 'external'.
26 */
27 function getExternalLinkAttributes( $class = 'external' ) {
28 return $this->getLinkAttributesInternal( '', $class );
29 }
30
31 /**
32 * Get the appropriate HTML attributes to add to the "a" element of an in-
33 * terwiki link.
34 *
35 * @param string $title The title text for the link, URL-encoded (???) but
36 * not HTML-escaped
37 * @param string $unused Unused
38 * @param string $class The contents of the class attribute; if an empty
39 * string is passed, which is the default value, defaults to 'external'.
40 */
41 function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
42 global $wgContLang;
43
44 # FIXME: We have a whole bunch of handling here that doesn't happen in
45 # getExternalLinkAttributes, why?
46 $title = urldecode( $title );
47 $title = $wgContLang->checkTitleEncoding( $title );
48 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
49
50 return $this->getLinkAttributesInternal( $title, $class );
51 }
52
53 /**
54 * Get the appropriate HTML attributes to add to the "a" element of an in-
55 * ternal link.
56 *
57 * @param string $title The title text for the link, URL-encoded (???) but
58 * not HTML-escaped
59 * @param string $unused Unused
60 * @param string $class The contents of the class attribute, default none
61 */
62 function getInternalLinkAttributes( $title, $unused = null, $class='' ) {
63 $title = urldecode( $title );
64 $title = str_replace( '_', ' ', $title );
65 return $this->getLinkAttributesInternal( $title, $class );
66 }
67
68 /**
69 * Get the appropriate HTML attributes to add to the "a" element of an in-
70 * ternal link, given the Title object for the page we want to link to.
71 *
72 * @param Title $nt The Title object
73 * @param string $unused Unused
74 * @param string $class The contents of the class attribute, default none
75 * @param mixed $title Optional (unescaped) string to use in the title
76 * attribute; if false, default to the name of the page we're linking to
77 */
78 function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
79 if( $title === false ) {
80 $title = $nt->getPrefixedText();
81 }
82 return $this->getLinkAttributesInternal( $title, $class );
83 }
84
85 /**
86 * Common code for getLinkAttributesX functions
87 */
88 private function getLinkAttributesInternal( $title, $class ) {
89 $title = htmlspecialchars( $title );
90 $class = htmlspecialchars( $class );
91 $r = '';
92 if ( $class != '' ) {
93 $r .= " class=\"$class\"";
94 }
95 if ( $title != '') {
96 $r .= " title=\"$title\"";
97 }
98 return $r;
99 }
100
101 /**
102 * Return the CSS colour of a known link
103 *
104 * @param Title $t
105 * @param integer $threshold user defined threshold
106 * @return string CSS class
107 */
108 function getLinkColour( $t, $threshold ) {
109 $colour = '';
110 if ( $t->isRedirect() ) {
111 # Page is a redirect
112 $colour = 'mw-redirect';
113 } elseif ( $threshold > 0 &&
114 $t->exists() && $t->getLength() < $threshold &&
115 MWNamespace::isContent( $t->getNamespace() ) ) {
116 # Page is a stub
117 $colour = 'stub';
118 }
119 return $colour;
120 }
121
122 /**
123 * This function returns an HTML link to the given target. It serves a few
124 * purposes:
125 * 1) If $target is a Title, the correct URL to link to will be figured
126 * out automatically.
127 * 2) It automatically adds the usual classes for various types of link
128 * targets: "new" for red links, "stub" for short articles, etc.
129 * 3) It escapes all attribute values safely so there's no risk of XSS.
130 * 4) It provides a default tooltip if the target is a Title (the page
131 * name of the target).
132 * link() replaces the old functions in the makeLink() family.
133 *
134 * @param $target Title Can currently only be a Title, but this may
135 * change to support Images, literal URLs, etc.
136 * @param $text string The HTML contents of the <a> element, i.e.,
137 * the link text. This is raw HTML and will not be escaped. If null,
138 * defaults to the prefixed text of the Title; or if the Title is just a
139 * fragment, the contents of the fragment.
140 * @param $customAttribs array A key => value array of extra HTML attri-
141 * butes, such as title and class. (href is ignored.) Classes will be
142 * merged with the default classes, while other attributes will replace
143 * default attributes. All passed attribute values will be HTML-escaped.
144 * A false attribute value means to suppress that attribute.
145 * @param $query array The query string to append to the URL
146 * you're linking to, in key => value array form. Query keys and values
147 * will be URL-encoded.
148 * @param $options mixed String or array of strings:
149 * 'known': Page is known to exist, so don't check if it does.
150 * 'broken': Page is known not to exist, so don't check if it does.
151 * 'noclasses': Don't add any classes automatically (includes "new",
152 * "stub", "mw-redirect", "extiw"). Only use the class attribute
153 * provided, if any, so you get a simple blue link with no funny i-
154 * cons.
155 * 'forcearticlepath': Use the article path always, even with a querystring.
156 * Has compatibility issues on some setups, so avoid wherever possible.
157 * @return string HTML <a> attribute
158 */
159 public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
160 wfProfileIn( __METHOD__ );
161 if( !$target instanceof Title ) {
162 return "<!-- ERROR -->$text";
163 }
164 $options = (array)$options;
165
166 $ret = null;
167 if( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
168 &$customAttribs, &$query, &$options, &$ret ) ) ) {
169 wfProfileOut( __METHOD__ );
170 return $ret;
171 }
172
173 # Normalize the Title if it's a special page
174 $target = $this->normaliseSpecialPage( $target );
175
176 # If we don't know whether the page exists, let's find out.
177 wfProfileIn( __METHOD__ . '-checkPageExistence' );
178 if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
179 if( $target->isKnown() ) {
180 $options []= 'known';
181 } else {
182 $options []= 'broken';
183 }
184 }
185 wfProfileOut( __METHOD__ . '-checkPageExistence' );
186
187 $oldquery = array();
188 if( in_array( "forcearticlepath", $options ) && $query ){
189 $oldquery = $query;
190 $query = array();
191 }
192
193 # Note: we want the href attribute first, for prettiness.
194 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
195 if( in_array( 'forcearticlepath', $options ) && $oldquery ){
196 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
197 }
198
199 $attribs = array_merge(
200 $attribs,
201 $this->linkAttribs( $target, $customAttribs, $options )
202 );
203 if( is_null( $text ) ) {
204 $text = $this->linkText( $target );
205 }
206
207 $ret = null;
208 if( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text, &$attribs, &$ret ) ) ) {
209 $ret = Html::rawElement( 'a', $attribs, $text );
210 }
211
212 wfProfileOut( __METHOD__ );
213 return $ret;
214 }
215
216 /**
217 * Identical to link(), except $options defaults to 'known'.
218 */
219 public function linkKnown( $target, $text = null, $customAttribs = array(), $query = array(), $options = array('known','noclasses') ) {
220 return $this->link( $target, $text, $customAttribs, $query, $options );
221 }
222
223 /**
224 * Returns the Url used to link to a Title
225 */
226 private function linkUrl( $target, $query, $options ) {
227 wfProfileIn( __METHOD__ );
228 # We don't want to include fragments for broken links, because they
229 # generally make no sense.
230 if( in_array( 'broken', $options ) and $target->mFragment !== '' ) {
231 $target = clone $target;
232 $target->mFragment = '';
233 }
234
235 # If it's a broken link, add the appropriate query pieces, unless
236 # there's already an action specified, or unless 'edit' makes no sense
237 # (i.e., for a nonexistent special page).
238 if( in_array( 'broken', $options ) and empty( $query['action'] )
239 and $target->getNamespace() != NS_SPECIAL ) {
240 $query['action'] = 'edit';
241 $query['redlink'] = '1';
242 }
243 $ret = $target->getLinkUrl( $query );
244 wfProfileOut( __METHOD__ );
245 return $ret;
246 }
247
248 /**
249 * Returns the array of attributes used when linking to the Title $target
250 */
251 private function linkAttribs( $target, $attribs, $options ) {
252 wfProfileIn( __METHOD__ );
253 global $wgUser;
254 $defaults = array();
255
256 if( !in_array( 'noclasses', $options ) ) {
257 wfProfileIn( __METHOD__ . '-getClasses' );
258 # Now build the classes.
259 $classes = array();
260
261 if( in_array( 'broken', $options ) ) {
262 $classes[] = 'new';
263 }
264
265 if( $target->isExternal() ) {
266 $classes[] = 'extiw';
267 }
268
269 # Note that redirects never count as stubs here.
270 if ( !in_array( 'broken', $options ) && $target->isRedirect() ) {
271 $classes[] = 'mw-redirect';
272 } elseif( $target->isContentPage() ) {
273 # Check for stub.
274 $threshold = $wgUser->getOption( 'stubthreshold' );
275 if( $threshold > 0 and $target->exists() and $target->getLength() < $threshold ) {
276 $classes[] = 'stub';
277 }
278 }
279 if( $classes != array() ) {
280 $defaults['class'] = implode( ' ', $classes );
281 }
282 wfProfileOut( __METHOD__ . '-getClasses' );
283 }
284
285 # Get a default title attribute.
286 if( $target->getPrefixedText() == '' ) {
287 # A link like [[#Foo]]. This used to mean an empty title
288 # attribute, but that's silly. Just don't output a title.
289 } elseif( in_array( 'known', $options ) ) {
290 $defaults['title'] = $target->getPrefixedText();
291 } else {
292 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
293 }
294
295 # Finally, merge the custom attribs with the default ones, and iterate
296 # over that, deleting all "false" attributes.
297 $ret = array();
298 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
299 foreach( $merged as $key => $val ) {
300 # A false value suppresses the attribute, and we don't want the
301 # href attribute to be overridden.
302 if( $key != 'href' and $val !== false ) {
303 $ret[$key] = $val;
304 }
305 }
306 wfProfileOut( __METHOD__ );
307 return $ret;
308 }
309
310 /**
311 * Default text of the links to the Title $target
312 */
313 private function linkText( $target ) {
314 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
315 if( !$target instanceof Title ) {
316 return '';
317 }
318
319 # If the target is just a fragment, with no title, we return the frag-
320 # ment text. Otherwise, we return the title text itself.
321 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
322 return htmlspecialchars( $target->getFragment() );
323 }
324 return htmlspecialchars( $target->getPrefixedText() );
325 }
326
327 /**
328 * Generate either a normal exists-style link or a stub link, depending
329 * on the given page size.
330 *
331 * @param $size Integer
332 * @param $nt Title object.
333 * @param $text String
334 * @param $query String
335 * @param $trail String
336 * @param $prefix String
337 * @return string HTML of link
338 */
339 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
340 global $wgUser;
341 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
342 $colour = ( $size < $threshold ) ? 'stub' : '';
343 // FIXME: replace deprecated makeColouredLinkObj by link()
344 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
345 }
346
347 /**
348 * Make appropriate markup for a link to the current article. This is currently rendered
349 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
350 * despite $query not being used.
351 */
352 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
353 if ( $text == '' ) {
354 $text = htmlspecialchars( $nt->getPrefixedText() );
355 }
356 list( $inside, $trail ) = Linker::splitTrail( $trail );
357 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
358 }
359
360 function normaliseSpecialPage( Title $title ) {
361 if ( $title->getNamespace() == NS_SPECIAL ) {
362 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
363 if ( !$name ) return $title;
364 $ret = SpecialPage::getTitleFor( $name, $subpage );
365 $ret->mFragment = $title->getFragment();
366 return $ret;
367 } else {
368 return $title;
369 }
370 }
371
372 /**
373 * Returns the filename part of an url.
374 * Used as alternative text for external images.
375 */
376 function fnamePart( $url ) {
377 $basename = strrchr( $url, '/' );
378 if ( false === $basename ) {
379 $basename = $url;
380 } else {
381 $basename = substr( $basename, 1 );
382 }
383 return $basename;
384 }
385
386 /**
387 * Return the code for images which were added via external links,
388 * via Parser::maybeMakeExternalImage().
389 */
390 function makeExternalImage( $url, $alt = '' ) {
391 if ( $alt == '' ) {
392 $alt = $this->fnamePart( $url );
393 }
394 $img = '';
395 $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
396 if(!$success) {
397 wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true);
398 return $img;
399 }
400 return Html::element( 'img',
401 array(
402 'src' => $url,
403 'alt' => $alt ) );
404 }
405
406 /**
407 * Given parameters derived from [[Image:Foo|options...]], generate the
408 * HTML that that syntax inserts in the page.
409 *
410 * @param Title $title Title object
411 * @param File $file File object, or false if it doesn't exist
412 *
413 * @param array $frameParams Associative array of parameters external to the media handler.
414 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
415 * will often be false.
416 * thumbnail If present, downscale and frame
417 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
418 * framed Shows image in original size in a frame
419 * frameless Downscale but don't frame
420 * upright If present, tweak default sizes for portrait orientation
421 * upright_factor Fudge factor for "upright" tweak (default 0.75)
422 * border If present, show a border around the image
423 * align Horizontal alignment (left, right, center, none)
424 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
425 * bottom, text-bottom)
426 * alt Alternate text for image (i.e. alt attribute). Plain text.
427 * caption HTML for image caption.
428 * link-url URL to link to
429 * link-title Title object to link to
430 * no-link Boolean, suppress description link
431 *
432 * @param array $handlerParams Associative array of media handler parameters, to be passed
433 * to transform(). Typical keys are "width" and "page".
434 * @param string $time, timestamp of the file, set as false for current
435 * @param string $query, query params for desc url
436 * @return string HTML for an image, with links, wrappers, etc.
437 */
438 function makeImageLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
439 $res = null;
440 if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
441 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
442 return $res;
443 }
444
445 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
446 if ( $file && !$file->allowInlineDisplay() ) {
447 wfDebug( __METHOD__.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
448 return $this->link( $title );
449 }
450
451 // Shortcuts
452 $fp =& $frameParams;
453 $hp =& $handlerParams;
454
455 // Clean up parameters
456 $page = isset( $hp['page'] ) ? $hp['page'] : false;
457 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
458 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
459 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
460
461 $prefix = $postfix = '';
462
463 if ( 'center' == $fp['align'] ) {
464 $prefix = '<div class="center">';
465 $postfix = '</div>';
466 $fp['align'] = 'none';
467 }
468 if ( $file && !isset( $hp['width'] ) ) {
469 $hp['width'] = $file->getWidth( $page );
470
471 if( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) ) {
472 $wopt = $wgUser->getOption( 'thumbsize' );
473
474 if( !isset( $wgThumbLimits[$wopt] ) ) {
475 $wopt = User::getDefaultOption( 'thumbsize' );
476 }
477
478 // Reduce width for upright images when parameter 'upright' is used
479 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
480 $fp['upright'] = $wgThumbUpright;
481 }
482 // Use width which is smaller: real image width or user preference width
483 // 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
484 $prefWidth = isset( $fp['upright'] ) ?
485 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
486 $wgThumbLimits[$wopt];
487 if ( $hp['width'] <= 0 || $prefWidth < $hp['width'] ) {
488 if( !isset( $hp['height'] ) ) {
489 $hp['width'] = $prefWidth;
490 }
491 }
492 }
493 }
494
495 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
496 # Create a thumbnail. Alignment depends on language
497 # writing direction, # right aligned for left-to-right-
498 # languages ("Western languages"), left-aligned
499 # for right-to-left-languages ("Semitic languages")
500 #
501 # If thumbnail width has not been provided, it is set
502 # to the default user option as specified in Language*.php
503 if ( $fp['align'] == '' ) {
504 $fp['align'] = $wgContLang->alignEnd();
505 }
506 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
507 }
508
509 if ( $file && isset( $fp['frameless'] ) ) {
510 $srcWidth = $file->getWidth( $page );
511 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
512 # This is the same behaviour as the "thumb" option does it already.
513 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
514 $hp['width'] = $srcWidth;
515 }
516 }
517
518 if ( $file && $hp['width'] ) {
519 # Create a resized image, without the additional thumbnail features
520 $thumb = $file->transform( $hp );
521 } else {
522 $thumb = false;
523 }
524
525 if ( !$thumb ) {
526 $s = $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time==true );
527 } else {
528 $params = array(
529 'alt' => $fp['alt'],
530 'title' => $fp['title'],
531 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false ,
532 'img-class' => isset( $fp['border'] ) ? 'thumbborder' : false );
533 if ( !empty( $fp['link-url'] ) ) {
534 $params['custom-url-link'] = $fp['link-url'];
535 } elseif ( !empty( $fp['link-title'] ) ) {
536 $params['custom-title-link'] = $fp['link-title'];
537 } elseif ( !empty( $fp['no-link'] ) ) {
538 // No link
539 } else {
540 $params['desc-link'] = true;
541 $params['desc-query'] = $query;
542 }
543
544 $s = $thumb->toHtml( $params );
545 }
546 if ( $fp['align'] != '' ) {
547 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
548 }
549 return str_replace("\n", ' ',$prefix.$s.$postfix);
550 }
551
552 /**
553 * Make HTML for a thumbnail including image, border and caption
554 * @param Title $title
555 * @param File $file File object or false if it doesn't exist
556 */
557 function makeThumbLinkObj( Title $title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
558 $frameParams = array(
559 'alt' => $alt,
560 'caption' => $label,
561 'align' => $align
562 );
563 if ( $framed ) $frameParams['framed'] = true;
564 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
565 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
566 }
567
568 function makeThumbLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
569 global $wgStylePath, $wgContLang;
570 $exists = $file && $file->exists();
571
572 # Shortcuts
573 $fp =& $frameParams;
574 $hp =& $handlerParams;
575
576 $page = isset( $hp['page'] ) ? $hp['page'] : false;
577 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
578 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
579 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
580 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
581
582 if ( empty( $hp['width'] ) ) {
583 // Reduce width for upright images when parameter 'upright' is used
584 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
585 }
586 $thumb = false;
587
588 if ( !$exists ) {
589 $outerWidth = $hp['width'] + 2;
590 } else {
591 if ( isset( $fp['manualthumb'] ) ) {
592 # Use manually specified thumbnail
593 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
594 if( $manual_title ) {
595 $manual_img = wfFindFile( $manual_title );
596 if ( $manual_img ) {
597 $thumb = $manual_img->getUnscaledThumb();
598 } else {
599 $exists = false;
600 }
601 }
602 } elseif ( isset( $fp['framed'] ) ) {
603 // Use image dimensions, don't scale
604 $thumb = $file->getUnscaledThumb( $page );
605 } else {
606 # Do not present an image bigger than the source, for bitmap-style images
607 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
608 $srcWidth = $file->getWidth( $page );
609 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
610 $hp['width'] = $srcWidth;
611 }
612 $thumb = $file->transform( $hp );
613 }
614
615 if ( $thumb ) {
616 $outerWidth = $thumb->getWidth() + 2;
617 } else {
618 $outerWidth = $hp['width'] + 2;
619 }
620 }
621
622 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
623 # So we don't need to pass it here in $query. However, the URL for the
624 # zoom icon still needs it, so we make a unique query for it. See bug 14771
625 $url = $title->getLocalURL( $query );
626 if( $page ) {
627 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
628 }
629
630 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
631
632 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
633 if( !$exists ) {
634 $s .= $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time==true );
635 $zoomicon = '';
636 } elseif ( !$thumb ) {
637 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
638 $zoomicon = '';
639 } else {
640 $s .= $thumb->toHtml( array(
641 'alt' => $fp['alt'],
642 'title' => $fp['title'],
643 'img-class' => 'thumbimage',
644 'desc-link' => true,
645 'desc-query' => $query ) );
646 if ( isset( $fp['framed'] ) ) {
647 $zoomicon="";
648 } else {
649 $zoomicon = '<div class="magnify">'.
650 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
651 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
652 'width="15" height="11" alt="" /></a></div>';
653 }
654 }
655 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
656 return str_replace("\n", ' ', $s);
657 }
658
659 /**
660 * Make a "broken" link to an image
661 *
662 * @param Title $title Image title
663 * @param string $text Link label
664 * @param string $query Query string
665 * @param string $trail Link trail
666 * @param string $prefix Link prefix
667 * @param bool $time, a file of a certain timestamp was requested
668 * @return string
669 */
670 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
671 global $wgEnableUploads, $wgUploadNavigationUrl;
672 if( $title instanceof Title ) {
673 wfProfileIn( __METHOD__ );
674 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
675 if( ( $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
676 if( $text == '' )
677 $text = htmlspecialchars( $title->getPrefixedText() );
678
679 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
680 if( $redir ) {
681 wfProfileOut( __METHOD__ );
682 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
683 }
684
685 $href = $this->getUploadUrl( $title, $query );
686
687
688 list( $inside, $trail ) = self::splitTrail( $trail );
689
690 wfProfileOut( __METHOD__ );
691 return Html::element( 'a', array(
692 'href' => $href,
693 'class' => 'new',
694 'title' => $title->getPrefixedText()
695 ), $prefix . $text . $inside ) . $trail;
696 } else {
697 wfProfileOut( __METHOD__ );
698 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
699 }
700 } else {
701 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
702 }
703 }
704
705 /**
706 * Get the URL to upload a certain file
707 *
708 * @param $destFile Title Title of the file to upload
709 * @param $query string Urlencoded query string to prepend
710 * @return string Urlencoded URL
711 */
712 protected function getUploadUrl( $destFile, $query = '' ) {
713 global $wgUploadNavigationUrl;
714 $q = 'wpDestFile=' . $destFile->getPartialUrl();
715 if( $query != '' )
716 $q .= '&' . $query;
717
718 if( $wgUploadNavigationUrl ) {
719 return wfAppendQuery( $wgUploadNavigationUrl, $q );
720 } else {
721 $upload = SpecialPage::getTitleFor( 'Upload' );
722 return $upload->getLocalUrl( $q );
723 }
724 }
725
726 /**
727 * Create a direct link to a given uploaded file.
728 *
729 * @param $title Title object.
730 * @param $text String: pre-sanitized HTML
731 * @param $time string: time image was created
732 * @return string HTML
733 *
734 * @public
735 * @todo Handle invalid or missing images better.
736 */
737 function makeMediaLinkObj( $title, $text = '', $time = false ) {
738 if( is_null( $title ) ) {
739 ### HOTFIX. Instead of breaking, return empty string.
740 return $text;
741 } else {
742 $img = wfFindFile( $title, array( 'time' => $time ) );
743 if( $img ) {
744 $url = $img->getURL();
745 $class = 'internal';
746 } else {
747 $url = $this->getUploadUrl( $title );
748 $class = 'new';
749 }
750 $alt = htmlspecialchars( $title->getText() );
751 if( $text == '' ) {
752 $text = $alt;
753 }
754 $u = htmlspecialchars( $url );
755 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
756 }
757 }
758
759 /**
760 * Make a link to a special page given its name and, optionally,
761 * a message key from the link text.
762 * Usage example: $skin->specialLink( 'recentchanges' )
763 */
764 function specialLink( $name, $key = '' ) {
765 global $wgContLang;
766
767 if ( $key == '' ) { $key = strtolower( $name ); }
768 $pn = $wgContLang->ucfirst( $name );
769 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
770 wfMsg( $key ) );
771 }
772
773 /**
774 * Make an external link
775 * @param String $url URL to link to
776 * @param String $text text of link
777 * @param boolean $escape Do we escape the link text?
778 * @param String $linktype Type of external link. Gets added to the classes
779 * @param array $attribs Array of extra attributes to <a>
780 *
781 * @todo FIXME: This is a really crappy implementation. $linktype and
782 * 'external' are mashed into the class attrib for the link (which is made
783 * into a string). Then, if we've got additional params in $attribs, we
784 * add to it. People using this might want to change the classes (or other
785 * default link attributes), but passing $attribsText is just messy. Would
786 * make a lot more sense to make put the classes into $attribs, let the
787 * hook play with them, *then* expand it all at once.
788 */
789 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
790 if ( isset( $attribs[ 'class' ] ) ) $class = $attribs[ 'class' ]; # yet another hack :(
791 else $class = 'external ' . $linktype;
792
793 $attribsText = $this->getExternalLinkAttributes( $class );
794 $url = htmlspecialchars( $url );
795 if( $escape ) {
796 $text = htmlspecialchars( $text );
797 }
798 $link = '';
799 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
800 if(!$success) {
801 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true);
802 return $link;
803 }
804 if ( $attribs ) {
805 $attribsText .= Html::expandAttributes( $attribs );
806 }
807 return '<a href="'.$url.'"'.$attribsText.'>'.$text.'</a>';
808 }
809
810 /**
811 * Make user link (or user contributions for unregistered users)
812 * @param $userId Integer: user id in database.
813 * @param $userText String: user name in database
814 * @return string HTML fragment
815 * @private
816 */
817 function userLink( $userId, $userText ) {
818 if( $userId == 0 ) {
819 $page = SpecialPage::getTitleFor( 'Contributions', $userText );
820 } else {
821 $page = Title::makeTitle( NS_USER, $userText );
822 }
823 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
824 }
825
826 /**
827 * Generate standard user tool links (talk, contributions, block link, etc.)
828 *
829 * @param int $userId User identifier
830 * @param string $userText User name or IP address
831 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
832 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
833 * @param int $edits, user edit count (optional, for performance)
834 * @return string
835 */
836 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
837 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
838 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
839 $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
840
841 $items = array();
842 if( $talkable ) {
843 $items[] = $this->userTalkLink( $userId, $userText );
844 }
845 if( $userId ) {
846 // check if the user has an edit
847 $attribs = array();
848 if( $redContribsWhenNoEdits ) {
849 $count = !is_null($edits) ? $edits : User::edits( $userId );
850 if( $count == 0 ) {
851 $attribs['class'] = 'new';
852 }
853 }
854 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
855
856 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
857 }
858 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
859 $items[] = $this->blockLink( $userId, $userText );
860 }
861
862 if( $items ) {
863 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
864 } else {
865 return '';
866 }
867 }
868
869 /**
870 * Alias for userToolLinks( $userId, $userText, true );
871 * @param int $userId User identifier
872 * @param string $userText User name or IP address
873 * @param int $edits, user edit count (optional, for performance)
874 */
875 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
876 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
877 }
878
879
880 /**
881 * @param $userId Integer: user id in database.
882 * @param $userText String: user name in database.
883 * @return string HTML fragment with user talk link
884 * @private
885 */
886 function userTalkLink( $userId, $userText ) {
887 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
888 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
889 return $userTalkLink;
890 }
891
892 /**
893 * @param $userId Integer: userid
894 * @param $userText String: user name in database.
895 * @return string HTML fragment with block link
896 * @private
897 */
898 function blockLink( $userId, $userText ) {
899 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
900 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
901 return $blockLink;
902 }
903
904 /**
905 * Generate a user link if the current user is allowed to view it
906 * @param $rev Revision object.
907 * @param $isPublic, bool, show only if all users can see it
908 * @return string HTML
909 */
910 function revUserLink( $rev, $isPublic = false ) {
911 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
912 $link = wfMsgHtml( 'rev-deleted-user' );
913 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
914 $link = $this->userLink( $rev->getUser( Revision::FOR_THIS_USER ),
915 $rev->getUserText( Revision::FOR_THIS_USER ) );
916 } else {
917 $link = wfMsgHtml( 'rev-deleted-user' );
918 }
919 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
920 return '<span class="history-deleted">' . $link . '</span>';
921 }
922 return $link;
923 }
924
925 /**
926 * Generate a user tool link cluster if the current user is allowed to view it
927 * @param $rev Revision object.
928 * @param $isPublic, bool, show only if all users can see it
929 * @return string HTML
930 */
931 function revUserTools( $rev, $isPublic = false ) {
932 if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
933 $link = wfMsgHtml( 'rev-deleted-user' );
934 } else if( $rev->userCan( Revision::DELETED_USER ) ) {
935 $userId = $rev->getUser( Revision::FOR_THIS_USER );
936 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
937 $link = $this->userLink( $userId, $userText ) .
938 ' ' . $this->userToolLinks( $userId, $userText );
939 } else {
940 $link = wfMsgHtml( 'rev-deleted-user' );
941 }
942 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
943 return ' <span class="history-deleted">' . $link . '</span>';
944 }
945 return $link;
946 }
947
948 /**
949 * This function is called by all recent changes variants, by the page history,
950 * and by the user contributions list. It is responsible for formatting edit
951 * comments. It escapes any HTML in the comment, but adds some CSS to format
952 * auto-generated comments (from section editing) and formats [[wikilinks]].
953 *
954 * @author Erik Moeller <moeller@scireview.de>
955 *
956 * Note: there's not always a title to pass to this function.
957 * Since you can't set a default parameter for a reference, I've turned it
958 * temporarily to a value pass. Should be adjusted further. --brion
959 *
960 * @param string $comment
961 * @param mixed $title Title object (to generate link to the section in autocomment) or null
962 * @param bool $local Whether section links should refer to local page
963 */
964 function formatComment($comment, $title = null, $local = false) {
965 wfProfileIn( __METHOD__ );
966
967 # Sanitize text a bit:
968 $comment = str_replace( "\n", " ", $comment );
969 # Allow HTML entities (for bug 13815)
970 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
971
972 # Render autocomments and make links:
973 $comment = $this->formatAutocomments( $comment, $title, $local );
974 $comment = $this->formatLinksInComment( $comment, $title, $local );
975
976 wfProfileOut( __METHOD__ );
977 return $comment;
978 }
979
980 /**
981 * The pattern for autogen comments is / * foo * /, which makes for
982 * some nasty regex.
983 * We look for all comments, match any text before and after the comment,
984 * add a separator where needed and format the comment itself with CSS
985 * Called by Linker::formatComment.
986 *
987 * @param string $comment Comment text
988 * @param object $title An optional title object used to links to sections
989 * @return string $comment formatted comment
990 *
991 * @todo Document the $local parameter.
992 */
993 private function formatAutocomments( $comment, $title = null, $local = false ) {
994 // Bah!
995 $this->autocommentTitle = $title;
996 $this->autocommentLocal = $local;
997 $comment = preg_replace_callback(
998 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
999 array( $this, 'formatAutocommentsCallback' ),
1000 $comment );
1001 unset( $this->autocommentTitle );
1002 unset( $this->autocommentLocal );
1003 return $comment;
1004 }
1005
1006 private function formatAutocommentsCallback( $match ) {
1007 $title = $this->autocommentTitle;
1008 $local = $this->autocommentLocal;
1009
1010 $pre = $match[1];
1011 $auto = $match[2];
1012 $post = $match[3];
1013 $link = '';
1014 if ( $title ) {
1015 $section = $auto;
1016
1017 # Generate a valid anchor name from the section title.
1018 # Hackish, but should generally work - we strip wiki
1019 # syntax, including the magic [[: that is used to
1020 # "link rather than show" in case of images and
1021 # interlanguage links.
1022 $section = str_replace( '[[:', '', $section );
1023 $section = str_replace( '[[', '', $section );
1024 $section = str_replace( ']]', '', $section );
1025 if ( $local ) {
1026 $sectionTitle = Title::newFromText( '#' . $section );
1027 } else {
1028 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1029 $title->getDBkey(), $section );
1030 }
1031 if ( $sectionTitle ) {
1032 $link = $this->link( $sectionTitle,
1033 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1034 'noclasses' );
1035 } else {
1036 $link = '';
1037 }
1038 }
1039 $auto = "$link$auto";
1040 if( $pre ) {
1041 # written summary $presep autocomment (summary /* section */)
1042 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1043 }
1044 if( $post ) {
1045 # autocomment $postsep written summary (/* section */ summary)
1046 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1047 }
1048 $auto = '<span class="autocomment">' . $auto . '</span>';
1049 $comment = $pre . $auto . $post;
1050 return $comment;
1051 }
1052
1053 /**
1054 * Formats wiki links and media links in text; all other wiki formatting
1055 * is ignored
1056 *
1057 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1058 * @param string $comment Text to format links in
1059 * @return string
1060 */
1061 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1062 $this->commentContextTitle = $title;
1063 $this->commentLocal = $local;
1064 $html = preg_replace_callback(
1065 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1066 array( $this, 'formatLinksInCommentCallback' ),
1067 $comment );
1068 unset( $this->commentContextTitle );
1069 unset( $this->commentLocal );
1070 return $html;
1071 }
1072
1073 protected function formatLinksInCommentCallback( $match ) {
1074 global $wgContLang;
1075
1076 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1077 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1078
1079 $comment = $match[0];
1080
1081 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1082 if( strpos( $match[1], '%' ) !== false ) {
1083 $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
1084 }
1085
1086 # Handle link renaming [[foo|text]] will show link as "text"
1087 if( $match[3] != "" ) {
1088 $text = $match[3];
1089 if( $match[1] === "" && $this->commentContextTitle ) {
1090 $match[1] = Linker::getPipeTrickLink( $text, $this->commentContextTitle );
1091 }
1092 } elseif( $match[2] == "|" ) {
1093 $text = Linker::getPipeTrickText( $match[1] );
1094 } else {
1095 $text = $match[1];
1096 }
1097 $submatch = array();
1098 $thelink = null;
1099 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1100 # Media link; trail not supported.
1101 $linkRegexp = '/\[\[(.*?)\]\]/';
1102 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1103 $thelink = $this->makeMediaLinkObj( $title, $text );
1104 } else {
1105 # Other kind of link
1106 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1107 $trail = $submatch[1];
1108 } else {
1109 $trail = "";
1110 }
1111 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1112 if (isset($match[1][0]) && $match[1][0] == ':')
1113 $match[1] = substr($match[1], 1);
1114 list( $inside, $trail ) = Linker::splitTrail( $trail );
1115
1116 $linkText = $text;
1117 $linkTarget = Linker::normalizeSubpageLink( $this->commentContextTitle,
1118 $match[1], $linkText );
1119
1120 $target = Title::newFromText( $linkTarget );
1121 if( $target ) {
1122 if( $target->getText() == '' && !$this->commentLocal && $this->commentContextTitle ) {
1123 $newTarget = clone( $this->commentContextTitle );
1124 $newTarget->setFragment( '#' . $target->getFragment() );
1125 $target = $newTarget;
1126 }
1127 $thelink = $this->link(
1128 $target,
1129 $linkText . $inside
1130 ) . $trail;
1131 }
1132 }
1133 if( $thelink ) {
1134 // If the link is still valid, go ahead and replace it in!
1135 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1136 }
1137
1138 return $comment;
1139 }
1140
1141 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1142 # Valid link forms:
1143 # Foobar -- normal
1144 # :Foobar -- override special treatment of prefix (images, language links)
1145 # /Foobar -- convert to CurrentPage/Foobar
1146 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1147 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1148 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1149
1150 wfProfileIn( __METHOD__ );
1151 $ret = $target; # default return value is no change
1152
1153 # Some namespaces don't allow subpages,
1154 # so only perform processing if subpages are allowed
1155 if( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1156 $hash = strpos( $target, '#' );
1157 if( $hash !== false ) {
1158 $suffix = substr( $target, $hash );
1159 $target = substr( $target, 0, $hash );
1160 } else {
1161 $suffix = '';
1162 }
1163 # bug 7425
1164 $target = trim( $target );
1165 # Look at the first character
1166 if( $target != '' && $target{0} === '/' ) {
1167 # / at end means we don't want the slash to be shown
1168 $m = array();
1169 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1170 if( $trailingSlashes ) {
1171 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1172 } else {
1173 $noslash = substr( $target, 1 );
1174 }
1175
1176 $ret = $contextTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1177 if( $text === '' ) {
1178 $text = $target . $suffix;
1179 } # this might be changed for ugliness reasons
1180 } else {
1181 # check for .. subpage backlinks
1182 $dotdotcount = 0;
1183 $nodotdot = $target;
1184 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1185 ++$dotdotcount;
1186 $nodotdot = substr( $nodotdot, 3 );
1187 }
1188 if($dotdotcount > 0) {
1189 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1190 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1191 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1192 # / at the end means don't show full path
1193 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1194 $nodotdot = substr( $nodotdot, 0, -1 );
1195 if( $text === '' ) {
1196 $text = $nodotdot . $suffix;
1197 }
1198 }
1199 $nodotdot = trim( $nodotdot );
1200 if( $nodotdot != '' ) {
1201 $ret .= '/' . $nodotdot;
1202 }
1203 $ret .= $suffix;
1204 }
1205 }
1206 }
1207 }
1208
1209 wfProfileOut( __METHOD__ );
1210 return $ret;
1211 }
1212
1213 /**
1214 * Returns valid title characters and namespace characters for pipe trick.
1215 *
1216 * FIXME: the namespace characters should not be specified like this...
1217 */
1218 static function getPipeTrickCharacterClasses() {
1219 global $wgLegalTitleChars;
1220 return array( "[$wgLegalTitleChars]", '[ _0-9A-Za-z\x80-\xff-]' );
1221 }
1222
1223 /**
1224 * From the [[title|]] return link-text as though the used typed [[title|link-text]]
1225 *
1226 * For most links this be as though the user typed [[ns:title|title]]
1227 * However [[ns:title (context)|]], [[ns:title, context|]] and [[ns:title (context), context|]]
1228 * [[#title (context)|]] [[../context/title (context), context|]]
1229 * all return the |title]] with no context or indicative punctuation.
1230 *
1231 * @param string $link from [[$link|]]
1232 * @return string $text for [[$link|$text]]
1233 */
1234 static function getPipeTrickText( $link ) {
1235 static $rexps = FALSE;
1236 if( !$rexps ) {
1237 list( $tc, $nc ) = Linker::getPipeTrickCharacterClasses();
1238 $rexps = array (
1239 # try this first, to turn "[[A, B (C)|]]" into "A, B"
1240 "/^(:?$nc+:|[:#\/]|$tc+[\\/#]|)($tc+?)( \\($tc+\\)| ($tc+))$/", # [[ns:page (context)|]]
1241 "/^(:?$nc+:|[:#\/]|$tc+[\\/#]|)($tc+?)( \\($tc+\\)| ($tc+)|)((?:,|,) $tc+|)$/", # [[ns:page (context), context|]]
1242 );
1243 }
1244 $text = urldecode( $link );
1245
1246 for( $i = 0; $i < count( $rexps ); $i++) {
1247 if( preg_match( $rexps[$i], $text, $m ) )
1248 return $m[2];
1249 }
1250 return $text;
1251 }
1252
1253 /**
1254 * From the [[|link-text]] return the title as though the user typed [[title|link-text]]
1255 *
1256 * On most pages this will return link-text or "" if the link-text is not a valid title
1257 * On pages like [[ns:title (context)]] and [[ns:title, context]] it will act like
1258 * [[ns:link-text (context)|link-text]] and [[ns:link-text, context|link-text]]
1259 *
1260 * @param string $text from [[|$text]]
1261 * @param Title $title to resolve the link against
1262 * @return string $link for [[$link|$text]]
1263 */
1264 static function getPipeTrickLink( $text, $title ) {
1265 static $rexps = FALSE, $tc;
1266 if( !$rexps ) {
1267 list( $tc, $nc ) = Linker::getPipeTrickCharacterClasses();
1268 $rexps = array (
1269 "/^($nc+:|)$tc+?( \\($tc+\\)| ($tc+))$/", # [[ns:page (context)|]]
1270 "/^($nc+:|)$tc+?(?:(?: \\($tc+\\)| ($tc+)|)((?:,|,) $tc+|))$/" # [[ns:page (context), context|]]
1271 );
1272 }
1273
1274 if( !preg_match( "/^$tc+$/", $text ) )
1275 return '';
1276
1277 $t = $title->getText();
1278
1279 for( $i = 0; $i < count( $rexps ); $i++) {
1280 if( preg_match( $rexps[$i], $t, $m ) )
1281 return "$m[1]$text$m[2]";
1282 }
1283 return $text;
1284 }
1285
1286 /**
1287 * Wrap a comment in standard punctuation and formatting if
1288 * it's non-empty, otherwise return empty string.
1289 *
1290 * @param string $comment
1291 * @param mixed $title Title object (to generate link to section in autocomment) or null
1292 * @param bool $local Whether section links should refer to local page
1293 *
1294 * @return string
1295 */
1296 function commentBlock( $comment, $title = null, $local = false ) {
1297 // '*' used to be the comment inserted by the software way back
1298 // in antiquity in case none was provided, here for backwards
1299 // compatability, acc. to brion -ævar
1300 if( $comment == '' || $comment == '*' ) {
1301 return '';
1302 } else {
1303 $formatted = $this->formatComment( $comment, $title, $local );
1304 return " <span class=\"comment\">($formatted)</span>";
1305 }
1306 }
1307
1308 /**
1309 * Wrap and format the given revision's comment block, if the current
1310 * user is allowed to view it.
1311 *
1312 * @param Revision $rev
1313 * @param bool $local Whether section links should refer to local page
1314 * @param $isPublic, show only if all users can see it
1315 * @return string HTML
1316 */
1317 function revComment( Revision $rev, $local = false, $isPublic = false ) {
1318 if( $rev->getRawComment() == "" ) return "";
1319 if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1320 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1321 } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1322 $block = $this->commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1323 $rev->getTitle(), $local );
1324 } else {
1325 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1326 }
1327 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1328 return " <span class=\"history-deleted\">$block</span>";
1329 }
1330 return $block;
1331 }
1332
1333 public function formatRevisionSize( $size ) {
1334 if ( $size == 0 ) {
1335 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1336 } else {
1337 global $wgLang;
1338 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1339 $stxt = "($stxt)";
1340 }
1341 $stxt = htmlspecialchars( $stxt );
1342 return "<span class=\"history-size\">$stxt</span>";
1343 }
1344
1345 /**
1346 * Add another level to the Table of Contents
1347 */
1348 function tocIndent() {
1349 return "\n<ul>";
1350 }
1351
1352 /**
1353 * Finish one or more sublevels on the Table of Contents
1354 */
1355 function tocUnindent($level) {
1356 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1357 }
1358
1359 /**
1360 * parameter level defines if we are on an indentation level
1361 */
1362 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1363 $classes = "toclevel-$level";
1364 if ( $sectionIndex !== false )
1365 $classes .= " tocsection-$sectionIndex";
1366 return "\n<li class=\"$classes\"><a href=\"#" .
1367 $anchor . '"><span class="tocnumber">' .
1368 $tocnumber . '</span> <span class="toctext">' .
1369 $tocline . '</span></a>';
1370 }
1371
1372 /**
1373 * End a Table Of Contents line.
1374 * tocUnindent() will be used instead if we're ending a line below
1375 * the new level.
1376 */
1377 function tocLineEnd() {
1378 return "</li>\n";
1379 }
1380
1381 /**
1382 * Wraps the TOC in a table and provides the hide/collapse javascript.
1383 * @param string $toc html of the Table Of Contents
1384 * @return string Full html of the TOC
1385 */
1386 function tocList($toc) {
1387 $title = wfMsgHtml('toc') ;
1388 return
1389 '<table id="toc" class="toc"><tr><td>'
1390 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1391 . $toc
1392 # no trailing newline, script should not be wrapped in a
1393 # paragraph
1394 . "</ul>\n</td></tr></table>"
1395 . Html::inlineScript(
1396 'if (window.showTocToggle) {'
1397 . ' var tocShowText = "' . Xml::escapeJsString( wfMsg('showtoc') ) . '";'
1398 . ' var tocHideText = "' . Xml::escapeJsString( wfMsg('hidetoc') ) . '";'
1399 . ' showTocToggle();'
1400 . ' } ' )
1401 . "\n";
1402 }
1403
1404 /**
1405 * Generate a table of contents from a section tree
1406 * Currently unused.
1407 * @param $tree Return value of ParserOutput::getSections()
1408 * @return string HTML
1409 */
1410 public function generateTOC( $tree ) {
1411 $toc = '';
1412 $lastLevel = 0;
1413 foreach ( $tree as $section ) {
1414 if ( $section['toclevel'] > $lastLevel )
1415 $toc .= $this->tocIndent();
1416 else if ( $section['toclevel'] < $lastLevel )
1417 $toc .= $this->tocUnindent(
1418 $lastLevel - $section['toclevel'] );
1419 else
1420 $toc .= $this->tocLineEnd();
1421
1422 $toc .= $this->tocLine( $section['anchor'],
1423 $section['line'], $section['number'],
1424 $section['toclevel'], $section['index'] );
1425 $lastLevel = $section['toclevel'];
1426 }
1427 $toc .= $this->tocLineEnd();
1428 return $this->tocList( $toc );
1429 }
1430
1431 /**
1432 * Create a section edit link. This supersedes editSectionLink() and
1433 * editSectionLinkForOther().
1434 *
1435 * @param $nt Title The title being linked to (may not be the same as
1436 * $wgTitle, if the section is included from a template)
1437 * @param $section string The designation of the section being pointed to,
1438 * to be included in the link, like "&section=$section"
1439 * @param $tooltip string The tooltip to use for the link: will be escaped
1440 * and wrapped in the 'editsectionhint' message
1441 * @return string HTML to use for edit link
1442 */
1443 public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
1444 // HTML generated here should probably have userlangattributes
1445 // added to it for LTR text on RTL pages
1446 $attribs = array();
1447 if( !is_null( $tooltip ) ) {
1448 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1449 }
1450 $link = $this->link( $nt, wfMsg('editsection'),
1451 $attribs,
1452 array( 'action' => 'edit', 'section' => $section ),
1453 array( 'noclasses', 'known' )
1454 );
1455
1456 # Run the old hook. This takes up half of the function . . . hopefully
1457 # we can rid of it someday.
1458 $attribs = '';
1459 if( $tooltip ) {
1460 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1461 $attribs = " title=\"$attribs\"";
1462 }
1463 $result = null;
1464 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result ) );
1465 if( !is_null( $result ) ) {
1466 # For reverse compatibility, add the brackets *after* the hook is
1467 # run, and even add them to hook-provided text. (This is the main
1468 # reason that the EditSectionLink hook is deprecated in favor of
1469 # DoEditSectionLink: it can't change the brackets or the span.)
1470 $result = wfMsgHtml( 'editsection-brackets', $result );
1471 return "<span class=\"editsection\">$result</span>";
1472 }
1473
1474 # Add the brackets and the span, and *then* run the nice new hook, with
1475 # clean and non-redundant arguments.
1476 $result = wfMsgHtml( 'editsection-brackets', $link );
1477 $result = "<span class=\"editsection\">$result</span>";
1478
1479 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1480 return $result;
1481 }
1482
1483 /**
1484 * Create a headline for content
1485 *
1486 * @param int $level The level of the headline (1-6)
1487 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1488 * This *must* be at least '>' for no attribs
1489 * @param string $anchor The anchor to give the headline (the bit after the #)
1490 * @param string $text The text of the header
1491 * @param string $link HTML to add for the section edit link
1492 * @param mixed $legacyAnchor A second, optional anchor to give for
1493 * backward compatibility (false to omit)
1494 *
1495 * @return string HTML headline
1496 */
1497 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1498 $ret = "<h$level$attribs"
1499 . $link
1500 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1501 . "</h$level>";
1502 if ( $legacyAnchor !== false ) {
1503 $ret = "<a id=\"$legacyAnchor\"></a>$ret";
1504 }
1505 return $ret;
1506 }
1507
1508 /**
1509 * Split a link trail, return the "inside" portion and the remainder of the trail
1510 * as a two-element array
1511 *
1512 * @static
1513 */
1514 static function splitTrail( $trail ) {
1515 static $regex = false;
1516 if ( $regex === false ) {
1517 global $wgContLang;
1518 $regex = $wgContLang->linkTrail();
1519 }
1520 $inside = '';
1521 if ( $trail != '' ) {
1522 $m = array();
1523 if ( preg_match( $regex, $trail, $m ) ) {
1524 $inside = $m[1];
1525 $trail = $m[2];
1526 }
1527 }
1528 return array( $inside, $trail );
1529 }
1530
1531 /**
1532 * Generate a rollback link for a given revision. Currently it's the
1533 * caller's responsibility to ensure that the revision is the top one. If
1534 * it's not, of course, the user will get an error message.
1535 *
1536 * If the calling page is called with the parameter &bot=1, all rollback
1537 * links also get that parameter. It causes the edit itself and the rollback
1538 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1539 * changes, so this allows sysops to combat a busy vandal without bothering
1540 * other users.
1541 *
1542 * @param Revision $rev
1543 */
1544 function generateRollback( $rev ) {
1545 return '<span class="mw-rollback-link">['
1546 . $this->buildRollbackLink( $rev )
1547 . ']</span>';
1548 }
1549
1550 /**
1551 * Build a raw rollback link, useful for collections of "tool" links
1552 *
1553 * @param Revision $rev
1554 * @return string
1555 */
1556 public function buildRollbackLink( $rev ) {
1557 global $wgRequest, $wgUser;
1558 $title = $rev->getTitle();
1559 $query = array(
1560 'action' => 'rollback',
1561 'from' => $rev->getUserText()
1562 );
1563 if( $wgRequest->getBool( 'bot' ) ) {
1564 $query['bot'] = '1';
1565 $query['hidediff'] = '1'; // bug 15999
1566 }
1567 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1568 $rev->getUserText() ) );
1569 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1570 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1571 $query, array( 'known', 'noclasses' ) );
1572 }
1573
1574 /**
1575 * Returns HTML for the "templates used on this page" list.
1576 *
1577 * @param array $templates Array of templates from Article::getUsedTemplate
1578 * or similar
1579 * @param bool $preview Whether this is for a preview
1580 * @param bool $section Whether this is for a section edit
1581 * @return string HTML output
1582 */
1583 public function formatTemplates( $templates, $preview = false, $section = false ) {
1584 wfProfileIn( __METHOD__ );
1585
1586 $outText = '';
1587 if ( count( $templates ) > 0 ) {
1588 # Do a batch existence check
1589 $batch = new LinkBatch;
1590 foreach( $templates as $title ) {
1591 $batch->addObj( $title );
1592 }
1593 $batch->execute();
1594
1595 # Construct the HTML
1596 $outText = '<div class="mw-templatesUsedExplanation">';
1597 if ( $preview ) {
1598 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1599 } elseif ( $section ) {
1600 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1601 } else {
1602 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1603 }
1604 $outText .= "</div><ul>\n";
1605
1606 usort( $templates, array( 'Title', 'compare' ) );
1607 foreach ( $templates as $titleObj ) {
1608 $r = $titleObj->getRestrictions( 'edit' );
1609 if ( in_array( 'sysop', $r ) ) {
1610 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1611 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1612 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1613 } else {
1614 $protected = '';
1615 }
1616 if( $titleObj->quickUserCan( 'edit' ) ) {
1617 $editLink = $this->link(
1618 $titleObj,
1619 wfMsg( 'editlink' ),
1620 array(),
1621 array( 'action' => 'edit' )
1622 );
1623 } else {
1624 $editLink = $this->link(
1625 $titleObj,
1626 wfMsg( 'viewsourcelink' ),
1627 array(),
1628 array( 'action' => 'edit' )
1629 );
1630 }
1631 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1632 }
1633 $outText .= '</ul>';
1634 }
1635 wfProfileOut( __METHOD__ );
1636 return $outText;
1637 }
1638
1639 /**
1640 * Returns HTML for the "hidden categories on this page" list.
1641 *
1642 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1643 * or similar
1644 * @return string HTML output
1645 */
1646 public function formatHiddenCategories( $hiddencats ) {
1647 global $wgLang;
1648 wfProfileIn( __METHOD__ );
1649
1650 $outText = '';
1651 if ( count( $hiddencats ) > 0 ) {
1652 # Construct the HTML
1653 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1654 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1655 $outText .= "</div><ul>\n";
1656
1657 foreach ( $hiddencats as $titleObj ) {
1658 $outText .= '<li>' . $this->link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1659 }
1660 $outText .= '</ul>';
1661 }
1662 wfProfileOut( __METHOD__ );
1663 return $outText;
1664 }
1665
1666 /**
1667 * Format a size in bytes for output, using an appropriate
1668 * unit (B, KB, MB or GB) according to the magnitude in question
1669 *
1670 * @param $size Size to format
1671 * @return string
1672 */
1673 public function formatSize( $size ) {
1674 global $wgLang;
1675 return htmlspecialchars( $wgLang->formatSize( $size ) );
1676 }
1677
1678 /**
1679 * Given the id of an interface element, constructs the appropriate title
1680 * attribute from the system messages. (Note, this is usually the id but
1681 * isn't always, because sometimes the accesskey needs to go on a different
1682 * element than the id, for reverse-compatibility, etc.)
1683 *
1684 * @param string $name Id of the element, minus prefixes.
1685 * @param mixed $options null or the string 'withaccess' to add an access-
1686 * key hint
1687 * @return string Contents of the title attribute (which you must HTML-
1688 * escape), or false for no title attribute
1689 */
1690 public function titleAttrib( $name, $options = null ) {
1691 wfProfileIn( __METHOD__ );
1692
1693 $tooltip = wfMsg( "tooltip-$name" );
1694 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1695 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1696
1697 # Message equal to '-' means suppress it.
1698 if ( wfEmptyMsg( "tooltip-$name", $tooltip ) || $tooltip == '-' ) {
1699 $tooltip = false;
1700 }
1701
1702 if ( $options == 'withaccess' ) {
1703 $accesskey = $this->accesskey( $name );
1704 if( $accesskey !== false ) {
1705 if ( $tooltip === false || $tooltip === '' ) {
1706 $tooltip = "[$accesskey]";
1707 } else {
1708 $tooltip .= " [$accesskey]";
1709 }
1710 }
1711 }
1712
1713 wfProfileOut( __METHOD__ );
1714 return $tooltip;
1715 }
1716
1717 /**
1718 * Given the id of an interface element, constructs the appropriate
1719 * accesskey attribute from the system messages. (Note, this is usually
1720 * the id but isn't always, because sometimes the accesskey needs to go on
1721 * a different element than the id, for reverse-compatibility, etc.)
1722 *
1723 * @param string $name Id of the element, minus prefixes.
1724 * @return string Contents of the accesskey attribute (which you must HTML-
1725 * escape), or false for no accesskey attribute
1726 */
1727 public function accesskey( $name ) {
1728 wfProfileIn( __METHOD__ );
1729
1730 $accesskey = wfMsg( "accesskey-$name" );
1731
1732 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1733 # attribute, but this is broken for accesskey: that might be a useful
1734 # value.
1735 if( $accesskey != '' && $accesskey != '-' && !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1736 wfProfileOut( __METHOD__ );
1737 return $accesskey;
1738 }
1739
1740 wfProfileOut( __METHOD__ );
1741 return false;
1742 }
1743
1744 /**
1745 * Creates a (show/hide) link for deleting revisions/log entries
1746 *
1747 * @param array $query Query parameters to be passed to link()
1748 * @param bool $restricted Set to true to use a <strong> instead of a <span>
1749 * @param bool $delete Set to true to use (show/hide) rather than (show)
1750 *
1751 * @return string HTML <a> link to Special:Revisiondelete, wrapped in a
1752 * span to allow for customization of appearance with CSS
1753 */
1754 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1755 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1756 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1757 $tag = $restricted ? 'strong' : 'span';
1758 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1759 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1760 }
1761
1762 /**
1763 * Creates a dead (show/hide) link for deleting revisions/log entries
1764 *
1765 * @param bool $delete Set to true to use (show/hide) rather than (show)
1766 *
1767 * @return string HTML text wrapped in a span to allow for customization
1768 * of appearance with CSS
1769 */
1770 public function revDeleteLinkDisabled( $delete = true ) {
1771 $text = $delete ? wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1772 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1773 }
1774
1775 /* Deprecated methods */
1776
1777 /**
1778 * @deprecated
1779 */
1780 function postParseLinkColour( $s = null ) {
1781 wfDeprecated( __METHOD__ );
1782 return null;
1783 }
1784
1785
1786 /**
1787 * @deprecated Use link()
1788 *
1789 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1790 * it if you already have a title object handy. See makeLinkObj for further documentation.
1791 *
1792 * @param $title String: the text of the title
1793 * @param $text String: link text
1794 * @param $query String: optional query part
1795 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1796 * be included in the link text. Other characters will be appended after
1797 * the end of the link.
1798 */
1799 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1800 wfProfileIn( __METHOD__ );
1801 $nt = Title::newFromText( $title );
1802 if ( $nt instanceof Title ) {
1803 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1804 } else {
1805 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
1806 $result = $text == "" ? $title : $text;
1807 }
1808
1809 wfProfileOut( __METHOD__ );
1810 return $result;
1811 }
1812
1813 /**
1814 * @deprecated Use link()
1815 *
1816 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1817 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1818 *
1819 * @param $title String: the text of the title
1820 * @param $text String: link text
1821 * @param $query String: optional query part
1822 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1823 * be included in the link text. Other characters will be appended after
1824 * the end of the link.
1825 */
1826 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
1827 $nt = Title::newFromText( $title );
1828 if ( $nt instanceof Title ) {
1829 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1830 } else {
1831 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
1832 return $text == '' ? $title : $text;
1833 }
1834 }
1835
1836 /**
1837 * @deprecated Use link()
1838 *
1839 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1840 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1841 *
1842 * @param string $title The text of the title
1843 * @param string $text Link text
1844 * @param string $query Optional query part
1845 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
1846 * be included in the link text. Other characters will be appended after
1847 * the end of the link.
1848 */
1849 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1850 $nt = Title::newFromText( $title );
1851 if ( $nt instanceof Title ) {
1852 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1853 } else {
1854 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
1855 return $text == '' ? $title : $text;
1856 }
1857 }
1858
1859 /**
1860 * @deprecated Use link()
1861 *
1862 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1863 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1864 *
1865 * @param $title String: the text of the title
1866 * @param $text String: link text
1867 * @param $query String: optional query part
1868 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1869 * be included in the link text. Other characters will be appended after
1870 * the end of the link.
1871 */
1872 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1873 wfDeprecated( __METHOD__ );
1874 $nt = Title::newFromText( $title );
1875 if ( $nt instanceof Title ) {
1876 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1877 } else {
1878 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
1879 return $text == '' ? $title : $text;
1880 }
1881 }
1882
1883 /**
1884 * @deprecated Use link()
1885 *
1886 * Make a link for a title which may or may not be in the database. If you need to
1887 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1888 * call to this will result in a DB query.
1889 *
1890 * @param $nt Title: the title object to make the link from, e.g. from
1891 * Title::newFromText.
1892 * @param $text String: link text
1893 * @param $query String: optional query part
1894 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1895 * be included in the link text. Other characters will be appended after
1896 * the end of the link.
1897 * @param $prefix String: optional prefix. As trail, only before instead of after.
1898 */
1899 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
1900 wfProfileIn( __METHOD__ );
1901
1902 $query = wfCgiToArray( $query );
1903 list( $inside, $trail ) = Linker::splitTrail( $trail );
1904 if( $text === '' ) {
1905 $text = $this->linkText( $nt );
1906 }
1907
1908 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1909
1910 wfProfileOut( __METHOD__ );
1911 return $ret;
1912 }
1913
1914 /**
1915 * @deprecated Use link()
1916 *
1917 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1918 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1919 * pages.
1920 *
1921 * @param $nt Title object of target page
1922 * @param $text String: text to replace the title
1923 * @param $query String: link target
1924 * @param $trail String: text after link
1925 * @param $prefix String: text before link text
1926 * @param $aprops String: extra attributes to the a-element
1927 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1928 * @return the a-element
1929 */
1930 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1931 wfProfileIn( __METHOD__ );
1932
1933 if ( $text == '' ) {
1934 $text = $this->linkText( $title );
1935 }
1936 $attribs = Sanitizer::mergeAttributes(
1937 Sanitizer::decodeTagAttributes( $aprops ),
1938 Sanitizer::decodeTagAttributes( $style )
1939 );
1940 $query = wfCgiToArray( $query );
1941 list( $inside, $trail ) = Linker::splitTrail( $trail );
1942
1943 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1944 array( 'known', 'noclasses' ) ) . $trail;
1945
1946 wfProfileOut( __METHOD__ );
1947 return $ret;
1948 }
1949
1950 /**
1951 * @deprecated Use link()
1952 *
1953 * Make a red link to the edit page of a given title.
1954 *
1955 * @param $nt Title object of the target page
1956 * @param $text String: Link text
1957 * @param $query String: Optional query part
1958 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1959 * be included in the link text. Other characters will be appended after
1960 * the end of the link.
1961 */
1962 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1963 wfProfileIn( __METHOD__ );
1964
1965 list( $inside, $trail ) = Linker::splitTrail( $trail );
1966 if( $text === '' ) {
1967 $text = $this->linkText( $title );
1968 }
1969 $nt = $this->normaliseSpecialPage( $title );
1970
1971 $ret = $this->link( $title, "$prefix$text$inside", array(),
1972 wfCgiToArray( $query ), 'broken' ) . $trail;
1973
1974 wfProfileOut( __METHOD__ );
1975 return $ret;
1976 }
1977
1978 /**
1979 * @deprecated Use link()
1980 *
1981 * Make a brown link to a short article.
1982 *
1983 * @param $nt Title object of the target page
1984 * @param $text String: link text
1985 * @param $query String: optional query part
1986 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1987 * be included in the link text. Other characters will be appended after
1988 * the end of the link.
1989 */
1990 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1991 wfDeprecated( __METHOD__ );
1992 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1993 }
1994
1995 /**
1996 * @deprecated Use link()
1997 *
1998 * Make a coloured link.
1999 *
2000 * @param $nt Title object of the target page
2001 * @param $colour Integer: colour of the link
2002 * @param $text String: link text
2003 * @param $query String: optional query part
2004 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2005 * be included in the link text. Other characters will be appended after
2006 * the end of the link.
2007 */
2008 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2009 if($colour != ''){
2010 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
2011 } else $style = '';
2012 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2013 }
2014
2015 /** Obsolete alias */
2016 function makeImage( $url, $alt = '' ) {
2017 wfDeprecated( __METHOD__ );
2018 return $this->makeExternalImage( $url, $alt );
2019 }
2020
2021 /**
2022 * Creates the HTML source for images
2023 * @deprecated use makeImageLink2
2024 *
2025 * @param object $title
2026 * @param string $label label text
2027 * @param string $alt alt text
2028 * @param string $align horizontal alignment: none, left, center, right)
2029 * @param array $handlerParams Parameters to be passed to the media handler
2030 * @param boolean $framed shows image in original size in a frame
2031 * @param boolean $thumb shows image as thumbnail in a frame
2032 * @param string $manualthumb image name for the manual thumbnail
2033 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
2034 * @param string $time, timestamp of the file, set as false for current
2035 * @return string
2036 */
2037 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
2038 $thumb = false, $manualthumb = '', $valign = '', $time = false )
2039 {
2040 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2041 if ( $align ) {
2042 $frameParams['align'] = $align;
2043 }
2044 if ( $framed ) {
2045 $frameParams['framed'] = true;
2046 }
2047 if ( $thumb ) {
2048 $frameParams['thumbnail'] = true;
2049 }
2050 if ( $manualthumb ) {
2051 $frameParams['manualthumb'] = $manualthumb;
2052 }
2053 if ( $valign ) {
2054 $frameParams['valign'] = $valign;
2055 }
2056 $file = wfFindFile( $title, array( 'time' => $time ) );
2057 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2058 }
2059
2060 /** @deprecated use Linker::makeMediaLinkObj() */
2061 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2062 $nt = Title::makeTitleSafe( NS_FILE, $name );
2063 return $this->makeMediaLinkObj( $nt, $text, $time );
2064 }
2065
2066 /**
2067 * Used to generate section edit links that point to "other" pages
2068 * (sections that are really part of included pages).
2069 *
2070 * @deprecated use Linker::doEditSectionLink()
2071 * @param $title Title string.
2072 * @param $section Integer: section number.
2073 */
2074 public function editSectionLinkForOther( $title, $section ) {
2075 wfDeprecated( __METHOD__ );
2076 $title = Title::newFromText( $title );
2077 return $this->doEditSectionLink( $title, $section );
2078 }
2079
2080 /**
2081 * @deprecated use Linker::doEditSectionLink()
2082 * @param $nt Title object.
2083 * @param $section Integer: section number.
2084 * @param $hint Link String: title, or default if omitted or empty
2085 */
2086 public function editSectionLink( Title $nt, $section, $hint = '' ) {
2087 wfDeprecated( __METHOD__ );
2088 if( $hint === '' ) {
2089 # No way to pass an actual empty $hint here! The new interface al-
2090 # lows this, so we have to do this for compatibility.
2091 $hint = null;
2092 }
2093 return $this->doEditSectionLink( $nt, $section, $hint );
2094 }
2095
2096 /**
2097 * Returns the attributes for the tooltip and access key
2098 */
2099 public function tooltipAndAccesskeyAttribs( $name ) {
2100 global $wgEnableTooltipsAndAccesskeys;
2101 if ( !$wgEnableTooltipsAndAccesskeys )
2102 return array();
2103 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2104 # no attribute" instead of "output '' as value for attribute", this
2105 # would be three lines.
2106 $attribs = array(
2107 'title' => $this->titleAttrib( $name, 'withaccess' ),
2108 'accesskey' => $this->accesskey( $name )
2109 );
2110 if ( $attribs['title'] === false ) {
2111 unset( $attribs['title'] );
2112 }
2113 if ( $attribs['accesskey'] === false ) {
2114 unset( $attribs['accesskey'] );
2115 }
2116 return $attribs;
2117 }
2118 /**
2119 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
2120 */
2121 public function tooltipAndAccesskey( $name ) {
2122 return Xml::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2123 }
2124
2125
2126 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
2127 public function tooltip( $name, $options = null ) {
2128 global $wgEnableTooltipsAndAccesskeys;
2129 if ( !$wgEnableTooltipsAndAccesskeys )
2130 return '';
2131 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2132 # no attribute" instead of "output '' as value for attribute", this
2133 # would be two lines.
2134 $tooltip = $this->titleAttrib( $name, $options );
2135 if ( $tooltip === false ) {
2136 return '';
2137 }
2138 return Xml::expandAttributes( array(
2139 'title' => $this->titleAttrib( $name, $options )
2140 ) );
2141 }
2142 }