MediaWiki REL1_34
Linker.php
Go to the documentation of this file.
1<?php
25
35class Linker {
41
85 public static function link(
86 $target, $html = null, $customAttribs = [], $query = [], $options = []
87 ) {
88 if ( !$target instanceof LinkTarget ) {
89 wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget object.', 2 );
90 return "<!-- ERROR -->$html";
91 }
92
93 $services = MediaWikiServices::getInstance();
94 $options = (array)$options;
95 if ( $options ) {
96 // Custom options, create new LinkRenderer
97 if ( !isset( $options['stubThreshold'] ) ) {
98 $defaultLinkRenderer = $services->getLinkRenderer();
99 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
100 }
101 $linkRenderer = $services->getLinkRendererFactory()
102 ->createFromLegacyOptions( $options );
103 } else {
104 $linkRenderer = $services->getLinkRenderer();
105 }
106
107 if ( $html !== null ) {
108 $text = new HtmlArmor( $html );
109 } else {
110 $text = null;
111 }
112
113 if ( in_array( 'known', $options, true ) ) {
114 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
115 }
116
117 if ( in_array( 'broken', $options, true ) ) {
118 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
119 }
120
121 if ( in_array( 'noclasses', $options, true ) ) {
122 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
123 }
124
125 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
126 }
127
141 public static function linkKnown(
142 $target, $html = null, $customAttribs = [],
143 $query = [], $options = [ 'known' ]
144 ) {
145 return self::link( $target, $html, $customAttribs, $query, $options );
146 }
147
163 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
164 $nt = Title::newFromLinkTarget( $nt );
165 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
166 if ( !Hooks::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
167 return $ret;
168 }
169
170 if ( $html == '' ) {
171 $html = htmlspecialchars( $nt->getPrefixedText() );
172 }
173 list( $inside, $trail ) = self::splitTrail( $trail );
174 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
175 }
176
187 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
188 // First we check whether the namespace exists or not.
189 if ( MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
190 if ( $namespace == NS_MAIN ) {
191 $name = $context->msg( 'blanknamespace' )->text();
192 } else {
193 $name = MediaWikiServices::getInstance()->getContentLanguage()->
194 getFormattedNsText( $namespace );
195 }
196 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
197 }
198
199 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
200 }
201
207 public static function normaliseSpecialPage( LinkTarget $target ) {
208 if ( $target->getNamespace() == NS_SPECIAL && !$target->isExternal() ) {
209 list( $name, $subpage ) = MediaWikiServices::getInstance()->getSpecialPageFactory()->
210 resolveAlias( $target->getDBkey() );
211 if ( $name ) {
212 return SpecialPage::getTitleValueFor( $name, $subpage, $target->getFragment() );
213 }
214 }
215
216 return $target;
217 }
218
227 private static function fnamePart( $url ) {
228 $basename = strrchr( $url, '/' );
229 if ( $basename === false ) {
230 $basename = $url;
231 } else {
232 $basename = substr( $basename, 1 );
233 }
234 return $basename;
235 }
236
247 public static function makeExternalImage( $url, $alt = '' ) {
248 if ( $alt == '' ) {
249 $alt = self::fnamePart( $url );
250 }
251 $img = '';
252 $success = Hooks::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
253 if ( !$success ) {
254 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
255 . "with url {$url} and alt text {$alt} to {$img}\n", true );
256 return $img;
257 }
258 return Html::element( 'img',
259 [
260 'src' => $url,
261 'alt' => $alt
262 ]
263 );
264 }
265
303 public static function makeImageLink( Parser $parser, LinkTarget $title,
304 $file, $frameParams = [], $handlerParams = [], $time = false,
305 $query = "", $widthOption = null
306 ) {
307 $title = Title::newFromLinkTarget( $title );
308 $res = null;
309 $dummy = new DummyLinker;
310 if ( !Hooks::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
311 &$file, &$frameParams, &$handlerParams, &$time, &$res,
312 $parser, &$query, &$widthOption
313 ] ) ) {
314 return $res;
315 }
316
317 if ( $file && !$file->allowInlineDisplay() ) {
318 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
319 return self::link( $title );
320 }
321
322 // Clean up parameters
323 $page = $handlerParams['page'] ?? false;
324 if ( !isset( $frameParams['align'] ) ) {
325 $frameParams['align'] = '';
326 }
327 if ( !isset( $frameParams['alt'] ) ) {
328 $frameParams['alt'] = '';
329 }
330 if ( !isset( $frameParams['title'] ) ) {
331 $frameParams['title'] = '';
332 }
333 if ( !isset( $frameParams['class'] ) ) {
334 $frameParams['class'] = '';
335 }
336
337 $prefix = $postfix = '';
338
339 if ( $frameParams['align'] == 'center' ) {
340 $prefix = '<div class="center">';
341 $postfix = '</div>';
342 $frameParams['align'] = 'none';
343 }
344 if ( $file && !isset( $handlerParams['width'] ) ) {
345 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
346 // If its a vector image, and user only specifies height
347 // we don't want it to be limited by its "normal" width.
348 global $wgSVGMaxSize;
349 $handlerParams['width'] = $wgSVGMaxSize;
350 } else {
351 $handlerParams['width'] = $file->getWidth( $page );
352 }
353
354 if ( isset( $frameParams['thumbnail'] )
355 || isset( $frameParams['manualthumb'] )
356 || isset( $frameParams['framed'] )
357 || isset( $frameParams['frameless'] )
358 || !$handlerParams['width']
359 ) {
361
362 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
363 $widthOption = User::getDefaultOption( 'thumbsize' );
364 }
365
366 // Reduce width for upright images when parameter 'upright' is used
367 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
368 $frameParams['upright'] = $wgThumbUpright;
369 }
370
371 // For caching health: If width scaled down due to upright
372 // parameter, round to full __0 pixel to avoid the creation of a
373 // lot of odd thumbs.
374 $prefWidth = isset( $frameParams['upright'] ) ?
375 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
376 $wgThumbLimits[$widthOption];
377
378 // Use width which is smaller: real image width or user preference width
379 // Unless image is scalable vector.
380 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
381 $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
382 $handlerParams['width'] = $prefWidth;
383 }
384 }
385 }
386
387 if ( isset( $frameParams['thumbnail'] ) || isset( $frameParams['manualthumb'] )
388 || isset( $frameParams['framed'] )
389 ) {
390 # Create a thumbnail. Alignment depends on the writing direction of
391 # the page content language (right-aligned for LTR languages,
392 # left-aligned for RTL languages)
393 # If a thumbnail width has not been provided, it is set
394 # to the default user option as specified in Language*.php
395 if ( $frameParams['align'] == '' ) {
396 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
397 }
398 return $prefix .
399 self::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
400 $postfix;
401 }
402
403 if ( $file && isset( $frameParams['frameless'] ) ) {
404 $srcWidth = $file->getWidth( $page );
405 # For "frameless" option: do not present an image bigger than the
406 # source (for bitmap-style images). This is the same behavior as the
407 # "thumb" option does it already.
408 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
409 $handlerParams['width'] = $srcWidth;
410 }
411 }
412
413 if ( $file && isset( $handlerParams['width'] ) ) {
414 # Create a resized image, without the additional thumbnail features
415 $thumb = $file->transform( $handlerParams );
416 } else {
417 $thumb = false;
418 }
419
420 if ( !$thumb ) {
421 $s = self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
422 } else {
423 self::processResponsiveImages( $file, $thumb, $handlerParams );
424 $params = [
425 'alt' => $frameParams['alt'],
426 'title' => $frameParams['title'],
427 'valign' => $frameParams['valign'] ?? false,
428 'img-class' => $frameParams['class'] ];
429 if ( isset( $frameParams['border'] ) ) {
430 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
431 }
432 $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
433
434 $s = $thumb->toHtml( $params );
435 }
436 if ( $frameParams['align'] != '' ) {
437 $s = Html::rawElement(
438 'div',
439 [ 'class' => 'float' . $frameParams['align'] ],
440 $s
441 );
442 }
443 return str_replace( "\n", ' ', $prefix . $s . $postfix );
444 }
445
454 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
455 $mtoParams = [];
456 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
457 $mtoParams['custom-url-link'] = $frameParams['link-url'];
458 if ( isset( $frameParams['link-target'] ) ) {
459 $mtoParams['custom-target-link'] = $frameParams['link-target'];
460 }
461 if ( $parser ) {
462 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
463 foreach ( $extLinkAttrs as $name => $val ) {
464 // Currently could include 'rel' and 'target'
465 $mtoParams['parser-extlink-' . $name] = $val;
466 }
467 }
468 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
469 $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
470 self::normaliseSpecialPage( $frameParams['link-title'] )
471 );
472 } elseif ( !empty( $frameParams['no-link'] ) ) {
473 // No link
474 } else {
475 $mtoParams['desc-link'] = true;
476 $mtoParams['desc-query'] = $query;
477 }
478 return $mtoParams;
479 }
480
493 public static function makeThumbLinkObj( LinkTarget $title, $file, $label = '', $alt = '',
494 $align = 'right', $params = [], $framed = false, $manualthumb = ""
495 ) {
496 $frameParams = [
497 'alt' => $alt,
498 'caption' => $label,
499 'align' => $align
500 ];
501 if ( $framed ) {
502 $frameParams['framed'] = true;
503 }
504 if ( $manualthumb ) {
505 $frameParams['manualthumb'] = $manualthumb;
506 }
507 return self::makeThumbLink2( $title, $file, $frameParams, $params );
508 }
509
519 public static function makeThumbLink2( LinkTarget $title, $file, $frameParams = [],
520 $handlerParams = [], $time = false, $query = ""
521 ) {
522 $exists = $file && $file->exists();
523
524 $page = $handlerParams['page'] ?? false;
525 if ( !isset( $frameParams['align'] ) ) {
526 $frameParams['align'] = 'right';
527 }
528 if ( !isset( $frameParams['alt'] ) ) {
529 $frameParams['alt'] = '';
530 }
531 if ( !isset( $frameParams['title'] ) ) {
532 $frameParams['title'] = '';
533 }
534 if ( !isset( $frameParams['caption'] ) ) {
535 $frameParams['caption'] = '';
536 }
537
538 if ( empty( $handlerParams['width'] ) ) {
539 // Reduce width for upright images when parameter 'upright' is used
540 $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
541 }
542 $thumb = false;
543 $noscale = false;
544 $manualthumb = false;
545
546 if ( !$exists ) {
547 $outerWidth = $handlerParams['width'] + 2;
548 } else {
549 if ( isset( $frameParams['manualthumb'] ) ) {
550 # Use manually specified thumbnail
551 $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
552 if ( $manual_title ) {
553 $manual_img = MediaWikiServices::getInstance()->getRepoGroup()
554 ->findFile( $manual_title );
555 if ( $manual_img ) {
556 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
557 $manualthumb = true;
558 } else {
559 $exists = false;
560 }
561 }
562 } elseif ( isset( $frameParams['framed'] ) ) {
563 // Use image dimensions, don't scale
564 $thumb = $file->getUnscaledThumb( $handlerParams );
565 $noscale = true;
566 } else {
567 # Do not present an image bigger than the source, for bitmap-style images
568 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
569 $srcWidth = $file->getWidth( $page );
570 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
571 $handlerParams['width'] = $srcWidth;
572 }
573 $thumb = $file->transform( $handlerParams );
574 }
575
576 if ( $thumb ) {
577 $outerWidth = $thumb->getWidth() + 2;
578 } else {
579 $outerWidth = $handlerParams['width'] + 2;
580 }
581 }
582
583 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
584 # So we don't need to pass it here in $query. However, the URL for the
585 # zoom icon still needs it, so we make a unique query for it. See T16771
586 $url = Title::newFromLinkTarget( $title )->getLocalURL( $query );
587 if ( $page ) {
588 $url = wfAppendQuery( $url, [ 'page' => $page ] );
589 }
590 if ( $manualthumb
591 && !isset( $frameParams['link-title'] )
592 && !isset( $frameParams['link-url'] )
593 && !isset( $frameParams['no-link'] ) ) {
594 $frameParams['link-url'] = $url;
595 }
596
597 $s = "<div class=\"thumb t{$frameParams['align']}\">"
598 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
599
600 if ( !$exists ) {
601 $s .= self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
602 $zoomIcon = '';
603 } elseif ( !$thumb ) {
604 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
605 $zoomIcon = '';
606 } else {
607 if ( !$noscale && !$manualthumb ) {
608 self::processResponsiveImages( $file, $thumb, $handlerParams );
609 }
610 $params = [
611 'alt' => $frameParams['alt'],
612 'title' => $frameParams['title'],
613 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
614 ? $frameParams['class'] . ' '
615 : '' ) . 'thumbimage'
616 ];
617 $params = self::getImageLinkMTOParams( $frameParams, $query ) + $params;
618 $s .= $thumb->toHtml( $params );
619 if ( isset( $frameParams['framed'] ) ) {
620 $zoomIcon = "";
621 } else {
622 $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
623 Html::rawElement( 'a', [
624 'href' => $url,
625 'class' => 'internal',
626 'title' => wfMessage( 'thumbnail-more' )->text() ],
627 "" ) );
628 }
629 }
630 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
631 return str_replace( "\n", ' ', $s );
632 }
633
642 public static function processResponsiveImages( $file, $thumb, $hp ) {
643 global $wgResponsiveImages;
644 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
645 $hp15 = $hp;
646 $hp15['width'] = round( $hp['width'] * 1.5 );
647 $hp20 = $hp;
648 $hp20['width'] = $hp['width'] * 2;
649 if ( isset( $hp['height'] ) ) {
650 $hp15['height'] = round( $hp['height'] * 1.5 );
651 $hp20['height'] = $hp['height'] * 2;
652 }
653
654 $thumb15 = $file->transform( $hp15 );
655 $thumb20 = $file->transform( $hp20 );
656 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
657 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
658 }
659 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
660 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
661 }
662 }
663 }
664
677 public static function makeBrokenImageLinkObj( $title, $label = '',
678 $query = '', $unused1 = '', $unused2 = '', $time = false
679 ) {
680 if ( !$title instanceof LinkTarget ) {
681 wfWarn( __METHOD__ . ': Requires $title to be a LinkTarget object.' );
682 return "<!-- ERROR -->" . htmlspecialchars( $label );
683 }
684
685 $title = Title::castFromLinkTarget( $title );
686
688 if ( $label == '' ) {
689 $label = $title->getPrefixedText();
690 }
691 $repoGroup = MediaWikiServices::getInstance()->getRepoGroup();
692 $currentExists = $time
693 && $repoGroup->findFile( $title ) !== false;
694
696 && !$currentExists
697 ) {
698 if ( $repoGroup->getLocalRepo()->checkRedirect( $title ) ) {
699 // We already know it's a redirect, so mark it accordingly
700 return self::link(
701 $title,
702 htmlspecialchars( $label ),
703 [ 'class' => 'mw-redirect' ],
704 wfCgiToArray( $query ),
705 [ 'known', 'noclasses' ]
706 );
707 }
708
709 return Html::element( 'a', [
710 'href' => self::getUploadUrl( $title, $query ),
711 'class' => 'new',
712 'title' => $title->getPrefixedText()
713 ], $label );
714 }
715
716 return self::link(
717 $title,
718 htmlspecialchars( $label ),
719 [],
720 wfCgiToArray( $query ),
721 [ 'known', 'noclasses' ]
722 );
723 }
724
733 protected static function getUploadUrl( $destFile, $query = '' ) {
735 $q = 'wpDestFile=' . Title::castFromLinkTarget( $destFile )->getPartialURL();
736 if ( $query != '' ) {
737 $q .= '&' . $query;
738 }
739
742 }
743
746 }
747
748 $upload = SpecialPage::getTitleFor( 'Upload' );
749
750 return $upload->getLocalURL( $q );
751 }
752
762 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
763 $img = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
764 $title, [ 'time' => $time ]
765 );
766 return self::makeMediaLinkFile( $title, $img, $html );
767 }
768
781 public static function makeMediaLinkFile( LinkTarget $title, $file, $html = '' ) {
782 if ( $file && $file->exists() ) {
783 $url = $file->getUrl();
784 $class = 'internal';
785 } else {
786 $url = self::getUploadUrl( $title );
787 $class = 'new';
788 }
789
790 $alt = $title->getText();
791 if ( $html == '' ) {
792 $html = $alt;
793 }
794
795 $ret = '';
796 $attribs = [
797 'href' => $url,
798 'class' => $class,
799 'title' => $alt
800 ];
801
802 if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
803 [ Title::castFromLinkTarget( $title ), $file, &$html, &$attribs, &$ret ] ) ) {
804 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
805 . "with url {$url} and text {$html} to {$ret}\n", true );
806 return $ret;
807 }
808
809 return Html::rawElement( 'a', $attribs, $html );
810 }
811
822 public static function specialLink( $name, $key = '' ) {
823 if ( $key == '' ) {
824 $key = strtolower( $name );
825 }
826
827 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->escaped() );
828 }
829
848 public static function makeExternalLink( $url, $text, $escape = true,
849 $linktype = '', $attribs = [], $title = null
850 ) {
851 global $wgTitle;
852 $class = "external";
853 if ( $linktype ) {
854 $class .= " $linktype";
855 }
856 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
857 $class .= " {$attribs['class']}";
858 }
859 $attribs['class'] = $class;
860
861 if ( $escape ) {
862 $text = htmlspecialchars( $text );
863 }
864
865 if ( !$title ) {
867 }
868 $newRel = Parser::getExternalLinkRel( $url, $title );
869 if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
870 $attribs['rel'] = $newRel;
871 } elseif ( $newRel !== '' ) {
872 // Merge the rel attributes.
873 $newRels = explode( ' ', $newRel );
874 $oldRels = explode( ' ', $attribs['rel'] );
875 $combined = array_unique( array_merge( $newRels, $oldRels ) );
876 $attribs['rel'] = implode( ' ', $combined );
877 }
878 $link = '';
879 $success = Hooks::run( 'LinkerMakeExternalLink',
880 [ &$url, &$text, &$link, &$attribs, $linktype ] );
881 if ( !$success ) {
882 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
883 . "with url {$url} and text {$text} to {$link}\n", true );
884 return $link;
885 }
886 $attribs['href'] = $url;
887 return Html::rawElement( 'a', $attribs, $text );
888 }
889
898 public static function userLink( $userId, $userName, $altUserName = false ) {
899 if ( $userName === '' || $userName === false || $userName === null ) {
900 wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
901 'that need to be fixed?' );
902 return wfMessage( 'empty-username' )->parse();
903 }
904
905 $classes = 'mw-userlink';
906 $page = null;
907 if ( $userId == 0 ) {
908 $page = ExternalUserNames::getUserLinkTitle( $userName );
909
910 if ( ExternalUserNames::isExternal( $userName ) ) {
911 $classes .= ' mw-extuserlink';
912 } elseif ( $altUserName === false ) {
913 $altUserName = IP::prettifyIP( $userName );
914 }
915 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
916 } else {
917 $page = new TitleValue( NS_USER, strtr( $userName, ' ', '_' ) );
918 }
919
920 // Wrap the output with <bdi> tags for directionality isolation
921 $linkText =
922 '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
923
924 return $page
925 ? self::link( $page, $linkText, [ 'class' => $classes ] )
926 : Html::rawElement( 'span', [ 'class' => $classes ], $linkText );
927 }
928
943 public static function userToolLinks(
944 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
945 $useParentheses = true
946 ) {
947 if ( $userText === '' ) {
948 wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
949 'that need to be fixed?' );
950 return ' ' . wfMessage( 'empty-username' )->parse();
951 }
952
953 global $wgUser, $wgDisableAnonTalk, $wgLang;
954 $talkable = !( $wgDisableAnonTalk && $userId == 0 );
955 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
956 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
957
958 if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
959 // No tools for an external user
960 return '';
961 }
962
963 $items = [];
964 if ( $talkable ) {
965 $items[] = self::userTalkLink( $userId, $userText );
966 }
967 if ( $userId ) {
968 // check if the user has an edit
969 $attribs = [];
970 $attribs['class'] = 'mw-usertoollinks-contribs';
971 if ( $redContribsWhenNoEdits ) {
972 if ( intval( $edits ) === 0 && $edits !== 0 ) {
973 $user = User::newFromId( $userId );
974 $edits = $user->getEditCount();
975 }
976 if ( $edits === 0 ) {
977 $attribs['class'] .= ' new';
978 }
979 }
980 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
981
982 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
983 }
984 $userCanBlock = MediaWikiServices::getInstance()->getPermissionManager()
985 ->userHasRight( $wgUser, 'block' );
986 if ( $blockable && $userCanBlock ) {
987 $items[] = self::blockLink( $userId, $userText );
988 }
989
990 if ( $addEmailLink && $wgUser->canSendEmail() ) {
991 $items[] = self::emailLink( $userId, $userText );
992 }
993
994 Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
995
996 if ( !$items ) {
997 return '';
998 }
999
1000 if ( $useParentheses ) {
1001 return wfMessage( 'word-separator' )->escaped()
1002 . '<span class="mw-usertoollinks">'
1003 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1004 . '</span>';
1005 }
1006
1007 $tools = [];
1008 foreach ( $items as $tool ) {
1009 $tools[] = Html::rawElement( 'span', [], $tool );
1010 }
1011 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1012 implode( ' ', $tools ) . '</span>';
1013 }
1014
1024 public static function userToolLinksRedContribs(
1025 $userId, $userText, $edits = null, $useParentheses = true
1026 ) {
1027 return self::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1028 }
1029
1036 public static function userTalkLink( $userId, $userText ) {
1037 if ( $userText === '' ) {
1038 wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1039 'that need to be fixed?' );
1040 return wfMessage( 'empty-username' )->parse();
1041 }
1042
1043 $userTalkPage = new TitleValue( NS_USER_TALK, strtr( $userText, ' ', '_' ) );
1044 $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-talk' ];
1045
1046 return self::link( $userTalkPage,
1047 wfMessage( 'talkpagelinktext' )->escaped(),
1048 $moreLinkAttribs
1049 );
1050 }
1051
1058 public static function blockLink( $userId, $userText ) {
1059 if ( $userText === '' ) {
1060 wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1061 'that need to be fixed?' );
1062 return wfMessage( 'empty-username' )->parse();
1063 }
1064
1065 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1066 $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-block' ];
1067
1068 return self::link( $blockPage,
1069 wfMessage( 'blocklink' )->escaped(),
1070 $moreLinkAttribs
1071 );
1072 }
1073
1079 public static function emailLink( $userId, $userText ) {
1080 if ( $userText === '' ) {
1081 wfLogWarning( __METHOD__ . ' received an empty username. Are there database errors ' .
1082 'that need to be fixed?' );
1083 return wfMessage( 'empty-username' )->parse();
1084 }
1085
1086 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1087 $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-mail' ];
1088 return self::link( $emailPage,
1089 wfMessage( 'emaillink' )->escaped(),
1090 $moreLinkAttribs
1091 );
1092 }
1093
1101 public static function revUserLink( $rev, $isPublic = false ) {
1102 if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) && $isPublic ) {
1103 $link = wfMessage( 'rev-deleted-user' )->escaped();
1104 } elseif ( $rev->userCan( RevisionRecord::DELETED_USER ) ) {
1105 $link = self::userLink( $rev->getUser( RevisionRecord::FOR_THIS_USER ),
1106 $rev->getUserText( RevisionRecord::FOR_THIS_USER ) );
1107 } else {
1108 $link = wfMessage( 'rev-deleted-user' )->escaped();
1109 }
1110 if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
1111 return '<span class="history-deleted">' . $link . '</span>';
1112 }
1113 return $link;
1114 }
1115
1124 public static function revUserTools( $rev, $isPublic = false, $useParentheses = true ) {
1125 if ( $rev->userCan( RevisionRecord::DELETED_USER ) &&
1126 ( !$rev->isDeleted( RevisionRecord::DELETED_USER ) || !$isPublic )
1127 ) {
1128 $userId = $rev->getUser( RevisionRecord::FOR_THIS_USER );
1129 $userText = $rev->getUserText( RevisionRecord::FOR_THIS_USER );
1130 if ( $userId || (string)$userText !== '' ) {
1131 $link = self::userLink( $userId, $userText )
1132 . self::userToolLinks( $userId, $userText, false, 0, null,
1133 $useParentheses );
1134 }
1135 }
1136
1137 if ( !isset( $link ) ) {
1138 $link = wfMessage( 'rev-deleted-user' )->escaped();
1139 }
1140
1141 if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
1142 return ' <span class="history-deleted mw-userlink">' . $link . '</span>';
1143 }
1144 return $link;
1145 }
1146
1165 public static function formatComment(
1166 $comment, $title = null, $local = false, $wikiId = null
1167 ) {
1168 # Sanitize text a bit:
1169 $comment = str_replace( "\n", " ", $comment );
1170 # Allow HTML entities (for T15815)
1171 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1172
1173 # Render autocomments and make links:
1174 $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1175 return self::formatLinksInComment( $comment, $title, $local, $wikiId );
1176 }
1177
1195 private static function formatAutocomments(
1196 $comment, $title = null, $local = false, $wikiId = null
1197 ) {
1198 // @todo $append here is something of a hack to preserve the status
1199 // quo. Someone who knows more about bidi and such should decide
1200 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1201 // wiki, both when autocomments exist and when they don't, and
1202 // (2) what markup will make that actually happen.
1203 $append = '';
1204 $comment = preg_replace_callback(
1205 // To detect the presence of content before or after the
1206 // auto-comment, we use capturing groups inside optional zero-width
1207 // assertions. But older versions of PCRE can't directly make
1208 // zero-width assertions optional, so wrap them in a non-capturing
1209 // group.
1210 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1211 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1212 global $wgLang;
1213
1214 // Ensure all match positions are defined
1215 $match += [ '', '', '', '' ];
1216
1217 $pre = $match[1] !== '';
1218 $auto = $match[2];
1219 $post = $match[3] !== '';
1220 $comment = null;
1221
1222 Hooks::run(
1223 'FormatAutocomments',
1224 [ &$comment, $pre, $auto, $post, Title::castFromLinkTarget( $title ), $local,
1225 $wikiId ]
1226 );
1227
1228 if ( $comment === null ) {
1229 if ( $title ) {
1230 $section = $auto;
1231 # Remove links that a user may have manually put in the autosummary
1232 # This could be improved by copying as much of Parser::stripSectionName as desired.
1233 $section = str_replace( [
1234 '[[:',
1235 '[[',
1236 ']]'
1237 ], '', $section );
1238
1239 // We don't want any links in the auto text to be linked, but we still
1240 // want to show any [[ ]]
1241 $sectionText = str_replace( '[[', '&#91;[', $auto );
1242
1243 $section = substr( Parser::guessSectionNameFromStrippedText( $section ), 1 );
1244 // Support: HHVM (T222857)
1245 // The guessSectionNameFromStrippedText method returns a non-empty string
1246 // that starts with "#". Before PHP 7 (and still on HHVM) substr() would
1247 // return false if the start offset is the end of the string.
1248 // On PHP 7+, it gracefully returns empty string instead.
1249 if ( $section !== '' && $section !== false ) {
1250 if ( $local ) {
1251 $sectionTitle = new TitleValue( NS_MAIN, '', $section );
1252 } else {
1253 $sectionTitle = $title->createFragmentTarget( $section );
1254 }
1256 $sectionTitle,
1257 $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1258 $wikiId,
1259 'noclasses'
1260 );
1261 }
1262 }
1263 if ( $pre ) {
1264 # written summary $presep autocomment (summary /* section */)
1265 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1266 }
1267 if ( $post ) {
1268 # autocomment $postsep written summary (/* section */ summary)
1269 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1270 }
1271 if ( $auto ) {
1272 $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1273 $append .= '</span>';
1274 }
1275 $comment = $pre . $auto;
1276 }
1277 return $comment;
1278 },
1279 $comment
1280 );
1281 return $comment . $append;
1282 }
1283
1303 public static function formatLinksInComment(
1304 $comment, $title = null, $local = false, $wikiId = null
1305 ) {
1306 return preg_replace_callback(
1307 '/
1308 \[\[
1309 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1310 :? # ignore optional leading colon
1311 ([^\]|]+) # 1. link target; page names cannot include ] or |
1312 (?:\|
1313 # 2. link text
1314 # Stop matching at ]] without relying on backtracking.
1315 ((?:]?[^\]])*+)
1316 )?
1317 \]\]
1318 ([^[]*) # 3. link trail (the text up until the next link)
1319 /x',
1320 function ( $match ) use ( $title, $local, $wikiId ) {
1321 $services = MediaWikiServices::getInstance();
1322
1323 $medians = '(?:';
1324 $medians .= preg_quote(
1325 $services->getNamespaceInfo()->getCanonicalName( NS_MEDIA ), '/' );
1326 $medians .= '|';
1327 $medians .= preg_quote(
1328 $services->getContentLanguage()->getNsText( NS_MEDIA ),
1329 '/'
1330 ) . '):';
1331
1332 $comment = $match[0];
1333
1334 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1335 if ( strpos( $match[1], '%' ) !== false ) {
1336 $match[1] = strtr(
1337 rawurldecode( $match[1] ),
1338 [ '<' => '&lt;', '>' => '&gt;' ]
1339 );
1340 }
1341
1342 # Handle link renaming [[foo|text]] will show link as "text"
1343 if ( $match[2] != "" ) {
1344 $text = $match[2];
1345 } else {
1346 $text = $match[1];
1347 }
1348 $submatch = [];
1349 $thelink = null;
1350 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1351 # Media link; trail not supported.
1352 $linkRegexp = '/\[\[(.*?)\]\]/';
1353 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1354 if ( $title ) {
1355 $thelink = Linker::makeMediaLinkObj( $title, $text );
1356 }
1357 } else {
1358 # Other kind of link
1359 # Make sure its target is non-empty
1360 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1361 $match[1] = substr( $match[1], 1 );
1362 }
1363 if ( $match[1] !== false && $match[1] !== '' ) {
1364 if ( preg_match(
1365 $services->getContentLanguage()->linkTrail(),
1366 $match[3],
1367 $submatch
1368 ) ) {
1369 $trail = $submatch[1];
1370 } else {
1371 $trail = "";
1372 }
1373 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1374 list( $inside, $trail ) = Linker::splitTrail( $trail );
1375
1376 $linkText = $text;
1377 $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1378
1379 Title::newFromText( $linkTarget );
1380 try {
1381 $target = $services->getTitleParser()->
1382 parseTitle( $linkTarget );
1383
1384 if ( $target->getText() == '' && !$target->isExternal()
1385 && !$local && $title
1386 ) {
1387 $target = $title->createFragmentTarget( $target->getFragment() );
1388 }
1389
1390 $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1391 } catch ( MalformedTitleException $e ) {
1392 // Fall through
1393 }
1394 }
1395 }
1396 if ( $thelink ) {
1397 // If the link is still valid, go ahead and replace it in!
1398 $comment = preg_replace(
1399 $linkRegexp,
1401 $comment,
1402 1
1403 );
1404 }
1405
1406 return $comment;
1407 },
1408 $comment
1409 );
1410 }
1411
1425 public static function makeCommentLink(
1426 LinkTarget $linkTarget, $text, $wikiId = null, $options = []
1427 ) {
1428 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1429 $link = self::makeExternalLink(
1430 WikiMap::getForeignURL(
1431 $wikiId,
1432 $linkTarget->getNamespace() === 0
1433 ? $linkTarget->getDBkey()
1434 : MediaWikiServices::getInstance()->getNamespaceInfo()->
1435 getCanonicalName( $linkTarget->getNamespace() ) .
1436 ':' . $linkTarget->getDBkey(),
1437 $linkTarget->getFragment()
1438 ),
1439 $text,
1440 /* escape = */ false // Already escaped
1441 );
1442 } else {
1443 $link = self::link( $linkTarget, $text, [], [], $options );
1444 }
1445
1446 return $link;
1447 }
1448
1455 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1456 # Valid link forms:
1457 # Foobar -- normal
1458 # :Foobar -- override special treatment of prefix (images, language links)
1459 # /Foobar -- convert to CurrentPage/Foobar
1460 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1461 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1462 # ../Foobar -- convert to CurrentPage/Foobar,
1463 # (from CurrentPage/CurrentSubPage)
1464 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1465 # (from CurrentPage/CurrentSubPage)
1466
1467 $ret = $target; # default return value is no change
1468
1469 # Some namespaces don't allow subpages,
1470 # so only perform processing if subpages are allowed
1471 if (
1472 $contextTitle && MediaWikiServices::getInstance()->getNamespaceInfo()->
1473 hasSubpages( $contextTitle->getNamespace() )
1474 ) {
1475 $hash = strpos( $target, '#' );
1476 if ( $hash !== false ) {
1477 $suffix = substr( $target, $hash );
1478 $target = substr( $target, 0, $hash );
1479 } else {
1480 $suffix = '';
1481 }
1482 # T9425
1483 $target = trim( $target );
1484 $contextPrefixedText = MediaWikiServices::getInstance()->getTitleFormatter()->
1485 getPrefixedText( $contextTitle );
1486 # Look at the first character
1487 if ( $target != '' && $target[0] === '/' ) {
1488 # / at end means we don't want the slash to be shown
1489 $m = [];
1490 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1491 if ( $trailingSlashes ) {
1492 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1493 } else {
1494 $noslash = substr( $target, 1 );
1495 }
1496
1497 $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1498 if ( $text === '' ) {
1499 $text = $target . $suffix;
1500 } # this might be changed for ugliness reasons
1501 } else {
1502 # check for .. subpage backlinks
1503 $dotdotcount = 0;
1504 $nodotdot = $target;
1505 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1506 ++$dotdotcount;
1507 $nodotdot = substr( $nodotdot, 3 );
1508 }
1509 if ( $dotdotcount > 0 ) {
1510 $exploded = explode( '/', $contextPrefixedText );
1511 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1512 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1513 # / at the end means don't show full path
1514 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1515 $nodotdot = rtrim( $nodotdot, '/' );
1516 if ( $text === '' ) {
1517 $text = $nodotdot . $suffix;
1518 }
1519 }
1520 $nodotdot = trim( $nodotdot );
1521 if ( $nodotdot != '' ) {
1522 $ret .= '/' . $nodotdot;
1523 }
1524 $ret .= $suffix;
1525 }
1526 }
1527 }
1528 }
1529
1530 return $ret;
1531 }
1532
1547 public static function commentBlock(
1548 $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1549 ) {
1550 // '*' used to be the comment inserted by the software way back
1551 // in antiquity in case none was provided, here for backwards
1552 // compatibility, acc. to brion -ævar
1553 if ( $comment == '' || $comment == '*' ) {
1554 return '';
1555 }
1556 $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1557 if ( $useParentheses ) {
1558 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1559 $classNames = 'comment';
1560 } else {
1561 $classNames = 'comment comment--without-parentheses';
1562 }
1563 return " <span class=\"$classNames\">$formatted</span>";
1564 }
1565
1577 public static function revComment( Revision $rev, $local = false, $isPublic = false,
1578 $useParentheses = true
1579 ) {
1580 if ( $rev->getComment( RevisionRecord::RAW ) == "" ) {
1581 return "";
1582 }
1583 if ( $rev->isDeleted( RevisionRecord::DELETED_COMMENT ) && $isPublic ) {
1584 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1585 } elseif ( $rev->userCan( RevisionRecord::DELETED_COMMENT ) ) {
1586 $block = self::commentBlock( $rev->getComment( RevisionRecord::FOR_THIS_USER ),
1587 $rev->getTitle(), $local, null, $useParentheses );
1588 } else {
1589 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1590 }
1591 if ( $rev->isDeleted( RevisionRecord::DELETED_COMMENT ) ) {
1592 return " <span class=\"history-deleted comment\">$block</span>";
1593 }
1594 return $block;
1595 }
1596
1602 public static function formatRevisionSize( $size ) {
1603 if ( $size == 0 ) {
1604 $stxt = wfMessage( 'historyempty' )->escaped();
1605 } else {
1606 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1607 }
1608 return "<span class=\"history-size mw-diff-bytes\">$stxt</span>";
1609 }
1610
1617 public static function tocIndent() {
1618 return "\n<ul>\n";
1619 }
1620
1628 public static function tocUnindent( $level ) {
1629 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1630 }
1631
1643 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1644 $classes = "toclevel-$level";
1645 if ( $sectionIndex !== false ) {
1646 $classes .= " tocsection-$sectionIndex";
1647 }
1648
1649 // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1650 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1651 return Html::openElement( 'li', [ 'class' => $classes ] )
1652 . Html::rawElement( 'a',
1653 [ 'href' => "#$anchor" ],
1654 Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1655 . ' '
1656 . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1657 );
1658 }
1659
1667 public static function tocLineEnd() {
1668 return "</li>\n";
1669 }
1670
1679 public static function tocList( $toc, Language $lang = null ) {
1680 $lang = $lang ?? RequestContext::getMain()->getLanguage();
1681
1682 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1683
1684 return '<div id="toc" class="toc">'
1685 . Html::element( 'input', [
1686 'type' => 'checkbox',
1687 'role' => 'button',
1688 'id' => 'toctogglecheckbox',
1689 'class' => 'toctogglecheckbox',
1690 'style' => 'display:none',
1691 ] )
1692 . Html::openElement( 'div', [
1693 'class' => 'toctitle',
1694 'lang' => $lang->getHtmlCode(),
1695 'dir' => $lang->getDir(),
1696 ] )
1697 . "<h2>$title</h2>"
1698 . '<span class="toctogglespan">'
1699 . Html::label( '', 'toctogglecheckbox', [
1700 'class' => 'toctogglelabel',
1701 ] )
1702 . '</span>'
1703 . "</div>\n"
1704 . $toc
1705 . "</ul>\n</div>\n";
1706 }
1707
1716 public static function generateTOC( $tree, Language $lang = null ) {
1717 $toc = '';
1718 $lastLevel = 0;
1719 foreach ( $tree as $section ) {
1720 if ( $section['toclevel'] > $lastLevel ) {
1721 $toc .= self::tocIndent();
1722 } elseif ( $section['toclevel'] < $lastLevel ) {
1723 $toc .= self::tocUnindent(
1724 $lastLevel - $section['toclevel'] );
1725 } else {
1726 $toc .= self::tocLineEnd();
1727 }
1728
1729 $toc .= self::tocLine( $section['anchor'],
1730 $section['line'], $section['number'],
1731 $section['toclevel'], $section['index'] );
1732 $lastLevel = $section['toclevel'];
1733 }
1734 $toc .= self::tocLineEnd();
1735 return self::tocList( $toc, $lang );
1736 }
1737
1754 public static function makeHeadline( $level, $attribs, $anchor, $html,
1755 $link, $fallbackAnchor = false
1756 ) {
1757 $anchorEscaped = htmlspecialchars( $anchor );
1758 $fallback = '';
1759 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1760 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1761 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1762 }
1763 return "<h$level$attribs"
1764 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1765 . $link
1766 . "</h$level>";
1767 }
1768
1775 static function splitTrail( $trail ) {
1776 $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail();
1777 $inside = '';
1778 if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1779 list( , $inside, $trail ) = $m;
1780 }
1781 return [ $inside, $trail ];
1782 }
1783
1811 public static function generateRollback( $rev, IContextSource $context = null,
1812 $options = [ 'verify' ]
1813 ) {
1814 if ( $context === null ) {
1815 $context = RequestContext::getMain();
1816 }
1817
1818 $editCount = false;
1819 if ( in_array( 'verify', $options, true ) ) {
1820 $editCount = self::getRollbackEditCount( $rev, true );
1821 if ( $editCount === false ) {
1822 return '';
1823 }
1824 }
1825
1826 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1827
1828 if ( !in_array( 'noBrackets', $options, true ) ) {
1829 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1830 }
1831
1832 if ( $context->getUser()->getBoolOption( 'showrollbackconfirmation' ) ) {
1833 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1834 $stats->increment( 'rollbackconfirmation.event.load' );
1835 $context->getOutput()->addModules( 'mediawiki.page.rollback.confirmation' );
1836 }
1837
1838 return '<span class="mw-rollback-link">' . $inner . '</span>';
1839 }
1840
1856 public static function getRollbackEditCount( $rev, $verify ) {
1858 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1859 // Nothing has happened, indicate this by returning 'null'
1860 return null;
1861 }
1862
1863 $dbr = wfGetDB( DB_REPLICA );
1864
1865 // Up to the value of $wgShowRollbackEditCount revisions are counted
1867 $res = $dbr->select(
1868 $revQuery['tables'],
1869 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1870 // $rev->getPage() returns null sometimes
1871 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1872 __METHOD__,
1873 [
1874 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1875 'ORDER BY' => 'rev_timestamp DESC',
1876 'LIMIT' => $wgShowRollbackEditCount + 1
1877 ],
1878 $revQuery['joins']
1879 );
1880
1881 $editCount = 0;
1882 $moreRevs = false;
1883 foreach ( $res as $row ) {
1884 if ( $rev->getUserText( RevisionRecord::RAW ) != $row->rev_user_text ) {
1885 if ( $verify &&
1886 ( $row->rev_deleted & RevisionRecord::DELETED_TEXT
1887 || $row->rev_deleted & RevisionRecord::DELETED_USER
1888 ) ) {
1889 // If the user or the text of the revision we might rollback
1890 // to is deleted in some way we can't rollback. Similar to
1891 // the sanity checks in WikiPage::commitRollback.
1892 return false;
1893 }
1894 $moreRevs = true;
1895 break;
1896 }
1897 $editCount++;
1898 }
1899
1900 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1901 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1902 // and there weren't any other revisions. That means that the current user is the only
1903 // editor, so we can't rollback
1904 return false;
1905 }
1906 return $editCount;
1907 }
1908
1918 public static function buildRollbackLink( $rev, IContextSource $context = null,
1919 $editCount = false
1920 ) {
1922
1923 // To config which pages are affected by miser mode
1924 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1925
1926 if ( $context === null ) {
1927 $context = RequestContext::getMain();
1928 }
1929
1930 $title = $rev->getTitle();
1931
1932 $query = [
1933 'action' => 'rollback',
1934 'from' => $rev->getUserText(),
1935 'token' => $context->getUser()->getEditToken( 'rollback' ),
1936 ];
1937
1938 $attrs = [
1939 'data-mw' => 'interface',
1940 'title' => $context->msg( 'tooltip-rollback' )->text()
1941 ];
1942
1943 $options = [ 'known', 'noclasses' ];
1944
1945 if ( $context->getRequest()->getBool( 'bot' ) ) {
1946 //T17999
1947 $query['hidediff'] = '1';
1948 $query['bot'] = '1';
1949 }
1950
1951 $disableRollbackEditCount = false;
1952 if ( $wgMiserMode ) {
1953 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1954 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1955 $disableRollbackEditCount = true;
1956 break;
1957 }
1958 }
1959 }
1960
1961 if ( !$disableRollbackEditCount
1962 && is_int( $wgShowRollbackEditCount )
1964 ) {
1965 if ( !is_numeric( $editCount ) ) {
1966 $editCount = self::getRollbackEditCount( $rev, false );
1967 }
1968
1969 if ( $editCount > $wgShowRollbackEditCount ) {
1970 $html = $context->msg( 'rollbacklinkcount-morethan' )
1971 ->numParams( $wgShowRollbackEditCount )->parse();
1972 } else {
1973 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1974 }
1975
1976 return self::link( $title, $html, $attrs, $query, $options );
1977 }
1978
1979 $html = $context->msg( 'rollbacklink' )->escaped();
1980 return self::link( $title, $html, $attrs, $query, $options );
1981 }
1982
1991 public static function formatHiddenCategories( $hiddencats ) {
1992 $outText = '';
1993 if ( count( $hiddencats ) > 0 ) {
1994 # Construct the HTML
1995 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1996 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1997 $outText .= "</div><ul>\n";
1998
1999 foreach ( $hiddencats as $titleObj ) {
2000 # If it's hidden, it must exist - no need to check with a LinkBatch
2001 $outText .= '<li>'
2002 . self::link( $titleObj, null, [], [], 'known' )
2003 . "</li>\n";
2004 }
2005 $outText .= '</ul>';
2006 }
2007 return $outText;
2008 }
2009
2026 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2027 $message = wfMessage( "tooltip-$name", $msgParams );
2028 if ( !$message->exists() ) {
2029 $tooltip = false;
2030 } else {
2031 $tooltip = $message->text();
2032 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2033 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2034 # Message equal to '-' means suppress it.
2035 if ( $tooltip == '-' ) {
2036 $tooltip = false;
2037 }
2038 }
2039
2040 $options = (array)$options;
2041
2042 if ( in_array( 'nonexisting', $options ) ) {
2043 $tooltip = wfMessage( 'red-link-title', $tooltip ?: '' )->text();
2044 }
2045 if ( in_array( 'withaccess', $options ) ) {
2046 $accesskey = self::accesskey( $name );
2047 if ( $accesskey !== false ) {
2048 // Should be build the same as in jquery.accessKeyLabel.js
2049 if ( $tooltip === false || $tooltip === '' ) {
2050 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2051 } else {
2052 $tooltip .= wfMessage( 'word-separator' )->text();
2053 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2054 }
2055 }
2056 }
2057
2058 return $tooltip;
2059 }
2060
2061 public static $accesskeycache;
2062
2074 public static function accesskey( $name ) {
2075 if ( isset( self::$accesskeycache[$name] ) ) {
2076 return self::$accesskeycache[$name];
2077 }
2078
2079 $message = wfMessage( "accesskey-$name" );
2080
2081 if ( !$message->exists() ) {
2082 $accesskey = false;
2083 } else {
2084 $accesskey = $message->plain();
2085 if ( $accesskey === '' || $accesskey === '-' ) {
2086 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2087 # attribute, but this is broken for accesskey: that might be a useful
2088 # value.
2089 $accesskey = false;
2090 }
2091 }
2092
2093 self::$accesskeycache[$name] = $accesskey;
2094 return self::$accesskeycache[$name];
2095 }
2096
2110 public static function getRevDeleteLink( User $user, Revision $rev, LinkTarget $title ) {
2111 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
2112 $canHide = $permissionManager->userHasRight( $user, 'deleterevision' );
2113 $canHideHistory = $permissionManager->userHasRight( $user, 'deletedhistory' );
2114 if ( !$canHide && !( $rev->getVisibility() && $canHideHistory ) ) {
2115 return '';
2116 }
2117
2118 if ( !$rev->userCan( RevisionRecord::DELETED_RESTRICTED, $user ) ) {
2119 return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2120 }
2121 $prefixedDbKey = MediaWikiServices::getInstance()->getTitleFormatter()->
2122 getPrefixedDBkey( $title );
2123 if ( $rev->getId() ) {
2124 // RevDelete links using revision ID are stable across
2125 // page deletion and undeletion; use when possible.
2126 $query = [
2127 'type' => 'revision',
2128 'target' => $prefixedDbKey,
2129 'ids' => $rev->getId()
2130 ];
2131 } else {
2132 // Older deleted entries didn't save a revision ID.
2133 // We have to refer to these by timestamp, ick!
2134 $query = [
2135 'type' => 'archive',
2136 'target' => $prefixedDbKey,
2137 'ids' => $rev->getTimestamp()
2138 ];
2139 }
2140 return self::revDeleteLink( $query,
2141 $rev->isDeleted( RevisionRecord::DELETED_RESTRICTED ), $canHide );
2142 }
2143
2154 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2155 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2156 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2157 $html = wfMessage( $msgKey )->escaped();
2158 $tag = $restricted ? 'strong' : 'span';
2159 $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2160 return Xml::tags(
2161 $tag,
2162 [ 'class' => 'mw-revdelundel-link' ],
2163 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2164 );
2165 }
2166
2176 public static function revDeleteLinkDisabled( $delete = true ) {
2177 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2178 $html = wfMessage( $msgKey )->escaped();
2179 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2180 return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2181 }
2182
2195 public static function tooltipAndAccesskeyAttribs(
2196 $name,
2197 array $msgParams = [],
2198 $options = null
2199 ) {
2200 $options = (array)$options;
2201 $options[] = 'withaccess';
2202
2203 $attribs = [
2204 'title' => self::titleAttrib( $name, $options, $msgParams ),
2205 'accesskey' => self::accesskey( $name )
2206 ];
2207 if ( $attribs['title'] === false ) {
2208 unset( $attribs['title'] );
2209 }
2210 if ( $attribs['accesskey'] === false ) {
2211 unset( $attribs['accesskey'] );
2212 }
2213 return $attribs;
2214 }
2215
2223 public static function tooltip( $name, $options = null ) {
2224 $tooltip = self::titleAttrib( $name, $options );
2225 if ( $tooltip === false ) {
2226 return '';
2227 }
2228 return Xml::expandAttributes( [
2229 'title' => $tooltip
2230 ] );
2231 }
2232
2233}
$wgThumbUpright
Adjust width of upright images when parameter 'upright' is used This allows a nicer look for upright ...
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
$wgDisableAnonTalk
Disable links to talk pages of anonymous users (IPs) in listings on special pages like page history,...
$wgSVGMaxSize
Don't scale a SVG larger than this.
$wgShowRollbackEditCount
The $wgShowRollbackEditCount variable is used to show how many edits can be rolled back.
$wgUploadMissingFileUrl
Point the upload link for missing files to an external URL, as with $wgUploadNavigationUrl.
$wgUploadNavigationUrl
Point the upload navigation link to an external URL Useful if you want to use a shared repository by ...
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
$wgEnableUploads
Allow users to upload files.
$wgMiserMode
Disable database-intensive features.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
$fallback
$wgLang
Definition Setup.php:880
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition api.php:58
static getUserLinkTitle( $userName)
Get a target Title to link a username.
static isExternal( $username)
Tells whether the username is external or not.
Marks HTML that shouldn't be escaped.
Definition HtmlArmor.php:28
Internationalisation code.
Definition Language.php:37
Some internal bits split of from Skin.php.
Definition Linker.php:35
static generateRollback( $rev, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition Linker.php:1811
static makeMediaLinkFile(LinkTarget $title, $file, $html='')
Create a direct link to a given uploaded file.
Definition Linker.php:781
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition Linker.php:85
static fnamePart( $url)
Returns the filename part of an url.
Definition Linker.php:227
static tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition Linker.php:1643
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition Linker.php:898
static $accesskeycache
Definition Linker.php:2061
static titleAttrib( $name, $options=null, array $msgParams=[])
Given the id of an interface element, constructs the appropriate title attribute from the system mess...
Definition Linker.php:2026
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition Linker.php:2074
static formatAutocomments( $comment, $title=null, $local=false, $wikiId=null)
Converts autogenerated comments in edit summaries into section links.
Definition Linker.php:1195
static specialLink( $name, $key='')
Make a link to a special page given its name and, optionally, a message key from the link text.
Definition Linker.php:822
static getRevDeleteLink(User $user, Revision $rev, LinkTarget $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition Linker.php:2110
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition Linker.php:141
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition Linker.php:247
static buildRollbackLink( $rev, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition Linker.php:1918
static makeCommentLink(LinkTarget $linkTarget, $text, $wikiId=null, $options=[])
Generates a link to the given LinkTarget.
Definition Linker.php:1425
static revComment(Revision $rev, $local=false, $isPublic=false, $useParentheses=true)
Wrap and format the given revision's comment block, if the current user is allowed to view it.
Definition Linker.php:1577
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition Linker.php:642
static blockLink( $userId, $userText)
Definition Linker.php:1058
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition Linker.php:2176
static getRollbackEditCount( $rev, $verify)
This function will return the number of revisions which a rollback would revert and,...
Definition Linker.php:1856
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition Linker.php:1455
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition Linker.php:39
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='')
Make appropriate markup for a link to the current article.
Definition Linker.php:163
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition Linker.php:733
static tocIndent()
Add another level to the Table of Contents.
Definition Linker.php:1617
static makeImageLink(Parser $parser, LinkTarget $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="", $widthOption=null)
Given parameters derived from [[Image:Foo|options...]], generate the HTML that that syntax inserts in...
Definition Linker.php:303
static revUserLink( $rev, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition Linker.php:1101
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition Linker.php:187
static emailLink( $userId, $userText)
Definition Linker.php:1079
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition Linker.php:1991
static splitTrail( $trail)
Split a link trail, return the "inside" portion and the remainder of the trail as a two-element array...
Definition Linker.php:1775
static makeThumbLink2(LinkTarget $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="")
Definition Linker.php:519
static generateTOC( $tree, Language $lang=null)
Generate a table of contents from a section tree.
Definition Linker.php:1716
const TOOL_LINKS_EMAIL
Definition Linker.php:40
static formatRevisionSize( $size)
Definition Linker.php:1602
static commentBlock( $comment, $title=null, $local=false, $wikiId=null, $useParentheses=true)
Wrap a comment in standard punctuation and formatting if it's non-empty, otherwise return empty strin...
Definition Linker.php:1547
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition Linker.php:2223
static revUserTools( $rev, $isPublic=false, $useParentheses=true)
Generate a user tool link cluster if the current user is allowed to view it.
Definition Linker.php:1124
static userTalkLink( $userId, $userText)
Definition Linker.php:1036
static formatLinksInComment( $comment, $title=null, $local=false, $wikiId=null)
Formats wiki links and media links in text; all other wiki formatting is ignored.
Definition Linker.php:1303
static makeMediaLinkObj( $title, $html='', $time=false)
Create a direct link to a given uploaded file.
Definition Linker.php:762
static makeThumbLinkObj(LinkTarget $title, $file, $label='', $alt='', $align='right', $params=[], $framed=false, $manualthumb="")
Make HTML for a thumbnail including image, border and caption.
Definition Linker.php:493
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition Linker.php:848
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null, $useParentheses=true)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition Linker.php:943
static normaliseSpecialPage(LinkTarget $target)
Definition Linker.php:207
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition Linker.php:1754
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition Linker.php:1628
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition Linker.php:2195
static tocList( $toc, Language $lang=null)
Wraps the TOC in a table and provides the hide/collapse javascript.
Definition Linker.php:1679
static getImageLinkMTOParams( $frameParams, $query='', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition Linker.php:454
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition Linker.php:2154
static tocLineEnd()
End a Table Of Contents line.
Definition Linker.php:1667
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition Linker.php:1165
static userToolLinksRedContribs( $userId, $userText, $edits=null, $useParentheses=true)
Alias for userToolLinks( $userId, $userText, true );.
Definition Linker.php:1024
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false)
Make a "broken" link to an image.
Definition Linker.php:677
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Page revision base class.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:74
getTargetLanguage()
Get the target language for the content being parsed.
Definition Parser.php:1037
getTitle()
Returns the title of the page associated with this entry.
Definition Revision.php:559
getId()
Get revision ID.
Definition Revision.php:442
getComment( $audience=self::FOR_PUBLIC, User $user=null)
Definition Revision.php:649
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object.
Definition Revision.php:315
getTimestamp()
Definition Revision.php:798
getVisibility()
Get the deletion bitfield of the revision.
Definition Revision.php:701
userCan( $field, User $user=null)
Determine if the current user is allowed to view a particular field of this revision,...
isDeleted( $field)
Definition Revision.php:692
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Represents a page (or page fragment) title within MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:51
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition User.php:542
static getDefaultOption( $opt)
Get a given default option value.
Definition User.php:1734
const NS_USER
Definition Defines.php:71
const NS_FILE
Definition Defines.php:75
const NS_MAIN
Definition Defines.php:69
const NS_SPECIAL
Definition Defines.php:58
const NS_MEDIA
Definition Defines.php:57
const NS_USER_TALK
Definition Defines.php:72
Interface for objects which can provide a MediaWiki context on request.
getFragment()
Get the link fragment (i.e.
getNamespace()
Get the namespace index.
getDBkey()
Get the main part with underscores.
isExternal()
Whether this LinkTarget has an interwiki component.
$context
Definition load.php:45
const DB_REPLICA
Definition defines.php:25
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!isset( $args[0])) $lang