MediaWiki REL1_28
Linker.php
Go to the documentation of this file.
1<?php
24
34class Linker {
40
54 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
56
57 wfDeprecated( __METHOD__, '1.25' );
58
59 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
60 # getExternalLinkAttributes, why?
61 $title = urldecode( $title );
62 $title = $wgContLang->checkTitleEncoding( $title );
63 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
64
66 }
67
80 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
81 wfDeprecated( __METHOD__, '1.25' );
82
83 $title = urldecode( $title );
84 $title = strtr( $title, '_', ' ' );
86 }
87
102 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
103 wfDeprecated( __METHOD__, '1.25' );
104
105 if ( $title === false ) {
106 $title = $nt->getPrefixedText();
107 }
108 return self::getLinkAttributesInternal( $title, $class );
109 }
110
122 private static function getLinkAttributesInternal( $title, $class ) {
123 wfDeprecated( __METHOD__, '1.25' );
124
125 $title = htmlspecialchars( $title );
126 $class = htmlspecialchars( $class );
127 $r = '';
128 if ( $class != '' ) {
129 $r .= " class=\"$class\"";
130 }
131 if ( $title != '' ) {
132 $r .= " title=\"$title\"";
133 }
134 return $r;
135 }
136
147 public static function getLinkColour( LinkTarget $t, $threshold ) {
148 wfDeprecated( __METHOD__, '1.28' );
149 $services = MediaWikiServices::getInstance();
150 $linkRenderer = $services->getLinkRenderer();
151 if ( $threshold !== $linkRenderer->getStubThreshold() ) {
152 // Need to create a new instance with the right stub threshold...
153 $linkRenderer = $services->getLinkRendererFactory()->create();
154 $linkRenderer->setStubThreshold( $threshold );
155 }
156
157 return $linkRenderer->getLinkClasses( $t );
158 }
159
203 public static function link(
204 $target, $html = null, $customAttribs = [], $query = [], $options = []
205 ) {
206 if ( !$target instanceof Title ) {
207 wfWarn( __METHOD__ . ': Requires $target to be a Title object.', 2 );
208 return "<!-- ERROR -->$html";
209 }
210
211 if ( is_string( $query ) ) {
212 // some functions withing core using this still hand over query strings
213 wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
215 }
216
217 $services = MediaWikiServices::getInstance();
219 if ( $options ) {
220 // Custom options, create new LinkRenderer
221 if ( !isset( $options['stubThreshold'] ) ) {
222 $defaultLinkRenderer = $services->getLinkRenderer();
223 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
224 }
225 $linkRenderer = $services->getLinkRendererFactory()
226 ->createFromLegacyOptions( $options );
227 } else {
228 $linkRenderer = $services->getLinkRenderer();
229 }
230
231 if ( $html !== null ) {
232 $text = new HtmlArmor( $html );
233 } else {
234 $text = $html; // null
235 }
236 if ( in_array( 'known', $options, true ) ) {
237 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
238 } elseif ( in_array( 'broken', $options, true ) ) {
239 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
240 } elseif ( in_array( 'noclasses', $options, true ) ) {
241 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
242 } else {
243 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
244 }
245 }
246
255 public static function linkKnown(
256 $target, $html = null, $customAttribs = [],
257 $query = [], $options = [ 'known' ]
258 ) {
259 return self::link( $target, $html, $customAttribs, $query, $options );
260 }
261
277 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
278 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
279 if ( !Hooks::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
280 return $ret;
281 }
282
283 if ( $html == '' ) {
284 $html = htmlspecialchars( $nt->getPrefixedText() );
285 }
286 list( $inside, $trail ) = self::splitTrail( $trail );
287 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
288 }
289
300 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
302
303 // First we check whether the namespace exists or not.
304 if ( MWNamespace::exists( $namespace ) ) {
305 if ( $namespace == NS_MAIN ) {
306 $name = $context->msg( 'blanknamespace' )->text();
307 } else {
308 $name = $wgContLang->getFormattedNsText( $namespace );
309 }
310 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
311 } else {
312 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
313 }
314 }
315
321 public static function normaliseSpecialPage( LinkTarget $target ) {
322 if ( $target->getNamespace() == NS_SPECIAL && !$target->isExternal() ) {
323 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $target->getDBkey() );
324 if ( !$name ) {
325 return $target;
326 }
327 $ret = SpecialPage::getTitleValueFor( $name, $subpage, $target->getFragment() );
328 return $ret;
329 } else {
330 return $target;
331 }
332 }
333
342 private static function fnamePart( $url ) {
343 $basename = strrchr( $url, '/' );
344 if ( false === $basename ) {
345 $basename = $url;
346 } else {
347 $basename = substr( $basename, 1 );
348 }
349 return $basename;
350 }
351
362 public static function makeExternalImage( $url, $alt = '' ) {
363 if ( $alt == '' ) {
364 $alt = self::fnamePart( $url );
365 }
366 $img = '';
367 $success = Hooks::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
368 if ( !$success ) {
369 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
370 . "with url {$url} and alt text {$alt} to {$img}\n", true );
371 return $img;
372 }
373 return Html::element( 'img',
374 [
375 'src' => $url,
376 'alt' => $alt ] );
377 }
378
415 public static function makeImageLink( Parser $parser, Title $title,
416 $file, $frameParams = [], $handlerParams = [], $time = false,
417 $query = "", $widthOption = null
418 ) {
419 $res = null;
420 $dummy = new DummyLinker;
421 if ( !Hooks::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
422 &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
423 return $res;
424 }
425
426 if ( $file && !$file->allowInlineDisplay() ) {
427 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
428 return self::link( $title );
429 }
430
431 // Clean up parameters
432 $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false;
433 if ( !isset( $frameParams['align'] ) ) {
434 $frameParams['align'] = '';
435 }
436 if ( !isset( $frameParams['alt'] ) ) {
437 $frameParams['alt'] = '';
438 }
439 if ( !isset( $frameParams['title'] ) ) {
440 $frameParams['title'] = '';
441 }
442 if ( !isset( $frameParams['class'] ) ) {
443 $frameParams['class'] = '';
444 }
445
446 $prefix = $postfix = '';
447
448 if ( 'center' == $frameParams['align'] ) {
449 $prefix = '<div class="center">';
450 $postfix = '</div>';
451 $frameParams['align'] = 'none';
452 }
453 if ( $file && !isset( $handlerParams['width'] ) ) {
454 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
455 // If its a vector image, and user only specifies height
456 // we don't want it to be limited by its "normal" width.
458 $handlerParams['width'] = $wgSVGMaxSize;
459 } else {
460 $handlerParams['width'] = $file->getWidth( $page );
461 }
462
463 if ( isset( $frameParams['thumbnail'] )
464 || isset( $frameParams['manualthumb'] )
465 || isset( $frameParams['framed'] )
466 || isset( $frameParams['frameless'] )
467 || !$handlerParams['width']
468 ) {
470
471 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
472 $widthOption = User::getDefaultOption( 'thumbsize' );
473 }
474
475 // Reduce width for upright images when parameter 'upright' is used
476 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
477 $frameParams['upright'] = $wgThumbUpright;
478 }
479
480 // For caching health: If width scaled down due to upright
481 // parameter, round to full __0 pixel to avoid the creation of a
482 // lot of odd thumbs.
483 $prefWidth = isset( $frameParams['upright'] ) ?
484 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
485 $wgThumbLimits[$widthOption];
486
487 // Use width which is smaller: real image width or user preference width
488 // Unless image is scalable vector.
489 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
490 $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
491 $handlerParams['width'] = $prefWidth;
492 }
493 }
494 }
495
496 if ( isset( $frameParams['thumbnail'] ) || isset( $frameParams['manualthumb'] )
497 || isset( $frameParams['framed'] )
498 ) {
499 # Create a thumbnail. Alignment depends on the writing direction of
500 # the page content language (right-aligned for LTR languages,
501 # left-aligned for RTL languages)
502 # If a thumbnail width has not been provided, it is set
503 # to the default user option as specified in Language*.php
504 if ( $frameParams['align'] == '' ) {
505 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
506 }
507 return $prefix .
508 self::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
509 $postfix;
510 }
511
512 if ( $file && isset( $frameParams['frameless'] ) ) {
513 $srcWidth = $file->getWidth( $page );
514 # For "frameless" option: do not present an image bigger than the
515 # source (for bitmap-style images). This is the same behavior as the
516 # "thumb" option does it already.
517 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
518 $handlerParams['width'] = $srcWidth;
519 }
520 }
521
522 if ( $file && isset( $handlerParams['width'] ) ) {
523 # Create a resized image, without the additional thumbnail features
524 $thumb = $file->transform( $handlerParams );
525 } else {
526 $thumb = false;
527 }
528
529 if ( !$thumb ) {
530 $s = self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
531 } else {
533 $params = [
534 'alt' => $frameParams['alt'],
535 'title' => $frameParams['title'],
536 'valign' => isset( $frameParams['valign'] ) ? $frameParams['valign'] : false,
537 'img-class' => $frameParams['class'] ];
538 if ( isset( $frameParams['border'] ) ) {
539 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
540 }
542
543 $s = $thumb->toHtml( $params );
544 }
545 if ( $frameParams['align'] != '' ) {
546 $s = "<div class=\"float{$frameParams['align']}\">{$s}</div>";
547 }
548 return str_replace( "\n", ' ', $prefix . $s . $postfix );
549 }
550
559 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
560 $mtoParams = [];
561 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
562 $mtoParams['custom-url-link'] = $frameParams['link-url'];
563 if ( isset( $frameParams['link-target'] ) ) {
564 $mtoParams['custom-target-link'] = $frameParams['link-target'];
565 }
566 if ( $parser ) {
567 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
568 foreach ( $extLinkAttrs as $name => $val ) {
569 // Currently could include 'rel' and 'target'
570 $mtoParams['parser-extlink-' . $name] = $val;
571 }
572 }
573 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
574 $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
575 self::normaliseSpecialPage( $frameParams['link-title'] )
576 );
577 } elseif ( !empty( $frameParams['no-link'] ) ) {
578 // No link
579 } else {
580 $mtoParams['desc-link'] = true;
581 $mtoParams['desc-query'] = $query;
582 }
583 return $mtoParams;
584 }
585
598 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
599 $align = 'right', $params = [], $framed = false, $manualthumb = ""
600 ) {
601 $frameParams = [
602 'alt' => $alt,
603 'caption' => $label,
604 'align' => $align
605 ];
606 if ( $framed ) {
607 $frameParams['framed'] = true;
608 }
609 if ( $manualthumb ) {
610 $frameParams['manualthumb'] = $manualthumb;
611 }
612 return self::makeThumbLink2( $title, $file, $frameParams, $params );
613 }
614
624 public static function makeThumbLink2( Title $title, $file, $frameParams = [],
625 $handlerParams = [], $time = false, $query = ""
626 ) {
627 $exists = $file && $file->exists();
628
629 $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false;
630 if ( !isset( $frameParams['align'] ) ) {
631 $frameParams['align'] = 'right';
632 }
633 if ( !isset( $frameParams['alt'] ) ) {
634 $frameParams['alt'] = '';
635 }
636 if ( !isset( $frameParams['title'] ) ) {
637 $frameParams['title'] = '';
638 }
639 if ( !isset( $frameParams['caption'] ) ) {
640 $frameParams['caption'] = '';
641 }
642
643 if ( empty( $handlerParams['width'] ) ) {
644 // Reduce width for upright images when parameter 'upright' is used
645 $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
646 }
647 $thumb = false;
648 $noscale = false;
649 $manualthumb = false;
650
651 if ( !$exists ) {
652 $outerWidth = $handlerParams['width'] + 2;
653 } else {
654 if ( isset( $frameParams['manualthumb'] ) ) {
655 # Use manually specified thumbnail
656 $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
657 if ( $manual_title ) {
658 $manual_img = wfFindFile( $manual_title );
659 if ( $manual_img ) {
660 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
661 $manualthumb = true;
662 } else {
663 $exists = false;
664 }
665 }
666 } elseif ( isset( $frameParams['framed'] ) ) {
667 // Use image dimensions, don't scale
668 $thumb = $file->getUnscaledThumb( $handlerParams );
669 $noscale = true;
670 } else {
671 # Do not present an image bigger than the source, for bitmap-style images
672 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
673 $srcWidth = $file->getWidth( $page );
674 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
675 $handlerParams['width'] = $srcWidth;
676 }
677 $thumb = $file->transform( $handlerParams );
678 }
679
680 if ( $thumb ) {
681 $outerWidth = $thumb->getWidth() + 2;
682 } else {
683 $outerWidth = $handlerParams['width'] + 2;
684 }
685 }
686
687 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
688 # So we don't need to pass it here in $query. However, the URL for the
689 # zoom icon still needs it, so we make a unique query for it. See bug 14771
690 $url = $title->getLocalURL( $query );
691 if ( $page ) {
692 $url = wfAppendQuery( $url, [ 'page' => $page ] );
693 }
694 if ( $manualthumb
695 && !isset( $frameParams['link-title'] )
696 && !isset( $frameParams['link-url'] )
697 && !isset( $frameParams['no-link'] ) ) {
698 $frameParams['link-url'] = $url;
699 }
700
701 $s = "<div class=\"thumb t{$frameParams['align']}\">"
702 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
703
704 if ( !$exists ) {
705 $s .= self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
706 $zoomIcon = '';
707 } elseif ( !$thumb ) {
708 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
709 $zoomIcon = '';
710 } else {
711 if ( !$noscale && !$manualthumb ) {
713 }
714 $params = [
715 'alt' => $frameParams['alt'],
716 'title' => $frameParams['title'],
717 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
718 ? $frameParams['class'] . ' '
719 : '' ) . 'thumbimage'
720 ];
722 $s .= $thumb->toHtml( $params );
723 if ( isset( $frameParams['framed'] ) ) {
724 $zoomIcon = "";
725 } else {
726 $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
727 Html::rawElement( 'a', [
728 'href' => $url,
729 'class' => 'internal',
730 'title' => wfMessage( 'thumbnail-more' )->text() ],
731 "" ) );
732 }
733 }
734 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
735 return str_replace( "\n", ' ', $s );
736 }
737
746 public static function processResponsiveImages( $file, $thumb, $hp ) {
748 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
749 $hp15 = $hp;
750 $hp15['width'] = round( $hp['width'] * 1.5 );
751 $hp20 = $hp;
752 $hp20['width'] = $hp['width'] * 2;
753 if ( isset( $hp['height'] ) ) {
754 $hp15['height'] = round( $hp['height'] * 1.5 );
755 $hp20['height'] = $hp['height'] * 2;
756 }
757
758 $thumb15 = $file->transform( $hp15 );
759 $thumb20 = $file->transform( $hp20 );
760 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
761 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
762 }
763 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
764 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
765 }
766 }
767 }
768
781 public static function makeBrokenImageLinkObj( $title, $label = '',
782 $query = '', $unused1 = '', $unused2 = '', $time = false
783 ) {
784 if ( !$title instanceof Title ) {
785 wfWarn( __METHOD__ . ': Requires $title to be a Title object.' );
786 return "<!-- ERROR -->" . htmlspecialchars( $label );
787 }
788
790 if ( $label == '' ) {
791 $label = $title->getPrefixedText();
792 }
793 $encLabel = htmlspecialchars( $label );
794 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
795
797 && !$currentExists
798 ) {
799 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
800
801 if ( $redir ) {
802 // We already know it's a redirect, so mark it
803 // accordingly
804 return self::link(
805 $title,
806 $encLabel,
807 [ 'class' => 'mw-redirect' ],
809 [ 'known', 'noclasses' ]
810 );
811 }
812
813 $href = self::getUploadUrl( $title, $query );
814
815 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
816 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
817 $encLabel . '</a>';
818 }
819
820 return self::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
821 }
822
831 protected static function getUploadUrl( $destFile, $query = '' ) {
833 $q = 'wpDestFile=' . $destFile->getPartialURL();
834 if ( $query != '' ) {
835 $q .= '&' . $query;
836 }
837
840 } elseif ( $wgUploadNavigationUrl ) {
842 } else {
843 $upload = SpecialPage::getTitleFor( 'Upload' );
844 return $upload->getLocalURL( $q );
845 }
846 }
847
857 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
858 $img = wfFindFile( $title, [ 'time' => $time ] );
859 return self::makeMediaLinkFile( $title, $img, $html );
860 }
861
874 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
875 if ( $file && $file->exists() ) {
876 $url = $file->getUrl();
877 $class = 'internal';
878 } else {
879 $url = self::getUploadUrl( $title );
880 $class = 'new';
881 }
882
883 $alt = $title->getText();
884 if ( $html == '' ) {
885 $html = $alt;
886 }
887
888 $ret = '';
889 $attribs = [
890 'href' => $url,
891 'class' => $class,
892 'title' => $alt
893 ];
894
895 if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
896 [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
897 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
898 . "with url {$url} and text {$html} to {$ret}\n", true );
899 return $ret;
900 }
901
902 return Html::rawElement( 'a', $attribs, $html );
903 }
904
915 public static function specialLink( $name, $key = '' ) {
916 if ( $key == '' ) {
917 $key = strtolower( $name );
918 }
919
921 }
922
934 public static function makeExternalLink( $url, $text, $escape = true,
935 $linktype = '', $attribs = [], $title = null
936 ) {
938 $class = "external";
939 if ( $linktype ) {
940 $class .= " $linktype";
941 }
942 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
943 $class .= " {$attribs['class']}";
944 }
945 $attribs['class'] = $class;
946
947 if ( $escape ) {
948 $text = htmlspecialchars( $text );
949 }
950
951 if ( !$title ) {
953 }
954 $newRel = Parser::getExternalLinkRel( $url, $title );
955 if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
956 $attribs['rel'] = $newRel;
957 } elseif ( $newRel !== '' ) {
958 // Merge the rel attributes.
959 $newRels = explode( ' ', $newRel );
960 $oldRels = explode( ' ', $attribs['rel'] );
961 $combined = array_unique( array_merge( $newRels, $oldRels ) );
962 $attribs['rel'] = implode( ' ', $combined );
963 }
964 $link = '';
965 $success = Hooks::run( 'LinkerMakeExternalLink',
966 [ &$url, &$text, &$link, &$attribs, $linktype ] );
967 if ( !$success ) {
968 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
969 . "with url {$url} and text {$text} to {$link}\n", true );
970 return $link;
971 }
972 $attribs['href'] = $url;
973 return Html::rawElement( 'a', $attribs, $text );
974 }
975
984 public static function userLink( $userId, $userName, $altUserName = false ) {
985 $classes = 'mw-userlink';
986 if ( $userId == 0 ) {
987 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
988 if ( $altUserName === false ) {
989 $altUserName = IP::prettifyIP( $userName );
990 }
991 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
992 } else {
993 $page = Title::makeTitle( NS_USER, $userName );
994 }
995
996 // Wrap the output with <bdi> tags for directionality isolation
997 return self::link(
998 $page,
999 '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>',
1000 [ 'class' => $classes ]
1001 );
1002 }
1003
1017 public static function userToolLinks(
1018 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1019 ) {
1021 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1022 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1023 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1024
1025 $items = [];
1026 if ( $talkable ) {
1027 $items[] = self::userTalkLink( $userId, $userText );
1028 }
1029 if ( $userId ) {
1030 // check if the user has an edit
1031 $attribs = [];
1032 if ( $redContribsWhenNoEdits ) {
1033 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1034 $user = User::newFromId( $userId );
1035 $edits = $user->getEditCount();
1036 }
1037 if ( $edits === 0 ) {
1038 $attribs['class'] = 'new';
1039 }
1040 }
1041 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1042
1043 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1044 }
1045 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1046 $items[] = self::blockLink( $userId, $userText );
1047 }
1048
1049 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1050 $items[] = self::emailLink( $userId, $userText );
1051 }
1052
1053 Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
1054
1055 if ( $items ) {
1056 return wfMessage( 'word-separator' )->escaped()
1057 . '<span class="mw-usertoollinks">'
1058 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1059 . '</span>';
1060 } else {
1061 return '';
1062 }
1063 }
1064
1073 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1074 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1075 }
1076
1083 public static function userTalkLink( $userId, $userText ) {
1084 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1085 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1086 return $userTalkLink;
1087 }
1088
1095 public static function blockLink( $userId, $userText ) {
1096 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1097 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1098 return $blockLink;
1099 }
1100
1106 public static function emailLink( $userId, $userText ) {
1107 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1108 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1109 return $emailLink;
1110 }
1111
1119 public static function revUserLink( $rev, $isPublic = false ) {
1120 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1121 $link = wfMessage( 'rev-deleted-user' )->escaped();
1122 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1124 $rev->getUserText( Revision::FOR_THIS_USER ) );
1125 } else {
1126 $link = wfMessage( 'rev-deleted-user' )->escaped();
1127 }
1128 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1129 return '<span class="history-deleted">' . $link . '</span>';
1130 }
1131 return $link;
1132 }
1133
1141 public static function revUserTools( $rev, $isPublic = false ) {
1142 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1143 $link = wfMessage( 'rev-deleted-user' )->escaped();
1144 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1145 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1146 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1147 $link = self::userLink( $userId, $userText )
1148 . self::userToolLinks( $userId, $userText );
1149 } else {
1150 $link = wfMessage( 'rev-deleted-user' )->escaped();
1151 }
1152 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1153 return ' <span class="history-deleted">' . $link . '</span>';
1154 }
1155 return $link;
1156 }
1157
1180 public static function formatComment(
1181 $comment, $title = null, $local = false, $wikiId = null
1182 ) {
1183 # Sanitize text a bit:
1184 $comment = str_replace( "\n", " ", $comment );
1185 # Allow HTML entities (for bug 13815)
1186 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1187
1188 # Render autocomments and make links:
1189 $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1190 $comment = self::formatLinksInComment( $comment, $title, $local, $wikiId );
1191
1192 return $comment;
1193 }
1194
1212 private static function formatAutocomments(
1213 $comment, $title = null, $local = false, $wikiId = null
1214 ) {
1215 // @todo $append here is something of a hack to preserve the status
1216 // quo. Someone who knows more about bidi and such should decide
1217 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1218 // wiki, both when autocomments exist and when they don't, and
1219 // (2) what markup will make that actually happen.
1220 $append = '';
1221 $comment = preg_replace_callback(
1222 // To detect the presence of content before or after the
1223 // auto-comment, we use capturing groups inside optional zero-width
1224 // assertions. But older versions of PCRE can't directly make
1225 // zero-width assertions optional, so wrap them in a non-capturing
1226 // group.
1227 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1228 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1230
1231 // Ensure all match positions are defined
1232 $match += [ '', '', '', '' ];
1233
1234 $pre = $match[1] !== '';
1235 $auto = $match[2];
1236 $post = $match[3] !== '';
1237 $comment = null;
1238
1239 Hooks::run(
1240 'FormatAutocomments',
1241 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1242 );
1243
1244 if ( $comment === null ) {
1245 $link = '';
1246 if ( $title ) {
1247 $section = $auto;
1248 # Remove links that a user may have manually put in the autosummary
1249 # This could be improved by copying as much of Parser::stripSectionName as desired.
1250 $section = str_replace( '[[:', '', $section );
1251 $section = str_replace( '[[', '', $section );
1252 $section = str_replace( ']]', '', $section );
1253
1254 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1255 if ( $local ) {
1256 $sectionTitle = Title::newFromText( '#' . $section );
1257 } else {
1258 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1259 $title->getDBkey(), $section );
1260 }
1261 if ( $sectionTitle ) {
1262 $link = Linker::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1263 } else {
1264 $link = '';
1265 }
1266 }
1267 if ( $pre ) {
1268 # written summary $presep autocomment (summary /* section */)
1269 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1270 }
1271 if ( $post ) {
1272 # autocomment $postsep written summary (/* section */ summary)
1273 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1274 }
1275 $auto = '<span class="autocomment">' . $auto . '</span>';
1276 $comment = $pre . $link . $wgLang->getDirMark()
1277 . '<span dir="auto">' . $auto;
1278 $append .= '</span>';
1279 }
1280 return $comment;
1281 },
1282 $comment
1283 );
1284 return $comment . $append;
1285 }
1286
1305 public static function formatLinksInComment(
1306 $comment, $title = null, $local = false, $wikiId = null
1307 ) {
1308 return preg_replace_callback(
1309 '/
1310 \[\[
1311 :? # ignore optional leading colon
1312 ([^\]|]+) # 1. link target; page names cannot include ] or |
1313 (?:\|
1314 # 2. link text
1315 # Stop matching at ]] without relying on backtracking.
1316 ((?:]?[^\]])*+)
1317 )?
1318 \]\]
1319 ([^[]*) # 3. link trail (the text up until the next link)
1320 /x',
1321 function ( $match ) use ( $title, $local, $wikiId ) {
1323
1324 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1325 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1326
1327 $comment = $match[0];
1328
1329 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1330 if ( strpos( $match[1], '%' ) !== false ) {
1331 $match[1] = strtr(
1332 rawurldecode( $match[1] ),
1333 [ '<' => '&lt;', '>' => '&gt;' ]
1334 );
1335 }
1336
1337 # Handle link renaming [[foo|text]] will show link as "text"
1338 if ( $match[2] != "" ) {
1339 $text = $match[2];
1340 } else {
1341 $text = $match[1];
1342 }
1343 $submatch = [];
1344 $thelink = null;
1345 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1346 # Media link; trail not supported.
1347 $linkRegexp = '/\[\[(.*?)\]\]/';
1348 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1349 if ( $title ) {
1350 $thelink = Linker::makeMediaLinkObj( $title, $text );
1351 }
1352 } else {
1353 # Other kind of link
1354 # Make sure its target is non-empty
1355 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1356 $match[1] = substr( $match[1], 1 );
1357 }
1358 if ( $match[1] !== false && $match[1] !== '' ) {
1359 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1360 $trail = $submatch[1];
1361 } else {
1362 $trail = "";
1363 }
1364 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1365 list( $inside, $trail ) = Linker::splitTrail( $trail );
1366
1367 $linkText = $text;
1368 $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1369
1370 $target = Title::newFromText( $linkTarget );
1371 if ( $target ) {
1372 if ( $target->getText() == '' && !$target->isExternal()
1373 && !$local && $title
1374 ) {
1375 $newTarget = clone $title;
1376 $newTarget->setFragment( '#' . $target->getFragment() );
1377 $target = $newTarget;
1378 }
1379
1380 $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1381 }
1382 }
1383 }
1384 if ( $thelink ) {
1385 // If the link is still valid, go ahead and replace it in!
1386 $comment = preg_replace(
1387 $linkRegexp,
1389 $comment,
1390 1
1391 );
1392 }
1393
1394 return $comment;
1395 },
1396 $comment
1397 );
1398 }
1399
1413 public static function makeCommentLink(
1414 Title $title, $text, $wikiId = null, $options = []
1415 ) {
1416 if ( $wikiId !== null && !$title->isExternal() ) {
1419 $wikiId,
1420 $title->getPrefixedText(),
1421 $title->getFragment()
1422 ),
1423 $text,
1424 /* escape = */ false // Already escaped
1425 );
1426 } else {
1427 $link = Linker::link( $title, $text, [], [], $options );
1428 }
1429
1430 return $link;
1431 }
1432
1439 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1440 # Valid link forms:
1441 # Foobar -- normal
1442 # :Foobar -- override special treatment of prefix (images, language links)
1443 # /Foobar -- convert to CurrentPage/Foobar
1444 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1445 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1446 # ../Foobar -- convert to CurrentPage/Foobar,
1447 # (from CurrentPage/CurrentSubPage)
1448 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1449 # (from CurrentPage/CurrentSubPage)
1450
1451 $ret = $target; # default return value is no change
1452
1453 # Some namespaces don't allow subpages,
1454 # so only perform processing if subpages are allowed
1455 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1456 $hash = strpos( $target, '#' );
1457 if ( $hash !== false ) {
1458 $suffix = substr( $target, $hash );
1459 $target = substr( $target, 0, $hash );
1460 } else {
1461 $suffix = '';
1462 }
1463 # bug 7425
1464 $target = trim( $target );
1465 # Look at the first character
1466 if ( $target != '' && $target[0] === '/' ) {
1467 # / at end means we don't want the slash to be shown
1468 $m = [];
1469 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1470 if ( $trailingSlashes ) {
1471 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1472 } else {
1473 $noslash = substr( $target, 1 );
1474 }
1475
1476 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1477 if ( $text === '' ) {
1478 $text = $target . $suffix;
1479 } # this might be changed for ugliness reasons
1480 } else {
1481 # check for .. subpage backlinks
1482 $dotdotcount = 0;
1483 $nodotdot = $target;
1484 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1485 ++$dotdotcount;
1486 $nodotdot = substr( $nodotdot, 3 );
1487 }
1488 if ( $dotdotcount > 0 ) {
1489 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1490 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1491 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1492 # / at the end means don't show full path
1493 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1494 $nodotdot = rtrim( $nodotdot, '/' );
1495 if ( $text === '' ) {
1496 $text = $nodotdot . $suffix;
1497 }
1498 }
1499 $nodotdot = trim( $nodotdot );
1500 if ( $nodotdot != '' ) {
1501 $ret .= '/' . $nodotdot;
1502 }
1503 $ret .= $suffix;
1504 }
1505 }
1506 }
1507 }
1508
1509 return $ret;
1510 }
1511
1525 public static function commentBlock(
1526 $comment, $title = null, $local = false, $wikiId = null
1527 ) {
1528 // '*' used to be the comment inserted by the software way back
1529 // in antiquity in case none was provided, here for backwards
1530 // compatibility, acc. to brion -ævar
1531 if ( $comment == '' || $comment == '*' ) {
1532 return '';
1533 } else {
1534 $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1535 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1536 return " <span class=\"comment\">$formatted</span>";
1537 }
1538 }
1539
1550 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1551 if ( $rev->getComment( Revision::RAW ) == "" ) {
1552 return "";
1553 }
1554 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1555 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1556 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1557 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1558 $rev->getTitle(), $local );
1559 } else {
1560 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1561 }
1562 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1563 return " <span class=\"history-deleted\">$block</span>";
1564 }
1565 return $block;
1566 }
1567
1573 public static function formatRevisionSize( $size ) {
1574 if ( $size == 0 ) {
1575 $stxt = wfMessage( 'historyempty' )->escaped();
1576 } else {
1577 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1578 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1579 }
1580 return "<span class=\"history-size\">$stxt</span>";
1581 }
1582
1589 public static function tocIndent() {
1590 return "\n<ul>";
1591 }
1592
1600 public static function tocUnindent( $level ) {
1601 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1602 }
1603
1615 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1616 $classes = "toclevel-$level";
1617 if ( $sectionIndex !== false ) {
1618 $classes .= " tocsection-$sectionIndex";
1619 }
1620 return "\n<li class=\"$classes\"><a href=\"#" .
1621 $anchor . '"><span class="tocnumber">' .
1622 $tocnumber . '</span> <span class="toctext">' .
1623 $tocline . '</span></a>';
1624 }
1625
1633 public static function tocLineEnd() {
1634 return "</li>\n";
1635 }
1636
1645 public static function tocList( $toc, $lang = false ) {
1647 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1648
1649 return '<div id="toc" class="toc">'
1650 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1651 . $toc
1652 . "</ul>\n</div>\n";
1653 }
1654
1663 public static function generateTOC( $tree, $lang = false ) {
1664 $toc = '';
1665 $lastLevel = 0;
1666 foreach ( $tree as $section ) {
1667 if ( $section['toclevel'] > $lastLevel ) {
1668 $toc .= self::tocIndent();
1669 } elseif ( $section['toclevel'] < $lastLevel ) {
1670 $toc .= self::tocUnindent(
1671 $lastLevel - $section['toclevel'] );
1672 } else {
1673 $toc .= self::tocLineEnd();
1674 }
1675
1676 $toc .= self::tocLine( $section['anchor'],
1677 $section['line'], $section['number'],
1678 $section['toclevel'], $section['index'] );
1679 $lastLevel = $section['toclevel'];
1680 }
1681 $toc .= self::tocLineEnd();
1682 return self::tocList( $toc, $lang );
1683 }
1684
1701 public static function makeHeadline( $level, $attribs, $anchor, $html,
1702 $link, $fallbackAnchor = false
1703 ) {
1704 $anchorEscaped = htmlspecialchars( $anchor );
1705 $ret = "<h$level$attribs"
1706 . "<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1707 . $link
1708 . "</h$level>";
1709 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1710 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1711 $ret = "<div id=\"$fallbackAnchor\"></div>$ret";
1712 }
1713 return $ret;
1714 }
1715
1722 static function splitTrail( $trail ) {
1724 $regex = $wgContLang->linkTrail();
1725 $inside = '';
1726 if ( $trail !== '' ) {
1727 $m = [];
1728 if ( preg_match( $regex, $trail, $m ) ) {
1729 $inside = $m[1];
1730 $trail = $m[2];
1731 }
1732 }
1733 return [ $inside, $trail ];
1734 }
1735
1763 public static function generateRollback( $rev, IContextSource $context = null,
1764 $options = [ 'verify' ]
1765 ) {
1766 if ( $context === null ) {
1768 }
1769
1770 $editCount = false;
1771 if ( in_array( 'verify', $options, true ) ) {
1772 $editCount = self::getRollbackEditCount( $rev, true );
1773 if ( $editCount === false ) {
1774 return '';
1775 }
1776 }
1777
1778 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1779
1780 if ( !in_array( 'noBrackets', $options, true ) ) {
1781 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1782 }
1783
1784 return '<span class="mw-rollback-link">' . $inner . '</span>';
1785 }
1786
1802 public static function getRollbackEditCount( $rev, $verify ) {
1804 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1805 // Nothing has happened, indicate this by returning 'null'
1806 return null;
1807 }
1808
1809 $dbr = wfGetDB( DB_REPLICA );
1810
1811 // Up to the value of $wgShowRollbackEditCount revisions are counted
1812 $res = $dbr->select(
1813 'revision',
1814 [ 'rev_user_text', 'rev_deleted' ],
1815 // $rev->getPage() returns null sometimes
1816 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1817 __METHOD__,
1818 [
1819 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1820 'ORDER BY' => 'rev_timestamp DESC',
1821 'LIMIT' => $wgShowRollbackEditCount + 1
1822 ]
1823 );
1824
1825 $editCount = 0;
1826 $moreRevs = false;
1827 foreach ( $res as $row ) {
1828 if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1829 if ( $verify &&
1830 ( $row->rev_deleted & Revision::DELETED_TEXT
1831 || $row->rev_deleted & Revision::DELETED_USER
1832 ) ) {
1833 // If the user or the text of the revision we might rollback
1834 // to is deleted in some way we can't rollback. Similar to
1835 // the sanity checks in WikiPage::commitRollback.
1836 return false;
1837 }
1838 $moreRevs = true;
1839 break;
1840 }
1841 $editCount++;
1842 }
1843
1844 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1845 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1846 // and there weren't any other revisions. That means that the current user is the only
1847 // editor, so we can't rollback
1848 return false;
1849 }
1850 return $editCount;
1851 }
1852
1862 public static function buildRollbackLink( $rev, IContextSource $context = null,
1863 $editCount = false
1864 ) {
1866
1867 // To config which pages are affected by miser mode
1868 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1869
1870 if ( $context === null ) {
1872 }
1873
1874 $title = $rev->getTitle();
1875 $query = [
1876 'action' => 'rollback',
1877 'from' => $rev->getUserText(),
1878 'token' => $context->getUser()->getEditToken( 'rollback' ),
1879 ];
1880 $attrs = [
1881 'data-mw' => 'interface',
1882 'title' => $context->msg( 'tooltip-rollback' )->text(),
1883 ];
1884 $options = [ 'known', 'noclasses' ];
1885
1886 if ( $context->getRequest()->getBool( 'bot' ) ) {
1887 $query['bot'] = '1';
1888 $query['hidediff'] = '1'; // bug 15999
1889 }
1890
1891 $disableRollbackEditCount = false;
1892 if ( $wgMiserMode ) {
1893 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1894 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1895 $disableRollbackEditCount = true;
1896 break;
1897 }
1898 }
1899 }
1900
1901 if ( !$disableRollbackEditCount
1902 && is_int( $wgShowRollbackEditCount )
1904 ) {
1905 if ( !is_numeric( $editCount ) ) {
1906 $editCount = self::getRollbackEditCount( $rev, false );
1907 }
1908
1909 if ( $editCount > $wgShowRollbackEditCount ) {
1910 $html = $context->msg( 'rollbacklinkcount-morethan' )
1911 ->numParams( $wgShowRollbackEditCount )->parse();
1912 } else {
1913 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1914 }
1915
1916 return self::link( $title, $html, $attrs, $query, $options );
1917 } else {
1918 $html = $context->msg( 'rollbacklink' )->escaped();
1919 return self::link( $title, $html, $attrs, $query, $options );
1920 }
1921 }
1922
1941 public static function formatTemplates( $templates, $preview = false,
1942 $section = false, $more = null
1943 ) {
1944 wfDeprecated( __METHOD__, '1.28' );
1945
1946 $type = false;
1947 if ( $preview ) {
1948 $type = 'preview';
1949 } elseif ( $section ) {
1950 $type = 'section';
1951 }
1952
1953 if ( $more instanceof Message ) {
1954 $more = $more->toString();
1955 }
1956
1957 $formatter = new TemplatesOnThisPageFormatter(
1959 MediaWikiServices::getInstance()->getLinkRenderer()
1960 );
1961 return $formatter->format( $templates, $type, $more );
1962 }
1963
1972 public static function formatHiddenCategories( $hiddencats ) {
1973
1974 $outText = '';
1975 if ( count( $hiddencats ) > 0 ) {
1976 # Construct the HTML
1977 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1978 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1979 $outText .= "</div><ul>\n";
1980
1981 foreach ( $hiddencats as $titleObj ) {
1982 # If it's hidden, it must exist - no need to check with a LinkBatch
1983 $outText .= '<li>'
1984 . self::link( $titleObj, null, [], [], 'known' )
1985 . "</li>\n";
1986 }
1987 $outText .= '</ul>';
1988 }
1989 return $outText;
1990 }
1991
2002 public static function formatSize( $size ) {
2003 wfDeprecated( __METHOD__, '1.28' );
2004
2006 return htmlspecialchars( $wgLang->formatSize( $size ) );
2007 }
2008
2024 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2025 $message = wfMessage( "tooltip-$name", $msgParams );
2026 if ( !$message->exists() ) {
2027 $tooltip = false;
2028 } else {
2029 $tooltip = $message->text();
2030 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2031 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2032 # Message equal to '-' means suppress it.
2033 if ( $tooltip == '-' ) {
2034 $tooltip = false;
2035 }
2036 }
2037
2038 if ( $options == 'withaccess' ) {
2039 $accesskey = self::accesskey( $name );
2040 if ( $accesskey !== false ) {
2041 // Should be build the same as in jquery.accessKeyLabel.js
2042 if ( $tooltip === false || $tooltip === '' ) {
2043 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2044 } else {
2045 $tooltip .= wfMessage( 'word-separator' )->text();
2046 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2047 }
2048 }
2049 }
2050
2051 return $tooltip;
2052 }
2053
2054 public static $accesskeycache;
2055
2067 public static function accesskey( $name ) {
2068 if ( isset( self::$accesskeycache[$name] ) ) {
2069 return self::$accesskeycache[$name];
2070 }
2071
2072 $message = wfMessage( "accesskey-$name" );
2073
2074 if ( !$message->exists() ) {
2075 $accesskey = false;
2076 } else {
2077 $accesskey = $message->plain();
2078 if ( $accesskey === '' || $accesskey === '-' ) {
2079 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2080 # attribute, but this is broken for accesskey: that might be a useful
2081 # value.
2082 $accesskey = false;
2083 }
2084 }
2085
2086 self::$accesskeycache[$name] = $accesskey;
2087 return self::$accesskeycache[$name];
2088 }
2089
2103 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2104 $canHide = $user->isAllowed( 'deleterevision' );
2105 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2106 return '';
2107 }
2108
2109 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2110 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2111 } else {
2112 if ( $rev->getId() ) {
2113 // RevDelete links using revision ID are stable across
2114 // page deletion and undeletion; use when possible.
2115 $query = [
2116 'type' => 'revision',
2117 'target' => $title->getPrefixedDBkey(),
2118 'ids' => $rev->getId()
2119 ];
2120 } else {
2121 // Older deleted entries didn't save a revision ID.
2122 // We have to refer to these by timestamp, ick!
2123 $query = [
2124 'type' => 'archive',
2125 'target' => $title->getPrefixedDBkey(),
2126 'ids' => $rev->getTimestamp()
2127 ];
2128 }
2130 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2131 }
2132 }
2133
2144 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2145 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2146 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2147 $html = wfMessage( $msgKey )->escaped();
2148 $tag = $restricted ? 'strong' : 'span';
2149 $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2150 return Xml::tags(
2151 $tag,
2152 [ 'class' => 'mw-revdelundel-link' ],
2153 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2154 );
2155 }
2156
2166 public static function revDeleteLinkDisabled( $delete = true ) {
2167 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2168 $html = wfMessage( $msgKey )->escaped();
2169 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2170 return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2171 }
2172
2173 /* Deprecated methods */
2174
2184 public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = [] ) {
2185 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2186 # no attribute" instead of "output '' as value for attribute", this
2187 # would be three lines.
2188 $attribs = [
2189 'title' => self::titleAttrib( $name, 'withaccess', $msgParams ),
2190 'accesskey' => self::accesskey( $name )
2191 ];
2192 if ( $attribs['title'] === false ) {
2193 unset( $attribs['title'] );
2194 }
2195 if ( $attribs['accesskey'] === false ) {
2196 unset( $attribs['accesskey'] );
2197 }
2198 return $attribs;
2199 }
2200
2208 public static function tooltip( $name, $options = null ) {
2209 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2210 # no attribute" instead of "output '' as value for attribute", this
2211 # would be two lines.
2212 $tooltip = self::titleAttrib( $name, $options );
2213 if ( $tooltip === false ) {
2214 return '';
2215 }
2216 return Xml::expandAttributes( [
2217 'title' => $tooltip
2218 ] );
2219 }
2220
2221}
2222
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$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
Uploads have to be specially set up to be secure.
$wgMiserMode
Disable database-intensive features.
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
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.
wfFindFile( $title, $options=[])
Find a file.
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...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$wgUser
Definition Setup.php:806
if(! $wgRequest->checkUrlExtension()) if(isset($_SERVER[ 'PATH_INFO']) &&$_SERVER[ 'PATH_INFO'] !='') if(! $wgEnableAPI) $wgTitle
Definition api.php:68
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Marks HTML that shouldn't be escaped.
Definition HtmlArmor.php:28
static prettifyIP( $ip)
Prettify an IP for display to end users.
Definition IP.php:201
Some internal bits split of from Skin.php.
Definition Linker.php:34
static tocList( $toc, $lang=false)
Wraps the TOC in a table and provides the hide/collapse javascript.
Definition Linker.php:1645
static generateRollback( $rev, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition Linker.php:1763
static getInternalLinkAttributesObj( $nt, $unused=null, $class='', $title=false)
Get the appropriate HTML attributes to add to the "a" element of an internal link,...
Definition Linker.php:102
static getLinkAttributesInternal( $title, $class)
Common code for getLinkAttributesX functions.
Definition Linker.php:122
static makeMediaLinkFile(Title $title, $file, $html='')
Create a direct link to a given uploaded file.
Definition Linker.php:874
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition Linker.php:203
static fnamePart( $url)
Returns the filename part of an url.
Definition Linker.php:342
static tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition Linker.php:1615
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition Linker.php:984
static $accesskeycache
Definition Linker.php:2054
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:2024
static makeThumbLink2(Title $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="")
Definition Linker.php:624
static formatSize( $size)
Definition Linker.php:2002
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition Linker.php:2067
static getInterwikiLinkAttributes( $title, $unused=null, $class='external')
Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
Definition Linker.php:54
static formatAutocomments( $comment, $title=null, $local=false, $wikiId=null)
Converts autogenerated comments in edit summaries into section links.
Definition Linker.php:1212
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:915
static getLinkColour(LinkTarget $t, $threshold)
Return the CSS colour of a known link.
Definition Linker.php:147
static makeImageLink(Parser $parser, Title $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:415
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition Linker.php:255
static generateTOC( $tree, $lang=false)
Generate a table of contents from a section tree.
Definition Linker.php:1663
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition Linker.php:362
static userToolLinksRedContribs( $userId, $userText, $edits=null)
Alias for userToolLinks( $userId, $userText, true );.
Definition Linker.php:1073
static buildRollbackLink( $rev, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition Linker.php:1862
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition Linker.php:746
static blockLink( $userId, $userText)
Definition Linker.php:1095
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition Linker.php:2166
static getRollbackEditCount( $rev, $verify)
This function will return the number of revisions which a rollback would revert and,...
Definition Linker.php:1802
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition Linker.php:1439
static revComment(Revision $rev, $local=false, $isPublic=false)
Wrap and format the given revision's comment block, if the current user is allowed to view it.
Definition Linker.php:1550
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition Linker.php:38
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='')
Make appropriate markup for a link to the current article.
Definition Linker.php:277
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition Linker.php:831
static tocIndent()
Add another level to the Table of Contents.
Definition Linker.php:1589
static revUserLink( $rev, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition Linker.php:1119
static commentBlock( $comment, $title=null, $local=false, $wikiId=null)
Wrap a comment in standard punctuation and formatting if it's non-empty, otherwise return empty strin...
Definition Linker.php:1525
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[])
Returns the attributes for the tooltip and access key.
Definition Linker.php:2184
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition Linker.php:300
static revUserTools( $rev, $isPublic=false)
Generate a user tool link cluster if the current user is allowed to view it.
Definition Linker.php:1141
static emailLink( $userId, $userText)
Definition Linker.php:1106
static makeThumbLinkObj(Title $title, $file, $label='', $alt, $align='right', $params=[], $framed=false, $manualthumb="")
Make HTML for a thumbnail including image, border and caption.
Definition Linker.php:598
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition Linker.php:1972
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:1722
const TOOL_LINKS_EMAIL
Definition Linker.php:39
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition Linker.php:1017
static formatRevisionSize( $size)
Definition Linker.php:1573
static getInternalLinkAttributes( $title, $unused=null, $class='')
Get the appropriate HTML attributes to add to the "a" element of an internal link.
Definition Linker.php:80
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition Linker.php:2208
static userTalkLink( $userId, $userText)
Definition Linker.php:1083
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:1305
static makeMediaLinkObj( $title, $html='', $time=false)
Create a direct link to a given uploaded file.
Definition Linker.php:857
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition Linker.php:934
static makeCommentLink(Title $title, $text, $wikiId=null, $options=[])
Generates a link to the given Title.
Definition Linker.php:1413
static normaliseSpecialPage(LinkTarget $target)
Definition Linker.php:321
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition Linker.php:1701
static formatTemplates( $templates, $preview=false, $section=false, $more=null)
Definition Linker.php:1941
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition Linker.php:1600
static getImageLinkMTOParams( $frameParams, $query='', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition Linker.php:559
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition Linker.php:2144
static tocLineEnd()
End a Table Of Contents line.
Definition Linker.php:1633
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:1180
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false)
Make a "broken" link to an image.
Definition Linker.php:781
static getRevDeleteLink(User $user, Revision $rev, Title $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition Linker.php:2103
MediaWikiServices is the service locator for the application scope of MediaWiki.
The Message class provides methods which fulfil two basic services:
Definition Message.php:159
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:70
static singleton()
Get a RepoGroup instance.
Definition RepoGroup.php:59
static getMain()
Static methods.
const DELETED_USER
Definition Revision.php:87
const DELETED_TEXT
Definition Revision.php:85
const DELETED_RESTRICTED
Definition Revision.php:88
const RAW
Definition Revision.php:94
const DELETED_COMMENT
Definition Revision.php:86
const FOR_THIS_USER
Definition Revision.php:93
static resolveAlias( $alias)
Given a special page name with a possible subpage, return an array where the first element is the spe...
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
static getTitleValueFor( $name, $subpage=false, $fragment='')
Get a localised TitleValue object for a specified special page name.
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Handles formatting for the "templates used on this page" lists.
Represents a title within MediaWiki.
Definition Title.php:36
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:48
static getForeignURL( $wikiID, $page, $fragmentId=null)
Convenience to get a url to a page on a foreign wiki.
Definition WikiMap.php:168
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition Xml.php:67
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition Xml.php:131
$res
Definition database.txt:21
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------ Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server. Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It 's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use. Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves. The master writes thequery to the binlog when the transaction is committed. The slaves pollthe binlog and start executing the query as soon as it appears. They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes. Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load. MediaWiki 's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database. All edits and other write operations will berefused, with an error returned to the user. This gives the slaves achance to catch up. Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order. A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests. This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it. Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in "lagged slave mode". Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode(). The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time. Multi-row INSERT ...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it 's not practical to guarantee a low-lagenvironment. Lag will usually be less than one second, but mayoccasionally be up to 30 seconds. For scalability, it 's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer. So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn 't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum. In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------ Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks. By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent. Locks willbe held from the time when the query is done until the commit. So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction. Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical reasons
Definition design.txt:27
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition design.txt:56
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could change
const NS_USER
Definition Defines.php:58
const NS_FILE
Definition Defines.php:62
const NS_MAIN
Definition Defines.php:56
const NS_SPECIAL
Definition Defines.php:45
const NS_MEDIA
Definition Defines.php:44
const NS_USER_TALK
Definition Defines.php:59
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:249
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead $parser
Definition hooks.txt:2259
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition hooks.txt:2568
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1752
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped $pre
Definition hooks.txt:1552
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:986
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1096
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template to be included in the link
Definition hooks.txt:2902
null means default & $customAttribs
Definition hooks.txt:1939
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped true if there is text before this autocomment $auto
Definition hooks.txt:1554
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2710
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor' $rcid is used in generating this variable which contains information about the new such as the revision s whether the revision was marked as a minor edit or not
Definition hooks.txt:1207
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition hooks.txt:2207
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:1949
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition hooks.txt:1033
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:1957
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:2900
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition hooks.txt:1958
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition hooks.txt:2543
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition hooks.txt:2534
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1595
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition hooks.txt:1990
see documentation in includes Linker php for Linker::makeImageLink & $handlerParams
Definition hooks.txt:1750
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:2901
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1734
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
$comment
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
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:50
controlled by $wgMainCacheType controlled by $wgParserCacheType controlled by $wgMessageCacheType If you set CACHE_NONE to one of the three control default value for MediaWiki still create a but requests to it are no ops and we always fall through to the database If the cache daemon can t be it should also disable itself fairly smoothly By $wgMemc is used but when it is $parserMemc or $messageMemc this is mentioned below
Definition memcached.txt:96
const DB_REPLICA
Definition defines.php:22
$params
if(!isset( $args[0])) $lang