Sanitize.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. <?php
  2. /**
  3. * SimplePie
  4. *
  5. * A PHP-Based RSS and Atom Feed Framework.
  6. * Takes the hard work out of managing a complete RSS/Atom solution.
  7. *
  8. * Copyright (c) 2004-2016, Ryan Parman, Sam Sneddon, Ryan McCue, and contributors
  9. * All rights reserved.
  10. *
  11. * Redistribution and use in source and binary forms, with or without modification, are
  12. * permitted provided that the following conditions are met:
  13. *
  14. * * Redistributions of source code must retain the above copyright notice, this list of
  15. * conditions and the following disclaimer.
  16. *
  17. * * Redistributions in binary form must reproduce the above copyright notice, this list
  18. * of conditions and the following disclaimer in the documentation and/or other materials
  19. * provided with the distribution.
  20. *
  21. * * Neither the name of the SimplePie Team nor the names of its contributors may be used
  22. * to endorse or promote products derived from this software without specific prior
  23. * written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
  26. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  27. * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
  28. * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  29. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  30. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  32. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. * POSSIBILITY OF SUCH DAMAGE.
  34. *
  35. * @package SimplePie
  36. * @copyright 2004-2016 Ryan Parman, Sam Sneddon, Ryan McCue
  37. * @author Ryan Parman
  38. * @author Sam Sneddon
  39. * @author Ryan McCue
  40. * @link http://simplepie.org/ SimplePie
  41. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  42. */
  43. /**
  44. * Used for data cleanup and post-processing
  45. *
  46. *
  47. * This class can be overloaded with {@see SimplePie::set_sanitize_class()}
  48. *
  49. * @package SimplePie
  50. * @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags
  51. */
  52. class SimplePie_Sanitize
  53. {
  54. // Private vars
  55. var $base;
  56. // Options
  57. var $remove_div = true;
  58. var $image_handler = '';
  59. var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style');
  60. var $encode_instead_of_strip = false;
  61. var $strip_attributes = array('bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc');
  62. var $add_attributes = array('audio' => array('preload' => 'none'), 'iframe' => array('sandbox' => 'allow-scripts allow-same-origin'), 'video' => array('preload' => 'none'));
  63. var $strip_comments = false;
  64. var $output_encoding = 'UTF-8';
  65. var $enable_cache = true;
  66. var $cache_location = './cache';
  67. var $cache_name_function = 'md5';
  68. var $timeout = 10;
  69. var $useragent = '';
  70. var $force_fsockopen = false;
  71. var $replace_url_attributes = null;
  72. var $registry;
  73. /**
  74. * List of domains for which to force HTTPS.
  75. * @see SimplePie_Sanitize::set_https_domains()
  76. * Array is a tree split at DNS levels. Example:
  77. * array('biz' => true, 'com' => array('example' => true), 'net' => array('example' => array('www' => true)))
  78. */
  79. var $https_domains = array();
  80. public function __construct()
  81. {
  82. // Set defaults
  83. $this->set_url_replacements(null);
  84. }
  85. public function remove_div($enable = true)
  86. {
  87. $this->remove_div = (bool) $enable;
  88. }
  89. public function set_image_handler($page = false)
  90. {
  91. if ($page)
  92. {
  93. $this->image_handler = (string) $page;
  94. }
  95. else
  96. {
  97. $this->image_handler = false;
  98. }
  99. }
  100. public function set_registry(SimplePie_Registry $registry)
  101. {
  102. $this->registry = $registry;
  103. }
  104. public function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie_Cache')
  105. {
  106. if (isset($enable_cache))
  107. {
  108. $this->enable_cache = (bool) $enable_cache;
  109. }
  110. if ($cache_location)
  111. {
  112. $this->cache_location = (string) $cache_location;
  113. }
  114. if ($cache_name_function)
  115. {
  116. $this->cache_name_function = (string) $cache_name_function;
  117. }
  118. }
  119. public function pass_file_data($file_class = 'SimplePie_File', $timeout = 10, $useragent = '', $force_fsockopen = false)
  120. {
  121. if ($timeout)
  122. {
  123. $this->timeout = (string) $timeout;
  124. }
  125. if ($useragent)
  126. {
  127. $this->useragent = (string) $useragent;
  128. }
  129. if ($force_fsockopen)
  130. {
  131. $this->force_fsockopen = (string) $force_fsockopen;
  132. }
  133. }
  134. public function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'))
  135. {
  136. if ($tags)
  137. {
  138. if (is_array($tags))
  139. {
  140. $this->strip_htmltags = $tags;
  141. }
  142. else
  143. {
  144. $this->strip_htmltags = explode(',', $tags);
  145. }
  146. }
  147. else
  148. {
  149. $this->strip_htmltags = false;
  150. }
  151. }
  152. public function encode_instead_of_strip($encode = false)
  153. {
  154. $this->encode_instead_of_strip = (bool) $encode;
  155. }
  156. public function strip_attributes($attribs = array('bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'))
  157. {
  158. if ($attribs)
  159. {
  160. if (is_array($attribs))
  161. {
  162. $this->strip_attributes = $attribs;
  163. }
  164. else
  165. {
  166. $this->strip_attributes = explode(',', $attribs);
  167. }
  168. }
  169. else
  170. {
  171. $this->strip_attributes = false;
  172. }
  173. }
  174. public function add_attributes($attribs = array('audio' => array('preload' => 'none'), 'iframe' => array('sandbox' => 'allow-scripts allow-same-origin'), 'video' => array('preload' => 'none')))
  175. {
  176. if ($attribs)
  177. {
  178. if (is_array($attribs))
  179. {
  180. $this->add_attributes = $attribs;
  181. }
  182. else
  183. {
  184. $this->add_attributes = explode(',', $attribs);
  185. }
  186. }
  187. else
  188. {
  189. $this->add_attributes = false;
  190. }
  191. }
  192. public function strip_comments($strip = false)
  193. {
  194. $this->strip_comments = (bool) $strip;
  195. }
  196. public function set_output_encoding($encoding = 'UTF-8')
  197. {
  198. $this->output_encoding = (string) $encoding;
  199. }
  200. /**
  201. * Set element/attribute key/value pairs of HTML attributes
  202. * containing URLs that need to be resolved relative to the feed
  203. *
  204. * Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
  205. * |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
  206. * |q|@cite
  207. *
  208. * @since 1.0
  209. * @param array|null $element_attribute Element/attribute key/value pairs, null for default
  210. */
  211. public function set_url_replacements($element_attribute = null)
  212. {
  213. if ($element_attribute === null)
  214. {
  215. $element_attribute = array(
  216. 'a' => 'href',
  217. 'area' => 'href',
  218. 'blockquote' => 'cite',
  219. 'del' => 'cite',
  220. 'form' => 'action',
  221. 'img' => array(
  222. 'longdesc',
  223. 'src'
  224. ),
  225. 'input' => 'src',
  226. 'ins' => 'cite',
  227. 'q' => 'cite'
  228. );
  229. }
  230. $this->replace_url_attributes = (array) $element_attribute;
  231. }
  232. /**
  233. * Set the list of domains for which to force HTTPS.
  234. * @see SimplePie_Misc::https_url()
  235. * Example array('biz', 'example.com', 'example.org', 'www.example.net');
  236. */
  237. public function set_https_domains($domains)
  238. {
  239. $this->https_domains = array();
  240. foreach ($domains as $domain)
  241. {
  242. $domain = trim($domain, ". \t\n\r\0\x0B");
  243. $segments = array_reverse(explode('.', $domain));
  244. $node =& $this->https_domains;
  245. foreach ($segments as $segment)
  246. {//Build a tree
  247. if ($node === true)
  248. {
  249. break;
  250. }
  251. if (!isset($node[$segment]))
  252. {
  253. $node[$segment] = array();
  254. }
  255. $node =& $node[$segment];
  256. }
  257. $node = true;
  258. }
  259. }
  260. /**
  261. * Check if the domain is in the list of forced HTTPS.
  262. */
  263. protected function is_https_domain($domain)
  264. {
  265. $domain = trim($domain, '. ');
  266. $segments = array_reverse(explode('.', $domain));
  267. $node =& $this->https_domains;
  268. foreach ($segments as $segment)
  269. {//Explore the tree
  270. if (isset($node[$segment]))
  271. {
  272. $node =& $node[$segment];
  273. }
  274. else
  275. {
  276. break;
  277. }
  278. }
  279. return $node === true;
  280. }
  281. /**
  282. * Force HTTPS for selected Web sites.
  283. */
  284. public function https_url($url)
  285. {
  286. return (strtolower(substr($url, 0, 7)) === 'http://') &&
  287. $this->is_https_domain(parse_url($url, PHP_URL_HOST)) ?
  288. substr_replace($url, 's', 4, 0) : //Add the 's' to HTTPS
  289. $url;
  290. }
  291. public function sanitize($data, $type, $base = '')
  292. {
  293. $data = trim($data);
  294. if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI)
  295. {
  296. if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML)
  297. {
  298. if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data))
  299. {
  300. $type |= SIMPLEPIE_CONSTRUCT_HTML;
  301. }
  302. else
  303. {
  304. $type |= SIMPLEPIE_CONSTRUCT_TEXT;
  305. }
  306. }
  307. if ($type & SIMPLEPIE_CONSTRUCT_BASE64)
  308. {
  309. $data = base64_decode($data);
  310. }
  311. if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML))
  312. {
  313. if (!class_exists('DOMDocument'))
  314. {
  315. throw new SimplePie_Exception('DOMDocument not found, unable to use sanitizer');
  316. }
  317. $document = new DOMDocument();
  318. $document->encoding = 'UTF-8';
  319. $data = $this->preprocess($data, $type);
  320. set_error_handler(array('SimplePie_Misc', 'silence_errors'));
  321. $document->loadHTML($data);
  322. restore_error_handler();
  323. $xpath = new DOMXPath($document);
  324. // Strip comments
  325. if ($this->strip_comments)
  326. {
  327. $comments = $xpath->query('//comment()');
  328. foreach ($comments as $comment)
  329. {
  330. $comment->parentNode->removeChild($comment);
  331. }
  332. }
  333. // Strip out HTML tags and attributes that might cause various security problems.
  334. // Based on recommendations by Mark Pilgrim at:
  335. // http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
  336. if ($this->strip_htmltags)
  337. {
  338. foreach ($this->strip_htmltags as $tag)
  339. {
  340. $this->strip_tag($tag, $document, $xpath, $type);
  341. }
  342. }
  343. if ($this->strip_attributes)
  344. {
  345. foreach ($this->strip_attributes as $attrib)
  346. {
  347. $this->strip_attr($attrib, $xpath);
  348. }
  349. }
  350. if ($this->add_attributes)
  351. {
  352. foreach ($this->add_attributes as $tag => $valuePairs)
  353. {
  354. $this->add_attr($tag, $valuePairs, $document);
  355. }
  356. }
  357. // Replace relative URLs
  358. $this->base = $base;
  359. foreach ($this->replace_url_attributes as $element => $attributes)
  360. {
  361. $this->replace_urls($document, $element, $attributes);
  362. }
  363. // If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
  364. if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache)
  365. {
  366. $images = $document->getElementsByTagName('img');
  367. foreach ($images as $img)
  368. {
  369. if ($img->hasAttribute('src'))
  370. {
  371. $image_url = call_user_func($this->cache_name_function, $img->getAttribute('src'));
  372. $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, $image_url, 'spi'));
  373. if ($cache->load())
  374. {
  375. $img->setAttribute('src', $this->image_handler . $image_url);
  376. }
  377. else
  378. {
  379. $file = $this->registry->create('File', array($img->getAttribute('src'), $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen));
  380. $headers = $file->headers;
  381. if ($file->success && ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300)))
  382. {
  383. if ($cache->save(array('headers' => $file->headers, 'body' => $file->body)))
  384. {
  385. $img->setAttribute('src', $this->image_handler . $image_url);
  386. }
  387. else
  388. {
  389. trigger_error("$this->cache_location is not writable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }
  396. // Get content node
  397. $div = $document->getElementsByTagName('body')->item(0)->firstChild;
  398. // Finally, convert to a HTML string
  399. $data = trim($document->saveHTML($div));
  400. if ($this->remove_div)
  401. {
  402. $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data);
  403. $data = preg_replace('/<\/div>$/', '', $data);
  404. }
  405. else
  406. {
  407. $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
  408. }
  409. }
  410. if ($type & SIMPLEPIE_CONSTRUCT_IRI)
  411. {
  412. $absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base));
  413. if ($absolute !== false)
  414. {
  415. $data = $absolute;
  416. }
  417. }
  418. if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI))
  419. {
  420. $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
  421. }
  422. if ($this->output_encoding !== 'UTF-8')
  423. {
  424. $data = $this->registry->call('Misc', 'change_encoding', array($data, 'UTF-8', $this->output_encoding));
  425. }
  426. }
  427. return $data;
  428. }
  429. protected function preprocess($html, $type)
  430. {
  431. $ret = '';
  432. $html = preg_replace('%</?(?:html|body)[^>]*?'.'>%is', '', $html);
  433. if ($type & ~SIMPLEPIE_CONSTRUCT_XHTML)
  434. {
  435. // Atom XHTML constructs are wrapped with a div by default
  436. // Note: No protection if $html contains a stray </div>!
  437. $html = '<div>' . $html . '</div>';
  438. $ret .= '<!DOCTYPE html>';
  439. $content_type = 'text/html';
  440. }
  441. else
  442. {
  443. $ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  444. $content_type = 'application/xhtml+xml';
  445. }
  446. $ret .= '<html><head>';
  447. $ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />';
  448. $ret .= '</head><body>' . $html . '</body></html>';
  449. return $ret;
  450. }
  451. public function replace_urls($document, $tag, $attributes)
  452. {
  453. if (!is_array($attributes))
  454. {
  455. $attributes = array($attributes);
  456. }
  457. if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags))
  458. {
  459. $elements = $document->getElementsByTagName($tag);
  460. foreach ($elements as $element)
  461. {
  462. foreach ($attributes as $attribute)
  463. {
  464. if ($element->hasAttribute($attribute))
  465. {
  466. $value = $this->registry->call('Misc', 'absolutize_url', array($element->getAttribute($attribute), $this->base));
  467. if ($value !== false)
  468. {
  469. $value = $this->https_url($value);
  470. $element->setAttribute($attribute, $value);
  471. }
  472. }
  473. }
  474. }
  475. }
  476. }
  477. public function do_strip_htmltags($match)
  478. {
  479. if ($this->encode_instead_of_strip)
  480. {
  481. if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
  482. {
  483. $match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8');
  484. $match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8');
  485. return "&lt;$match[1]$match[2]&gt;$match[3]&lt;/$match[1]&gt;";
  486. }
  487. else
  488. {
  489. return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8');
  490. }
  491. }
  492. elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
  493. {
  494. return $match[4];
  495. }
  496. else
  497. {
  498. return '';
  499. }
  500. }
  501. protected function strip_tag($tag, $document, $xpath, $type)
  502. {
  503. $elements = $xpath->query('body//' . $tag);
  504. if ($this->encode_instead_of_strip)
  505. {
  506. foreach ($elements as $element)
  507. {
  508. $fragment = $document->createDocumentFragment();
  509. // For elements which aren't script or style, include the tag itself
  510. if (!in_array($tag, array('script', 'style')))
  511. {
  512. $text = '<' . $tag;
  513. if ($element->hasAttributes())
  514. {
  515. $attrs = array();
  516. foreach ($element->attributes as $name => $attr)
  517. {
  518. $value = $attr->value;
  519. // In XHTML, empty values should never exist, so we repeat the value
  520. if (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_XHTML))
  521. {
  522. $value = $name;
  523. }
  524. // For HTML, empty is fine
  525. elseif (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_HTML))
  526. {
  527. $attrs[] = $name;
  528. continue;
  529. }
  530. // Standard attribute text
  531. $attrs[] = $name . '="' . $attr->value . '"';
  532. }
  533. $text .= ' ' . implode(' ', $attrs);
  534. }
  535. $text .= '>';
  536. $fragment->appendChild(new DOMText($text));
  537. }
  538. $number = $element->childNodes->length;
  539. for ($i = $number; $i > 0; $i--)
  540. {
  541. $child = $element->childNodes->item(0);
  542. $fragment->appendChild($child);
  543. }
  544. if (!in_array($tag, array('script', 'style')))
  545. {
  546. $fragment->appendChild(new DOMText('</' . $tag . '>'));
  547. }
  548. $element->parentNode->replaceChild($fragment, $element);
  549. }
  550. return;
  551. }
  552. elseif (in_array($tag, array('script', 'style')))
  553. {
  554. foreach ($elements as $element)
  555. {
  556. $element->parentNode->removeChild($element);
  557. }
  558. return;
  559. }
  560. else
  561. {
  562. foreach ($elements as $element)
  563. {
  564. $fragment = $document->createDocumentFragment();
  565. $number = $element->childNodes->length;
  566. for ($i = $number; $i > 0; $i--)
  567. {
  568. $child = $element->childNodes->item(0);
  569. $fragment->appendChild($child);
  570. }
  571. $element->parentNode->replaceChild($fragment, $element);
  572. }
  573. }
  574. }
  575. protected function strip_attr($attrib, $xpath)
  576. {
  577. $elements = $xpath->query('//*[@' . $attrib . ']');
  578. foreach ($elements as $element)
  579. {
  580. $element->removeAttribute($attrib);
  581. }
  582. }
  583. protected function add_attr($tag, $valuePairs, $document)
  584. {
  585. $elements = $document->getElementsByTagName($tag);
  586. foreach ($elements as $element)
  587. {
  588. foreach ($valuePairs as $attrib => $value)
  589. {
  590. $element->setAttribute($attrib, $value);
  591. }
  592. }
  593. }
  594. }