Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
SanitizerHandler
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 4
756
0.00% covered (danger)
0.00%
0 / 1
 sanitizeToken
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
380
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 onCompoundTk
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 onAny
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2declare( strict_types = 1 );
3
4/**
5 * General token sanitizer. Strips out (or encapsulates) unsafe and disallowed
6 * tag types and attributes. Should run last in the third, synchronous
7 * expansion stage.
8 *
9 * FIXME: This code was originally ported from PHP to JS in 2012
10 * and periodically updated before being back to PHP. This code should be
11 * (a) resynced with core sanitizer changes (b) updated to use HTML5 spec
12 */
13
14namespace Wikimedia\Parsoid\Wt2Html\TT;
15
16use Wikimedia\Parsoid\Config\SiteConfig;
17use Wikimedia\Parsoid\Core\Sanitizer;
18use Wikimedia\Parsoid\Tokens\CompoundTk;
19use Wikimedia\Parsoid\Tokens\EmptyLineTk;
20use Wikimedia\Parsoid\Tokens\EndTagTk;
21use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
22use Wikimedia\Parsoid\Tokens\TagTk;
23use Wikimedia\Parsoid\Tokens\Token;
24use Wikimedia\Parsoid\Tokens\XMLTagTk;
25use Wikimedia\Parsoid\Utils\TokenUtils;
26use Wikimedia\Parsoid\Wikitext\Consts;
27use Wikimedia\Parsoid\Wt2Html\Frame;
28use Wikimedia\Parsoid\Wt2Html\TokenHandlerPipeline;
29
30class SanitizerHandler extends UniversalTokenHandler {
31    /** @var bool */
32    private $inTemplate;
33
34    private const NO_END_TAG_SET = [ 'br' => true ];
35
36    /**
37     * Sanitize a token.
38     *
39     * If the token is unmodified, return null.
40     *
41     * XXX: Make attribute sanitation reversible by storing round-trip info in
42     * $token->dataParsoid object (which is serialized as JSON in a data-parsoid
43     * attribute in the DOM).
44     *
45     * @param SiteConfig $siteConfig
46     * @param Frame $frame
47     * @param Token|string $token
48     * @param bool $inTemplate
49     * @return Token|string|null
50     */
51    private function sanitizeToken(
52        SiteConfig $siteConfig, Frame $frame, $token, bool $inTemplate
53    ) {
54        $attribs = $token->attribs ?? null;
55        $allowedTags = Consts::$Sanitizer['AllowedLiteralTags'];
56
57        if (
58            $token instanceof XMLTagTk &&
59            TokenUtils::isHTMLTag( $token ) &&
60            ( empty( $allowedTags[$token->getName()] ) ||
61                ( $token instanceof EndTagTk && !empty( self::NO_END_TAG_SET[$token->getName()] ) ) ||
62                Sanitizer::escapeLiteralHTMLTag( $token ) )
63        ) { // unknown tag -- convert to plain text
64            if ( !$inTemplate && !empty( $token->dataParsoid->tsr ) ) {
65                // Just get the original token source, so that we can avoid
66                // whitespace differences.
67                $token = $token->getWTSource( $frame->getSource() );
68            } elseif ( !( $token instanceof EndTagTk ) ) {
69                // Handle things without a TSR: For example template or extension
70                // content. Whitespace in these is not necessarily preserved.
71                $buf = '<' . $token->getName();
72                for ( $i = 0, $l = count( $attribs );  $i < $l;  $i++ ) {
73                    $kv = $attribs[$i];
74                    $buf .= ' ' . TokenUtils::tokensToString( $kv->k ) .
75                        "='" . TokenUtils::tokensToString( $kv->v ) . "'";
76                }
77                if ( $token instanceof SelfclosingTagTk ) {
78                    $buf .= ' /';
79                }
80                $buf .= '>';
81                $token = $buf;
82            } else {
83                $token = '</' . $token->getName() . '>';
84            }
85            return $token;
86        }
87
88        if ( $attribs && count( $attribs ) > 0 ) {
89            // Sanitize attributes
90            if ( $token instanceof TagTk || $token instanceof SelfclosingTagTk ) {
91                $newAttrs = Sanitizer::sanitizeTagAttrs( $siteConfig, null, $token, $attribs );
92
93                // Reset token attribs and rebuild
94                $token->attribs = [];
95
96                // SSS FIXME: We are right now adding shadow information for all sanitized
97                // attributes.  This is being done to minimize dirty diffs for the first
98                // cut.  It can be reasonably argued that we can permanently delete dangerous
99                // and unacceptable attributes in the interest of safety/security and the
100                // resultant dirty diffs should be acceptable.  But, this is something to do
101                // in the future once we have passed the initial tests of parsoid acceptance.
102                foreach ( $newAttrs as $k => $v ) {
103                    if ( $v[3] ) {
104                        $token->addAttribute( $k, $v[0] );
105                        $token->setShadowInfo( $k, $v[0], $v[1] );
106                    // explicit check against null to prevent discarding empty strings
107                    } elseif ( $v[0] !== null ) {
108                        $token->addNormalizedAttribute( $k, $v[0], $v[1] );
109                    } else {
110                        $token->setShadowInfoIfModified( $v[2], $v[0], $v[1] );
111                    }
112                }
113            } else {
114                // EndTagTk, drop attributes
115                $token->attribs = [];
116            }
117            return $token;
118        }
119
120        return null;
121    }
122
123    /**
124     * @param TokenHandlerPipeline $manager manager enviroment
125     * @param array $options various configuration options
126     */
127    public function __construct( TokenHandlerPipeline $manager, array $options ) {
128        parent::__construct( $manager, $options );
129        $this->inTemplate = $options['inTemplate'];
130    }
131
132    /** @inheritDoc */
133    public function onCompoundTk( CompoundTk $ctk, TokenHandler $tokensHandler ): ?array {
134        if ( !( $ctk instanceof EmptyLineTk ) ) {
135            $ctk->setNestedTokens( $tokensHandler->process( $ctk->getNestedTokens() ) );
136        }
137        return null;
138    }
139
140    /**
141     * @inheritDoc
142     */
143    public function onAny( $token ): ?array {
144        if ( is_string( $token ) ) {
145            return null;
146        }
147        $env = $this->env;
148        $env->trace( 'sanitizer', $this->pipelineId, $token );
149
150        $newToken = $this->sanitizeToken(
151            $env->getSiteConfig(), $this->manager->getFrame(), $token, $this->inTemplate
152        );
153
154        if ( $newToken ) {
155            $env->trace( 'sanitizer', $this->pipelineId, ' ---> ', $newToken );
156        }
157        return ( $newToken === null || $newToken === $token ) ? null : [ $newToken ];
158    }
159}