Debian Codegraph @

includes/OutputTransform/Stages/HandleSectionLinks.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\OutputTransform\Stages;
4
5 use LogicException;
6 use MediaWiki\Config\ServiceOptions;
7 use MediaWiki\Context\RequestContext;
8 use MediaWiki\Html\Html;
9 use MediaWiki\Html\HtmlHelper;
10 use MediaWiki\MainConfigNames;
11 use MediaWiki\OutputTransform\ContentTextTransformStage;
12 use MediaWiki\Parser\ParserOptions;
13 use MediaWiki\Parser\ParserOutput;
14 use MediaWiki\Parser\ParserOutputFlags;
15 use MediaWiki\Parser\Sanitizer;
16 use MediaWiki\Title\TitleFactory;
17 use Psr\Log\LoggerInterface;
18 use Skin;
19
20 /**
21 * Add anchors and other heading formatting, and replace the section link placeholders.
22 * @internal
23 */
24 class HandleSectionLinks extends ContentTextTransformStage {
25 private const EDITSECTION_REGEX = '#<mw:editsection page="(.*?)" section="(.*?)">(.*?)</mw:editsection>#s';
26 private const HEADING_REGEX =
27 '/<H(?P<level>[1-6])(?P<attrib>(?:[^\'">]*|"([^"]*)"|\'([^\']*)\')*>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i';
28
29 private TitleFactory $titleFactory;
30
31 /** @internal */
32 public const CONSTRUCTOR_OPTIONS = [
33 MainConfigNames::ParserEnableLegacyHeadingDOM, // For HandleSectionLinks
34 ];
35
36 public function __construct(
37 ServiceOptions $options, LoggerInterface $logger, TitleFactory $titleFactory
38 ) {
39 parent::__construct( $options, $logger );
40 $this->titleFactory = $titleFactory;
41 }
42
43 public function shouldRun( ParserOutput $po, ?ParserOptions $popts, array $options = [] ): bool {
44 $isParsoid = $options['isParsoidContent'] ?? false;
45 return !$isParsoid;
46 }
47
48 protected function transformText( string $text, ParserOutput $po, ?ParserOptions $popts, array &$options ): string {
49 $text = $this->replaceHeadings( $text, $options );
50
51 if (
52 ( $options['enableSectionEditLinks'] ?? true ) &&
53 !$po->getOutputFlag( ParserOutputFlags::NO_SECTION_EDIT_LINKS )
54 ) {
55 return $this->addSectionLinks( $text, $po, $options );
56 } else {
57 return preg_replace( self::EDITSECTION_REGEX, '', $text );
58 }
59 }
60
61 private function replaceHeadings( string $text, array $options ): string {
62 $skin = $this->resolveSkin( $options );
63 $useLegacyHeading = $this->options->get( MainConfigNames::ParserEnableLegacyHeadingDOM );
64 if ( $skin && !$skin->getOptions()['supportsMwHeading'] ) {
65 $useLegacyHeading = true;
66 }
67 $needToCheckExistingWrappers = preg_match( '/class="[^"]*\bmw-heading\b[^"]*"/', $text );
68
69 return preg_replace_callback( self::HEADING_REGEX, function ( $m ) use (
70 $useLegacyHeading, $needToCheckExistingWrappers, $text
71 ) {
72 // Parse attributes out of the <h#> tag. Do not actually use HtmlHelper's output,
73 // because EDITSECTION_REGEX is sensitive to quotes in HTML serialization.
74 $attrs = [];
75 HtmlHelper::modifyElements(
76 $m[0][0],
77 static fn ( $node ) => in_array( $node->name, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ] ),
78 static function ( $node ) use ( &$attrs ) {
79 $attrs = $node->attrs->getValues();
80 return $node;
81 }
82 );
83
84 if ( !isset( $attrs['data-mw-anchor'] ) ) {
85 return $m[0][0];
86 }
87
88 $anchor = $attrs['data-mw-anchor'];
89 $fallbackAnchor = $attrs['data-mw-fallback-anchor'] ?? false;
90 unset( $attrs['data-mw-anchor'] );
91 unset( $attrs['data-mw-fallback-anchor'] );
92
93 // Split the heading content from the section edit link placeholder
94 $editlink = '';
95 $contents = preg_replace_callback( self::EDITSECTION_REGEX, static function ( $mm ) use ( &$editlink ) {
96 $editlink = $mm[0];
97 return '';
98 }, $m['header'][0] );
99
100 if ( !$useLegacyHeading ) {
101 $wrapperType = 'mwheading';
102
103 // Do not add another wrapper if an existing wrapper if present.
104 // This is to support DiscussionTools adding wrappers itself.
105 // TODO: This is obviously bad and unreliable. One day, this code will use DOM transforms,
106 // and can just check ->parentNode like in HandleParsoidSectionLinks.
107 if ( $needToCheckExistingWrappers ) {
108 $textBeforeMatch = substr( $text, 0, $m[0][1] );
109 $openOffset = strrpos( $textBeforeMatch, '<div class="mw-heading' );
110 if ( $openOffset !== false ) {
111 $closeOffset = strpos( $textBeforeMatch, '</div>', $openOffset );
112 if ( $closeOffset === false ) {
113 // Looks like we're already inside a wrapper
114 $wrapperType = 'none';
115 }
116 }
117 }
118
119 // Do not add the wrapper if the heading has attributes generated from wikitext (T353489).
120 // In this case it's also guaranteed that there's no edit link, so we don't need wrappers.
121 foreach ( $attrs as $name => $value ) {
122 if ( !Sanitizer::isReservedDataAttribute( $name ) ) {
123 $wrapperType = 'none';
124 }
125 }
126
127 } else {
128 $wrapperType = 'legacy';
129 }
130
131 return $this->makeHeading(
132 (int)$m['level'][0],
133 $attrs,
134 $anchor,
135 $contents,
136 $editlink,
137 $fallbackAnchor,
138 $wrapperType
139 );
140 }, $text, -1, $count, PREG_OFFSET_CAPTURE );
141 }
142
143 /**
144 * @param int $level The level of the headline (1-6)
145 * @param array $attrs HTML attributes
146 * @param string $anchor The anchor to give the headline (the bit after the #)
147 * @param string $html HTML for the text of the header
148 * @param string $link HTML to add for the section edit link
149 * @param string|false $fallbackAnchor A second, optional anchor to give for
150 * backward compatibility (false to omit)
151 * @param string $wrapperType 'legacy', 'mwheading' or 'none'
152 * @return string HTML headline
153 */
154 private function makeHeading( $level, $attrs, $anchor, $html,
155 $link, $fallbackAnchor, string $wrapperType
156 ) {
157 $anchorEscaped = htmlspecialchars( $anchor, ENT_COMPAT );
158 $idAttr = " id=\"$anchorEscaped\"";
159 if ( isset( $attrs['id'] ) ) {
160 $idAttr = '';
161 }
162 $fallback = '';
163 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
164 $fallbackAnchor = htmlspecialchars( $fallbackAnchor, ENT_COMPAT );
165 $fallback = "<span id=\"$fallbackAnchor\"></span>";
166 }
167
168 switch ( $wrapperType ) {
169 case 'legacy':
170 return "<h$level" . Html::expandAttributes( $attrs ) . ">"
171 . "$fallback<span class=\"mw-headline\"$idAttr>$html</span>"
172 . $link
173 . "</h$level>";
174 case 'mwheading':
175 return "<div class=\"mw-heading mw-heading$level\">"
176 . "<h$level$idAttr" . Html::expandAttributes( $attrs ) . ">$fallback$html</h$level>"
177 . $link
178 . "</div>";
179 case 'none':
180 return "<h$level$idAttr" . Html::expandAttributes( $attrs ) . ">$fallback$html</h$level>"
181 . $link;
182 default:
183 throw new LogicException( "Bad wrapper type: $wrapperType" );
184 }
185 }
186
187 private function addSectionLinks( string $text, ParserOutput $po, array $options ): string {
188 $skin = $this->resolveSkin( $options );
189 if ( !$skin ) {
190 // Should be unreachable
191 return $text;
192 }
193 $titleText = $po->getTitleText();
194 return preg_replace_callback( self::EDITSECTION_REGEX, function ( $m ) use ( $skin, $titleText ) {
195 $editsectionPage = $this->titleFactory->newFromTextThrow( htmlspecialchars_decode( $m[1] ) );
196 $editsectionSection = htmlspecialchars_decode( $m[2] );
197 $editsectionContent = Sanitizer::decodeCharReferences( $m[3] );
198 return $skin->doEditSectionLink( $editsectionPage, $editsectionSection, $editsectionContent,
199 $skin->getLanguage() );
200 }, $text );
201 }
202
203 /**
204 * Extracts the skin from the $options array, with a fallback on request context skin
205 * @param array $options
206 * @return ?Skin
207 */
208 private function resolveSkin( array $options ): ?Skin {
209 $skin = $options[ 'skin' ] ?? null;
210 if ( !$skin ) {
211 if ( defined( 'MW_NO_SESSION' ) ) {
212 return null;
213 }
214 // T348853 passing $skin will be mandatory in the future
215 $skin = RequestContext::getMain()->getSkin();
216 }
217 return $skin;
218 }
219 }