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