summaryrefslogtreecommitdiffstats
path: root/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlParser.php
blob: ea04a476ff382d362b78c86ee231f9888135192e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php

namespace PicoFeed\Parser;

use Closure;
use DomDocument;
use SimpleXmlElement;

/**
 * XML parser class.
 *
 * Checks for XML eXternal Entity (XXE) and XML Entity Expansion (XEE) attacks on XML documents
 *
 * @author  Frederic Guillot
 */
class XmlParser
{
    /**
     * Get a SimpleXmlElement instance or return false.
     *
     * @static
     *
     * @param string $input XML content
     *
     * @return mixed
     */
    public static function getSimpleXml($input)
    {
        $dom = self::getDomDocument($input);

        if ($dom !== false) {
            $simplexml = simplexml_import_dom($dom);

            if (!$simplexml instanceof SimpleXmlElement) {
                return false;
            }

            return $simplexml;
        }

        return false;
    }

    /**
     * Scan the input for XXE attacks.
     *
     * @param string  $input    Unsafe input
     * @param Closure $callback Callback called to build the dom.
     *                          Must be an instance of DomDocument and receives the input as argument
     *
     * @return bool|DomDocument False if an XXE attack was discovered,
     *                          otherwise the return of the callback
     */
    private static function scanInput($input, Closure $callback)
    {
        $isRunningFpm = substr(php_sapi_name(), 0, 3) === 'fpm';

        if ($isRunningFpm) {

            // If running with PHP-FPM and an entity is detected we refuse to parse the feed
            // @see https://bugs.php.net/bug.php?id=64938
            if (strpos($input, '<!ENTITY') !== false) {
                return false;
            }
        } else {
            $entityLoaderDisabled = libxml_disable_entity_loader(true);
        }

        libxml_use_internal_errors(true);

        $dom = $callback($input);

        // Scan for potential XEE attacks using ENTITY
        foreach ($dom->childNodes as $child) {
            if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
                if ($child->entities->length > 0) {
                    return false;
                }
            }
        }

        if ($isRunningFpm === false) {
            libxml_disable_entity_loader($entityLoaderDisabled);
        }

        return $dom;
    }

    /**
     * Get a DomDocument instance or return false.
     *
     * @static
     *
     * @param string $input XML content
     *
     * @return \DOMNDocument
     */
    public static function getDomDocument($input)
    {
        if (empty($input)) {
            return false;
        }

        $dom = self::scanInput($input, function ($in) {
            $dom = new DomDocument();
            $dom->loadXml($in, LIBXML_NONET);

            return $dom;
        });

        // The document is empty, there is probably some parsing errors
        if ($dom && $dom->childNodes->length === 0) {
            return false;
        }

        return $dom;
    }

    /**
     * Load HTML document by using a DomDocument instance or return false on failure.
     *
     * @static
     *
     * @param string $input XML content
     *
     * @return \DOMDocument
     */
    public static function getHtmlDocument($input)
    {
        if (empty($input)) {
            return new DomDocument();
        }

        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            $callback = function ($in) {
                $dom = new DomDocument();
                $dom->loadHTML($in, LIBXML_NONET);

                return $dom;
            };
        } else {
            $callback = function ($in) {
                $dom = new DomDocument();
                $dom->loadHTML($in);

                return $dom;
            };
        }

        return self::scanInput($input, $callback);
    }

    /**
     * Convert a HTML document to XML.
     *
     * @static
     *
     * @param string $html HTML document
     *
     * @return string
     */
    public static function htmlToXml($html)
    {
        $dom = self::getHtmlDocument('<?xml version="1.0" encoding="UTF-8">'.$html);

        return $dom->saveXML($dom->getElementsByTagName('body')->item(0));
    }

    /**
     * Get XML parser errors.
     *
     * @static
     *
     * @return string
     */
    public static function getErrors()
    {
        $errors = array();

        foreach (libxml_get_errors() as $error) {
            $errors[] = sprintf('XML error: %s (Line: %d - Column: %d - Code: %d)',
                $error->message,
                $error->line,
                $error->column,
                $error->code
            );
        }

        return implode(', ', $errors);
    }

    /**
     * Get the encoding from a xml tag.
     *
     * @static
     *
     * @param string $data Input data
     *
     * @return string
     */
    public static function getEncodingFromXmlTag($data)
    {
        $encoding = '';

        if (strpos($data, '<?xml') !== false) {
            $data = substr($data, 0, strrpos($data, '?>'));
            $data = str_replace("'", '"', $data);

            $p1 = strpos($data, 'encoding=');
            $p2 = strpos($data, '"', $p1 + 10);

            if ($p1 !== false && $p2 !== false) {
                $encoding = substr($data, $p1 + 10, $p2 - $p1 - 10);
                $encoding = strtolower($encoding);
            }
        }

        return $encoding;
    }

    /**
     * Get the charset from a meta tag.
     *
     * @static
     *
     * @param string $data Input data
     *
     * @return string
     */
    public static function getEncodingFromMetaTag($data)
    {
        $encoding = '';

        if (preg_match('/<meta.*?charset\s*=\s*["\']?\s*([^"\'\s\/>;]+)/i', $data, $match) === 1) {
            $encoding = strtolower($match[1]);
        }

        return $encoding;
    }

    /**
     * Rewrite XPath query to use namespace-uri and local-name derived from prefix.
     *
     * @param string $query XPath query
     * @param array  $ns    Prefix to namespace URI mapping
     *
     * @return string
     */
    public static function replaceXPathPrefixWithNamespaceURI($query, array $ns)
    {
        return preg_replace_callback('/([A-Z0-9]+):([A-Z0-9]+)/iu', function ($matches) use ($ns) {
            // don't try to map the special prefix XML
            if (strtolower($matches[1]) === 'xml') {
                return $matches[0];
            }

            return '*[namespace-uri()="'.$ns[$matches[1]].'" and local-name()="'.$matches[2].'"]';
        },
        $query);
    }

    /**
     * Get the result elements of a XPath query.
     *
     * @param \SimpleXMLElement $xml   XML element
     * @param string            $query XPath query
     * @param array             $ns    Prefix to namespace URI mapping
     *
     * @return \SimpleXMLElement
     */
    public static function getXPathResult(SimpleXMLElement $xml, $query, array $ns = array())
    {
        if (!empty($ns)) {
            $query = static::replaceXPathPrefixWithNamespaceURI($query, $ns);
        }

        return $xml->xpath($query);
    }
}