Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.56% covered (warning)
59.56%
81 / 136
56.25% covered (warning)
56.25%
9 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Utils
59.56% covered (warning)
59.56%
81 / 136
56.25% covered (warning)
56.25%
9 / 16
200.39
0.00% covered (danger)
0.00%
0 / 1
 convert
66.67% covered (warning)
66.67%
8 / 12
0.00% covered (danger)
0.00%
0 / 1
15.48
 wikitextToHTML
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 htmlToWikitext
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 htmlToPlaintext
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 commentParser
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
5.20
 createDOM
54.84% covered (warning)
54.84%
17 / 31
0.00% covered (danger)
0.00%
0 / 1
7.30
 onFlowAddModules
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 saferSaveXML
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getInnerHtml
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 getOuterHtml
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 encodeHeadInfo
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 decodeHeadInfo
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 getParsoidVersion
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 createRelativeTitle
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 getLanguageConverter
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getConvertedTitle
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace Flow\Conversion;
4
5use DOMDocument;
6use DOMElement;
7use DOMNode;
8use Flow\Exception\NoParserException;
9use Flow\Exception\WikitextException;
10use Flow\Parsoid\ContentFixer;
11use Flow\Parsoid\Fixer\EmptyNodeFixer;
12use MediaWiki\Content\TextContent;
13use MediaWiki\Content\WikitextContent;
14use MediaWiki\Context\RequestContext;
15use MediaWiki\Html\Html;
16use MediaWiki\Language\ILanguageConverter;
17use MediaWiki\Language\Language;
18use MediaWiki\MediaWikiServices;
19use MediaWiki\Output\OutputPage;
20use MediaWiki\Parser\ParserOptions;
21use MediaWiki\Parser\Sanitizer;
22use MediaWiki\Title\Title;
23
24abstract class Utils {
25
26    public const PARSOID_VERSION = '2.0.0';
27
28    /**
29     * Convert from/to wikitext <=> html or topic-title-wikitext => topic-title-html.
30     * Only these pairs are supported.  html => wikitext requires Parsoid, and
31     * topic-title-html => topic-title-wikitext is not supported.
32     *
33     * @param string $from Format of content to convert: html|wikitext|topic-title-wikitext
34     * @param string $to Format to convert to: html|wikitext|topic-title-html
35     * @param string $content
36     * @param Title $title
37     * @return string
38     * @throws WikitextException When the requested conversion is unsupported
39     * @throws NoParserException When the conversion fails
40     * @return-taint none
41     */
42    public static function convert( $from, $to, $content, Title $title ) {
43        if ( $from === $to || $content === '' ) {
44            return $content;
45        }
46
47        if ( $from === 'wt' ) {
48            $from = 'wikitext';
49        }
50
51        if ( $from == 'wikitext' && $to == 'html' ) {
52            return self::wikitextToHTML( $content, $title );
53        } elseif ( $from == 'html' && $to == 'wikitext' ) {
54            return self::htmlToWikitext( $content, $title );
55        } elseif ( $from === 'topic-title-wikitext' &&
56            ( $to === 'topic-title-html' || $to === 'topic-title-plaintext' ) ) {
57            // FIXME: links need to be proceed by findVariantLinks or equivant function
58            return self::getLanguageConverter()->convert( self::commentParser( $from, $to, $content ) );
59        } else {
60            return self::commentParser( $from, $to, $content );
61        }
62    }
63
64    /**
65     * @param string $wikitext
66     * @param Title $title
67     *
68     * @return string The converted wikitext to HTML
69     */
70    private static function wikitextToHTML( string $wikitext, Title $title ) {
71        $parserOptions = ParserOptions::newFromAnon();
72        $parserOptions->setRenderReason( __METHOD__ );
73        $parserOptions->setUseParsoid();
74
75        $parserFactory = MediaWikiServices::getInstance()->getParsoidParserFactory()->create();
76        $parserOutput = $parserFactory->parse( $wikitext, $title, $parserOptions );
77
78        // $parserOutput is body-only, but we want to retain a <body> wrapper
79        // So we'll convert to full-document form and modify the HTML ourselves
80        $pbpoc = MediaWikiServices::getInstance()->getPageBundleParserOutputConverter();
81        $pb = $pbpoc->htmlPageBundleFromParserOutput(
82            $parserOutput,
83            bodyOnly: false,
84        );
85        preg_match( "#<body[^>]*>(.*?)</body>#s", $pb->html, $html );
86
87        return $html[0];
88    }
89
90    /**
91     * @param string $html
92     * @param Title $title
93     *
94     * @return string The converted HTML to Wikitext
95     * @throws WikitextException When the conversion is unsupported
96     */
97    private static function htmlToWikitext( string $html, Title $title ) {
98        $transform = MediaWikiServices::getInstance()->getHtmlTransformFactory()
99            ->getHtmlToContentTransform( $html, $title );
100
101        $transform->setOptions( [
102            'contentmodel' => CONTENT_MODEL_WIKITEXT,
103            'offsetType' => 'byte'
104        ] );
105
106        /** @var TextContent $content */
107        $content = $transform->htmlToContent();
108
109        if ( !$content instanceof WikitextContent ) {
110            throw new WikitextException( 'Conversion to Wikitext failed' );
111        }
112
113        return trim( $content->getTextForSearchIndex() );
114    }
115
116    /**
117     * Basic conversion of html to plaintext for use in recent changes, history,
118     * and other places where a roundtrip is undesired.
119     *
120     * @param string $html
121     * @param Language $lang Language to use for truncation.
122     * @param int|null $truncateLength Maximum length in characters (including ellipses) or null for whole string.
123     * @return string plaintext
124     */
125    public static function htmlToPlaintext( $html, Language $lang, ?int $truncateLength = null ) {
126        $plain = trim( Sanitizer::stripAllTags( $html ) );
127
128        // Fallback to some large-ish value for truncation.
129        $truncateLength ??= 10000;
130
131        return $lang->truncateForVisual( $plain, $truncateLength );
132    }
133
134    /**
135     * Convert from/to topic-title-wikitext/topic-title-html using
136     * MediaWiki\CommentFormatter\CommentFormatter::formatLinks
137     *
138     * @param string $from Format of content to convert: topic-title-wikitext
139     * @param string $to Format of content to convert to: topic-title-html
140     * @param string $content Content to convert, in topic-title-wikitext format.
141     * @return string $content in HTML
142     * @throws WikitextException
143     */
144    protected static function commentParser( $from, $to, $content ) {
145        if (
146            $from !== 'topic-title-wikitext' ||
147            ( $to !== 'topic-title-html' && $to !== 'topic-title-plaintext' )
148        ) {
149            throw new WikitextException( "Conversion from '$from' to '$to' was requested, " .
150                "but this is not supported." );
151        }
152
153        $html = MediaWikiServices::getInstance()->getCommentFormatter()
154            ->formatLinks( Sanitizer::escapeHtmlAllowEntities( $content ) );
155        if ( $to === 'topic-title-plaintext' ) {
156            $lang = RequestContext::getMain()->getLanguage();
157            return self::htmlToPlaintext( $html, $lang );
158        } else {
159            return $html;
160        }
161    }
162
163    /**
164     * Turns given $content string into a DOMDocument object.
165     *
166     * Note that, by default, $content will be prefixed with <?xml encoding="utf-8"?> to force
167     * libxml to interpret the content as UTF-8. If for some reason you don't want this to happen,
168     * or you are certain that your input already has <?xml encoding="utf-8"?> or
169     * <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> , then you can disable
170     * this behavior by setting $utf8Fragment=false to disable this behavior.
171     *
172     * Some libxml errors are forgivable, libxml errors that aren't
173     * ignored will throw a WikitextException.
174     *
175     * The default error codes allowed are:
176     *        9 - allow illegal characters (they are removed, but this option means it
177     *             doesn't trigger an error.
178     *      76 - allow unexpected end tag. This is typically old wikitext using deprecated tags.
179     *     513 - allow multiple tags with same id
180     *     801 - allow unrecognized tags like figcaption
181     *
182     * @param string $content
183     * @param bool $utf8Fragment If true, prefix $content with <?xml encoding="utf-8"?>
184     * @param array $ignoreErrorCodes
185     * @return DOMDocument
186     * @throws WikitextException
187     * @see http://www.xmlsoft.org/html/libxml-xmlerror.html
188     */
189    public static function createDOM(
190        $content,
191        $utf8Fragment = true,
192        array $ignoreErrorCodes = [ 9, 76, 513, 801 ]
193    ) {
194        $dom = new DOMDocument();
195
196        $loadEntities = false;
197        if ( LIBXML_VERSION < 20900 ) {
198            // Otherwise the parser may attempt to load the dtd from an external source.
199            // See: https://www.mediawiki.org/wiki/XML_External_Entity_Processing
200            $loadEntities = libxml_disable_entity_loader( true );
201        }
202
203        // don't output warnings
204        $useErrors = libxml_use_internal_errors( true );
205
206        // Work around DOMDocument's morbid insistence on using iso-8859-1
207        // Even $dom = new DOMDocument( '1.0', 'utf-8' ); doesn't work, you have to specify
208        // encoding ="utf-8" in the string fed to loadHTML()
209        $html = ( $utf8Fragment ? '<?xml encoding="utf-8"?>' : '' ) . $content;
210        $dom->loadHTML( $html, LIBXML_PARSEHUGE );
211
212        if ( LIBXML_VERSION < 20900 ) {
213            libxml_disable_entity_loader( $loadEntities );
214        }
215
216        // check error codes; if not in the supplied list of ignorable errors,
217        // throw an exception
218        $errors = array_filter(
219            libxml_get_errors(),
220            static function ( $error ) use( $ignoreErrorCodes ) {
221                return !in_array( $error->code, $ignoreErrorCodes );
222            }
223        );
224
225        // restore libxml state before anything else
226        libxml_clear_errors();
227        libxml_use_internal_errors( $useErrors );
228
229        if ( $errors ) {
230            throw new WikitextException(
231                implode(
232                    "\n",
233                    array_map(
234                        static function ( $error ) {
235                            return $error->message;
236                        },
237                        $errors
238                    )
239                ) . "\n\nFrom source content:\n" . $content,
240                'process-wikitext'
241            );
242        }
243
244        return $dom;
245    }
246
247    /**
248     * Handler for FlowAddModules, avoids rest of Flow having to be aware if
249     * Parsoid is in use.
250     *
251     * @param OutputPage $out
252     * @return bool
253     */
254    public static function onFlowAddModules( OutputPage $out ) {
255        // The module is only necessary when we are using parsoid.
256        // XXX We only need the Parsoid CSS if some content being
257        // rendered has getContentFormat() === 'html'.
258        $out->addModuleStyles( [
259            'mediawiki.skinning.content.parsoid',
260            'ext.cite.parsoid.styles',
261        ] );
262
263        return true;
264    }
265
266    /**
267     * Saves a document using saveXML, but avoid escaping style blocks with CDATA.
268     * This is not needed in HTML and breaks the CSS.
269     *
270     * @param DOMDocument $doc
271     * @param DOMNode|null $node the specific node to save
272     * @return string HTML
273     */
274    public static function saferSaveXML( DOMDocument $doc, ?DOMNode $node = null ) {
275        $html = $doc->saveXML( $node );
276        // This regex is only safe as long as attribute values get escaped > chars
277        // This is checked by the testcases
278        $html = preg_replace( '/<style([^>]*)><!\[CDATA\[/i', '<style\1>', $html );
279        return preg_replace( '/\]\]><\/style>/i', '</style>', $html );
280    }
281
282    /**
283     * Retrieves the html of the node's children.
284     *
285     * @param DOMNode|null $node
286     * @return string html of the nodes children
287     */
288    public static function getInnerHtml( ?DOMNode $node = null ) {
289        $html = '';
290        if ( $node ) {
291            $dom = $node instanceof DOMDocument ? $node : $node->ownerDocument;
292            // Don't use saveHTML(), it has bugs (T217766); instead use XML serialization
293            // with a workaround for empty non-void nodes
294            $fixer = new ContentFixer( new EmptyNodeFixer );
295            $fixer->applyToDom( $dom, Title::newMainPage() );
296
297            foreach ( $node->childNodes as $child ) {
298                $html .= self::saferSaveXML( $dom, $child );
299            }
300        }
301        return $html;
302    }
303
304    /**
305     * Gets the HTML of a node. This is like getInnterHtml(), but includes the node's tag itself too.
306     * @param DOMNode $node
307     * @return string HTML
308     */
309    public static function getOuterHtml( DOMNode $node ) {
310        $dom = $node instanceof DOMDocument ? $node : $node->ownerDocument;
311        // Don't use saveHTML(), it has bugs (T217766); instead use XML serialization
312        // with a workaround for empty non-void nodes
313        $fixer = new ContentFixer( new EmptyNodeFixer );
314        $fixer->applyToDom( $dom, Title::newMainPage() );
315        return self::saferSaveXML( $dom, $node );
316    }
317
318    /**
319     * Encode information from the <head> tag as attributes on the <body> tag, then
320     * drop the <head>.
321     *
322     * Specifically, add the Parsoid version number in the parsoid-version attribute;
323     * put the href of the <base> tag in the base-url attribute;
324     * and remove the class attribute from the <body>.
325     *
326     * @param string $html
327     * @return string HTML with <head> information encoded as attributes on the <body>
328     * @throws WikitextException
329     * @suppress PhanUndeclaredMethod,PhanTypeMismatchArgumentNullable Apparently a phan bug / wrong built-in PHP stubs
330     */
331    public static function encodeHeadInfo( $html ) {
332        $dom = ContentFixer::createDOM( $html );
333        $body = $dom->getElementsByTagName( 'body' )->item( 0 );
334        $head = $dom->getElementsByTagName( 'head' )->item( 0 );
335        $base = $head ? $head->getElementsByTagName( 'base' )->item( 0 ) : null;
336        $body->setAttribute( 'parsoid-version', self::PARSOID_VERSION );
337        if ( $base instanceof DOMElement && $base->getAttribute( 'href' ) ) {
338            $body->setAttribute( 'base-url', $base->getAttribute( 'href' ) );
339        }
340        // The class attribute is not used by us and is wastefully long, remove it
341        $body->removeAttribute( 'class' );
342        return self::getOuterHtml( $body );
343    }
344
345    /**
346     * Put the base URI from the <body>'s base-url attribute back in the <head> as a <base> tag.
347     * This reverses (part of) the transformation done by encodeHeadInfo().
348     *
349     * @param string $html HTML (may be a full document, <body> tag  or unwrapped <body> contents)
350     * @return string HTML (<html> tag with <head> and <body>) with the <base> tag restored
351     * @throws WikitextException
352     * @suppress PhanUndeclaredMethod,PhanTypeMismatchArgumentNullable Apparently a phan bug / wrong built-in PHP stubs
353     */
354    public static function decodeHeadInfo( $html ) {
355        $dom = ContentFixer::createDOM( $html );
356        $body = $dom->getElementsByTagName( 'body' )->item( 0 );
357        $baseUrl = $body->getAttribute( 'base-url' );
358        return Html::rawElement( 'html', [],
359            Html::rawElement( 'head', [],
360                // Only set base href if there's a value to set.
361                $baseUrl ? Html::element( 'base', [ 'href' => $baseUrl ] ) : ''
362            ) .
363            self::getOuterHtml( $body )
364        );
365    }
366
367    /**
368     * Get the Parsoid version from HTML content stored in the database.
369     * This interprets the transformation done by encodeHeadInfo().
370     *
371     * @param string $html
372     * @return string|null Parsoid version number, or null if none found
373     * @suppress PhanUndeclaredMethod Apparently a phan bug / wrong built-in PHP stubs
374     */
375    public static function getParsoidVersion( $html ) {
376        $dom = ContentFixer::createDOM( $html );
377        $body = $dom->getElementsByTagName( 'body' )->item( 0 );
378        $version = $body->getAttribute( 'parsoid-version' );
379        return $version !== '' ? $version : null;
380    }
381
382    /**
383     * Subpage links from Parsoid don't contain any direct context, its applied via
384     * a <base href="..."> tag, so here we apply a similar rule resolving against
385     * $title
386     *
387     * @param string $text
388     * @param Title $title Title to resolve relative links against
389     * @return Title|null
390     */
391    public static function createRelativeTitle( $text, Title $title ) {
392        // currently parsoid always uses enough ../ or ./ to go
393        // back to the root, a bit of a kludge but just assume we
394        // can strip and will end up with a non-relative text.
395        $text = preg_replace( '|^(\.\.?/)+|', '', $text );
396
397        if ( $text && ( $text[0] === '/' || $text[0] === '#' ) ) {
398            return Title::newFromText( $title->getDBkey() . $text, $title->getNamespace() );
399        }
400
401        return Title::newFromText( $text );
402    }
403
404    /**
405     * @since 1.35
406     * @return ILanguageConverter
407     */
408    private static function getLanguageConverter(): ILanguageConverter {
409        $services = MediaWikiServices::getInstance();
410        return $services
411            ->getLanguageConverterFactory()
412            ->getLanguageConverter( $services->getContentLanguage() );
413    }
414
415    /**
416     * @since 1.35
417     * @param Title $title Title to convert to language variant
418     * @return string Converted title
419     */
420    public static function getConvertedTitle( Title $title ) {
421        $ns = $title->getNamespace();
422        $titleText = $title->getText();
423        $langConv = self::getLanguageConverter();
424        $variant = $langConv->getPreferredVariant();
425        $convertedNamespace = $langConv->convertNamespace( $ns, $variant );
426        if ( $convertedNamespace ) {
427            return $convertedNamespace . ':' . $langConv->translate( $titleText, $variant );
428        } else {
429            return $langConv->translate( $titleText, $variant );
430        }
431    }
432}