Debian Codegraph @

vendor/wikimedia/parsoid/src/Wt2Html/DOM/Processors/AddMetaData.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Wt2Html\DOM\Processors;
5
6 use Closure;
7 use DateTime;
8 use Wikimedia\Parsoid\Config\Env;
9 use Wikimedia\Parsoid\DOM\Element;
10 use Wikimedia\Parsoid\DOM\Node;
11 use Wikimedia\Parsoid\Parsoid;
12 use Wikimedia\Parsoid\Utils\DOMCompat;
13 use Wikimedia\Parsoid\Utils\DOMDataUtils;
14 use Wikimedia\Parsoid\Utils\DOMUtils;
15 use Wikimedia\Parsoid\Utils\PHPUtils;
16 use Wikimedia\Parsoid\Utils\Utils;
17 use Wikimedia\Parsoid\Wt2Html\DOMPostProcessor;
18 use Wikimedia\Parsoid\Wt2Html\Wt2HtmlDOMProcessor;
19
20 class AddMetaData implements Wt2HtmlDOMProcessor {
21 private array $metadataMap;
22 private ?DOMPostProcessor $parentPipeline;
23
24 public function __construct( ?DOMPostProcessor $domPP ) {
25 $this->parentPipeline = $domPP;
26
27 // map from mediawiki metadata names to RDFa property names
28 $this->metadataMap = [
29 'ns' => [
30 'property' => 'mw:pageNamespace',
31 'content' => '%d',
32 ],
33 'id' => [
34 'property' => 'mw:pageId',
35 'content' => '%d',
36 ],
37
38 // DO NOT ADD rev_user, rev_userid, and rev_comment (See T125266)
39
40 // 'rev_revid' is used to set the overall subject of the document, we don't
41 // need to add a specific <meta> or <link> element for it.
42
43 'rev_parentid' => [
44 'rel' => 'dc:replaces',
45 'resource' => 'mwr:revision/%d',
46 ],
47 'rev_timestamp' => [
48 'property' => 'dc:modified',
49 'content' => static function ( $m ) {
50 # Convert from TS_MW ("mediawiki timestamp") format
51 $dt = DateTime::createFromFormat( 'YmdHis', $m['rev_timestamp'] );
52 # Note that DateTime::ISO8601 is not actually ISO8601, alas.
53 return $dt->format( 'Y-m-d\TH:i:s.000\Z' );
54 },
55 ],
56 'rev_sha1' => [
57 'property' => 'mw:revisionSHA1',
58 'content' => '%s',
59 ]
60 ];
61 }
62
63 private function updateBodyClasslist( Element $body, Env $env ): void {
64 $dir = $env->getPageConfig()->getPageLanguageDir();
65 $bodyCL = DOMCompat::getClassList( $body );
66 $bodyCL->add( 'mw-content-' . $dir );
67 $bodyCL->add( 'sitedir-' . $dir );
68 $bodyCL->add( $dir );
69 $body->setAttribute( 'dir', $dir );
70
71 // Set 'mw-body-content' directly on the body.
72 // This is the designated successor for #bodyContent in core skins.
73 $bodyCL->add( 'mw-body-content' );
74 // Set 'parsoid-body' to add the desired layout styling from Vector.
75 $bodyCL->add( 'parsoid-body' );
76 // Also, add the 'mediawiki' class.
77 // Some MediaWiki:Common.css seem to target this selector.
78 $bodyCL->add( 'mediawiki' );
79 // Set 'mw-parser-output' directly on the body.
80 // Templates target this class as part of the TemplateStyles RFC
81 // FIXME: This isn't expected to be found on the same element as the
82 // body class above, since some css targets it as a descendant.
83 // In visual diff'ing, we migrate the body contents to a wrapper div
84 // with this class to reduce visual differences. Consider getting
85 // rid of it.
86 $bodyCL->add( 'mw-parser-output' );
87
88 // Set the parsoid version on the body, for consistency with
89 // the wrapper div.
90 $body->setAttribute( 'data-mw-parsoid-version', Parsoid::version() );
91 $body->setAttribute( 'data-mw-html-version', Parsoid::defaultHTMLVersion() );
92 }
93
94 /**
95 * @inheritDoc
96 */
97 public function run(
98 Env $env, Node $root, array $options = [], bool $atTopLevel = false
99 ): void {
100 $title = $env->getContextTitle();
101 $document = $root->ownerDocument;
102
103 // Set the charset in the <head> first.
104 // This also adds the <head> element if it was missing.
105 DOMUtils::appendToHead( $document, 'meta', [ 'charset' => 'utf-8' ] );
106
107 // add mw: and mwr: RDFa prefixes
108 $prefixes = [
109 'dc: http://purl.org/dc/terms/',
110 'mw: http://mediawiki.org/rdf/'
111 ];
112 $document->documentElement->setAttribute( 'prefix', implode( ' ', $prefixes ) );
113
114 // (From wfParseUrl in core:)
115 // Protocol-relative URLs are handled really badly by parse_url().
116 // It's so bad that the easiest way to handle them is to just prepend
117 // 'https:' and strip the protocol out later.
118 $baseURI = $env->getSiteConfig()->baseURI();
119 $wasRelative = substr( $baseURI, 0, 2 ) == '//';
120 if ( $wasRelative ) {
121 $baseURI = "https:$baseURI";
122 }
123 // add 'https://' to baseURI if it was missing
124 $pu = parse_url( $baseURI );
125 $mwrPrefix = ( !empty( $pu['scheme'] ) ? '' : 'https://' ) .
126 $baseURI . 'Special:Redirect/';
127
128 ( DOMCompat::getHead( $document ) )->setAttribute( 'prefix', 'mwr: ' . $mwrPrefix );
129
130 // add <head> content based on page meta data:
131
132 // Add page / revision metadata to the <head>
133 // PORT-FIXME: We will need to do some refactoring to eliminate
134 // this hardcoding. Probably even merge this into metadataMap
135 $pageConfig = $env->getPageConfig();
136 $revProps = [
137 'id' => $pageConfig->getPageId(),
138 'ns' => $title->getNamespace(),
139 'rev_parentid' => $pageConfig->getParentRevisionId(),
140 'rev_revid' => $pageConfig->getRevisionId(),
141 'rev_sha1' => $pageConfig->getRevisionSha1(),
142 'rev_timestamp' => $pageConfig->getRevisionTimestamp()
143 ];
144 foreach ( $revProps as $key => $value ) {
145 // generate proper attributes for the <meta> or <link> tag
146 if ( $value === null || $value === '' || !isset( $this->metadataMap[$key] ) ) {
147 continue;
148 }
149
150 $attrs = [];
151 $mdm = $this->metadataMap[$key];
152
153 /** FIXME: The JS side has a bunch of other checks here */
154
155 foreach ( $mdm as $k => $v ) {
156 // evaluate a function, or perform sprintf-style formatting, or
157 // use string directly, depending on value in metadataMap
158 if ( $v instanceof Closure ) {
159 $v = $v( $revProps );
160 } elseif ( strpos( $v, '%' ) !== false ) {
161 // @phan-suppress-next-line PhanPluginPrintfVariableFormatString
162 $v = sprintf( $v, $value );
163 }
164 $attrs[$k] = $v;
165 }
166
167 // <link> is used if there's a resource or href attribute.
168 DOMUtils::appendToHead( $document,
169 isset( $attrs['resource'] ) || isset( $attrs['href'] ) ? 'link' : 'meta',
170 $attrs
171 );
172 }
173
174 if ( $revProps['rev_revid'] ) {
175 $document->documentElement->setAttribute(
176 'about', $mwrPrefix . 'revision/' . $revProps['rev_revid']
177 );
178 }
179
180 // Normalize before comparison
181 if ( $title->isSameLinkAs( $env->getSiteConfig()->mainPageLinkTarget() ) ) {
182 DOMUtils::appendToHead( $document, 'meta', [
183 'property' => 'isMainPage',
184 'content' => 'true' /* HTML attribute values should be strings */
185 ] );
186 }
187
188 // Set the parsoid content-type strings
189 // FIXME: Should we be using http-equiv for this?
190 DOMUtils::appendToHead( $document, 'meta', [
191 'property' => 'mw:htmlVersion',
192 'content' => $env->getOutputContentVersion()
193 ]
194 );
195 // Temporary backward compatibility for clients
196 // This could be skipped if we support a version downgrade path
197 // with a major version bump.
198 DOMUtils::appendToHead( $document, 'meta', [
199 'property' => 'mw:html:version',
200 'content' => $env->getOutputContentVersion()
201 ]
202 );
203
204 $expTitle = explode( '/', $title->getPrefixedDBKey() );
205 $expTitle = array_map( static function ( $comp ) {
206 return PHPUtils::encodeURIComponent( $comp );
207 }, $expTitle );
208
209 DOMUtils::appendToHead( $document, 'link', [
210 'rel' => 'dc:isVersionOf',
211 'href' => $env->getSiteConfig()->baseURI() . implode( '/', $expTitle )
212 ] );
213
214 // Add base href pointing to the wiki root
215 DOMUtils::appendToHead( $document, 'base', [
216 'href' => $env->getSiteConfig()->baseURI()
217 ] );
218
219 // Stick data attributes in the head
220 if ( $env->pageBundle ) {
221 DOMDataUtils::injectPageBundle( $document, DOMDataUtils::getPageBundle( $document ) );
222 }
223
224 // PageConfig guarantees language will always be non-null.
225 $lang = $env->getPageConfig()->getPageLanguageBcp47();
226 $body = DOMCompat::getBody( $document );
227 $body->setAttribute( 'lang', $lang->toBcp47Code() );
228 $this->updateBodyClasslist( $body, $env );
229 // T324431: Note that this is *not* the displaytitle, and that
230 // the title element contents are plaintext *not* HTML
231 DOMCompat::setTitle( $document, $title->getPrefixedText() );
232 $env->getSiteConfig()->exportMetadataToHeadBcp47(
233 $document, $env->getMetadata(),
234 $title->getPrefixedText(), $lang
235 );
236
237 // Indicate whether LanguageConverter is enabled, so that downstream
238 // caches can split on variant (if necessary)
239 DOMUtils::appendToHead( $document, 'meta', [
240 'http-equiv' => 'content-language',
241 // Note that this is "wrong": we should be returning
242 // $env->htmlContentLanguageBcp47()->toBcp47Code() directly
243 // but for back-compat we'll return the "old" mediawiki-internal
244 // code for now
245 'content' => Utils::bcp47ToMwCode( # T323052: remove this call
246 $env->htmlContentLanguageBcp47()->toBcp47Code()
247 ),
248 ]
249 );
250 DOMUtils::appendToHead( $document, 'meta', [
251 'http-equiv' => 'vary',
252 'content' => $env->htmlVary()
253 ]
254 );
255
256 if ( $env->profiling() && $this->parentPipeline ) {
257 $body = DOMCompat::getBody( $document );
258 $body->appendChild( $body->ownerDocument->createTextNode( "\n" ) );
259 $body->appendChild( $body->ownerDocument->createComment( $this->parentPipeline->getTimeProfile() ) );
260 $body->appendChild( $body->ownerDocument->createTextNode( "\n" ) );
261 }
262
263 if ( $env->hasDumpFlag( 'wt2html:limits' ) ) {
264 /*
265 * PORT-FIXME: Not yet implemented
266 $env->printWt2HtmlResourceUsage( [
267 'HTML Size' => strlen( DOMCompat::getOuterHTML( $document->documentElement ) )
268 ] );
269 */
270 }
271 }
272 }