Sin descripción

Sanitize.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. public function __construct()
  73. {
  74. // Set defaults
  75. $this->set_url_replacements(null);
  76. }
  77. public function remove_div($enable = true)
  78. {
  79. $this->remove_div = (bool) $enable;
  80. }
  81. public function set_image_handler($page = false)
  82. {
  83. if ($page)
  84. {
  85. $this->image_handler = (string) $page;
  86. }
  87. else
  88. {
  89. $this->image_handler = false;
  90. }
  91. }
  92. public function set_registry(SimplePie_Registry $registry)
  93. {
  94. $this->registry = $registry;
  95. }
  96. public function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie_Cache')
  97. {
  98. if (isset($enable_cache))
  99. {
  100. $this->enable_cache = (bool) $enable_cache;
  101. }
  102. if ($cache_location)
  103. {
  104. $this->cache_location = (string) $cache_location;
  105. }
  106. if ($cache_name_function)
  107. {
  108. $this->cache_name_function = (string) $cache_name_function;
  109. }
  110. }
  111. public function pass_file_data($file_class = 'SimplePie_File', $timeout = 10, $useragent = '', $force_fsockopen = false)
  112. {
  113. if ($timeout)
  114. {
  115. $this->timeout = (string) $timeout;
  116. }
  117. if ($useragent)
  118. {
  119. $this->useragent = (string) $useragent;
  120. }
  121. if ($force_fsockopen)
  122. {
  123. $this->force_fsockopen = (string) $force_fsockopen;
  124. }
  125. }
  126. 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'))
  127. {
  128. if ($tags)
  129. {
  130. if (is_array($tags))
  131. {
  132. $this->strip_htmltags = $tags;
  133. }
  134. else
  135. {
  136. $this->strip_htmltags = explode(',', $tags);
  137. }
  138. }
  139. else
  140. {
  141. $this->strip_htmltags = false;
  142. }
  143. }
  144. public function encode_instead_of_strip($encode = false)
  145. {
  146. $this->encode_instead_of_strip = (bool) $encode;
  147. }
  148. public function strip_attributes($attribs = array('bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'))
  149. {
  150. if ($attribs)
  151. {
  152. if (is_array($attribs))
  153. {
  154. $this->strip_attributes = $attribs;
  155. }
  156. else
  157. {
  158. $this->strip_attributes = explode(',', $attribs);
  159. }
  160. }
  161. else
  162. {
  163. $this->strip_attributes = false;
  164. }
  165. }
  166. public function add_attributes($attribs = array('audio' => array('preload' => 'none'), 'iframe' => array('sandbox' => 'allow-scripts allow-same-origin'), 'video' => array('preload' => 'none')))
  167. {
  168. if ($attribs)
  169. {
  170. if (is_array($attribs))
  171. {
  172. $this->add_attributes = $attribs;
  173. }
  174. else
  175. {
  176. $this->add_attributes = explode(',', $attribs);
  177. }
  178. }
  179. else
  180. {
  181. $this->add_attributes = false;
  182. }
  183. }
  184. public function strip_comments($strip = false)
  185. {
  186. $this->strip_comments = (bool) $strip;
  187. }
  188. public function set_output_encoding($encoding = 'UTF-8')
  189. {
  190. $this->output_encoding = (string) $encoding;
  191. }
  192. /**
  193. * Set element/attribute key/value pairs of HTML attributes
  194. * containing URLs that need to be resolved relative to the feed
  195. *
  196. * Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
  197. * |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
  198. * |q|@cite
  199. *
  200. * @since 1.0
  201. * @param array|null $element_attribute Element/attribute key/value pairs, null for default
  202. */
  203. public function set_url_replacements($element_attribute = null)
  204. {
  205. if ($element_attribute === null)
  206. {
  207. $element_attribute = array(
  208. 'a' => 'href',
  209. 'area' => 'href',
  210. 'blockquote' => 'cite',
  211. 'del' => 'cite',
  212. 'form' => 'action',
  213. 'img' => array(
  214. 'longdesc',
  215. 'src'
  216. ),
  217. 'input' => 'src',
  218. 'ins' => 'cite',
  219. 'q' => 'cite'
  220. );
  221. }
  222. $this->replace_url_attributes = (array) $element_attribute;
  223. }
  224. public function sanitize($data, $type, $base = '')
  225. {
  226. $data = trim($data);
  227. if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI)
  228. {
  229. if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML)
  230. {
  231. 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))
  232. {
  233. $type |= SIMPLEPIE_CONSTRUCT_HTML;
  234. }
  235. else
  236. {
  237. $type |= SIMPLEPIE_CONSTRUCT_TEXT;
  238. }
  239. }
  240. if ($type & SIMPLEPIE_CONSTRUCT_BASE64)
  241. {
  242. $data = base64_decode($data);
  243. }
  244. if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML))
  245. {
  246. if (!class_exists('DOMDocument'))
  247. {
  248. throw new SimplePie_Exception('DOMDocument not found, unable to use sanitizer');
  249. }
  250. $document = new DOMDocument();
  251. $document->encoding = 'UTF-8';
  252. $data = $this->preprocess($data, $type);
  253. set_error_handler(array('SimplePie_Misc', 'silence_errors'));
  254. $document->loadHTML($data);
  255. restore_error_handler();
  256. $xpath = new DOMXPath($document);
  257. // Strip comments
  258. if ($this->strip_comments)
  259. {
  260. $comments = $xpath->query('//comment()');
  261. foreach ($comments as $comment)
  262. {
  263. $comment->parentNode->removeChild($comment);
  264. }
  265. }
  266. // Strip out HTML tags and attributes that might cause various security problems.
  267. // Based on recommendations by Mark Pilgrim at:
  268. // http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
  269. if ($this->strip_htmltags)
  270. {
  271. foreach ($this->strip_htmltags as $tag)
  272. {
  273. $this->strip_tag($tag, $document, $xpath, $type);
  274. }
  275. }
  276. if ($this->strip_attributes)
  277. {
  278. foreach ($this->strip_attributes as $attrib)
  279. {
  280. $this->strip_attr($attrib, $xpath);
  281. }
  282. }
  283. if ($this->add_attributes)
  284. {
  285. foreach ($this->add_attributes as $tag => $valuePairs)
  286. {
  287. $this->add_attr($tag, $valuePairs, $document);
  288. }
  289. }
  290. // Replace relative URLs
  291. $this->base = $base;
  292. foreach ($this->replace_url_attributes as $element => $attributes)
  293. {
  294. $this->replace_urls($document, $element, $attributes);
  295. }
  296. // If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
  297. if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache)
  298. {
  299. $images = $document->getElementsByTagName('img');
  300. foreach ($images as $img)
  301. {
  302. if ($img->hasAttribute('src'))
  303. {
  304. $image_url = call_user_func($this->cache_name_function, $img->getAttribute('src'));
  305. $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, $image_url, 'spi'));
  306. if ($cache->load())
  307. {
  308. $img->setAttribute('src', $this->image_handler . $image_url);
  309. }
  310. else
  311. {
  312. $file = $this->registry->create('File', array($img->getAttribute('src'), $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen));
  313. $headers = $file->headers;
  314. if ($file->success && ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300)))
  315. {
  316. if ($cache->save(array('headers' => $file->headers, 'body' => $file->body)))
  317. {
  318. $img->setAttribute('src', $this->image_handler . $image_url);
  319. }
  320. else
  321. {
  322. 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);
  323. }
  324. }
  325. }
  326. }
  327. }
  328. }
  329. // Get content node
  330. $div = $document->getElementsByTagName('body')->item(0)->firstChild;
  331. // Finally, convert to a HTML string
  332. $data = trim($document->saveHTML($div));
  333. if ($this->remove_div)
  334. {
  335. $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data);
  336. $data = preg_replace('/<\/div>$/', '', $data);
  337. }
  338. else
  339. {
  340. $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
  341. }
  342. }
  343. if ($type & SIMPLEPIE_CONSTRUCT_IRI)
  344. {
  345. $absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base));
  346. if ($absolute !== false)
  347. {
  348. $data = $absolute;
  349. }
  350. }
  351. if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI))
  352. {
  353. $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
  354. }
  355. if ($this->output_encoding !== 'UTF-8')
  356. {
  357. $data = $this->registry->call('Misc', 'change_encoding', array($data, 'UTF-8', $this->output_encoding));
  358. }
  359. }
  360. return $data;
  361. }
  362. protected function preprocess($html, $type)
  363. {
  364. $ret = '';
  365. $html = preg_replace('%</?(?:html|body)[^>]*?'.'>%is', '', $html);
  366. if ($type & ~SIMPLEPIE_CONSTRUCT_XHTML)
  367. {
  368. // Atom XHTML constructs are wrapped with a div by default
  369. // Note: No protection if $html contains a stray </div>!
  370. $html = '<div>' . $html . '</div>';
  371. $ret .= '<!DOCTYPE html>';
  372. $content_type = 'text/html';
  373. }
  374. else
  375. {
  376. $ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  377. $content_type = 'application/xhtml+xml';
  378. }
  379. $ret .= '<html><head>';
  380. $ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />';
  381. $ret .= '</head><body>' . $html . '</body></html>';
  382. return $ret;
  383. }
  384. public function replace_urls($document, $tag, $attributes)
  385. {
  386. if (!is_array($attributes))
  387. {
  388. $attributes = array($attributes);
  389. }
  390. if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags))
  391. {
  392. $elements = $document->getElementsByTagName($tag);
  393. foreach ($elements as $element)
  394. {
  395. foreach ($attributes as $attribute)
  396. {
  397. if ($element->hasAttribute($attribute))
  398. {
  399. $value = $this->registry->call('Misc', 'absolutize_url', array($element->getAttribute($attribute), $this->base));
  400. if ($value !== false)
  401. {
  402. $element->setAttribute($attribute, $value);
  403. }
  404. }
  405. }
  406. }
  407. }
  408. }
  409. public function do_strip_htmltags($match)
  410. {
  411. if ($this->encode_instead_of_strip)
  412. {
  413. if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
  414. {
  415. $match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8');
  416. $match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8');
  417. return "&lt;$match[1]$match[2]&gt;$match[3]&lt;/$match[1]&gt;";
  418. }
  419. else
  420. {
  421. return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8');
  422. }
  423. }
  424. elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
  425. {
  426. return $match[4];
  427. }
  428. else
  429. {
  430. return '';
  431. }
  432. }
  433. protected function strip_tag($tag, $document, $xpath, $type)
  434. {
  435. $elements = $xpath->query('body//' . $tag);
  436. if ($this->encode_instead_of_strip)
  437. {
  438. foreach ($elements as $element)
  439. {
  440. $fragment = $document->createDocumentFragment();
  441. // For elements which aren't script or style, include the tag itself
  442. if (!in_array($tag, array('script', 'style')))
  443. {
  444. $text = '<' . $tag;
  445. if ($element->hasAttributes())
  446. {
  447. $attrs = array();
  448. foreach ($element->attributes as $name => $attr)
  449. {
  450. $value = $attr->value;
  451. // In XHTML, empty values should never exist, so we repeat the value
  452. if (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_XHTML))
  453. {
  454. $value = $name;
  455. }
  456. // For HTML, empty is fine
  457. elseif (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_HTML))
  458. {
  459. $attrs[] = $name;
  460. continue;
  461. }
  462. // Standard attribute text
  463. $attrs[] = $name . '="' . $attr->value . '"';
  464. }
  465. $text .= ' ' . implode(' ', $attrs);
  466. }
  467. $text .= '>';
  468. $fragment->appendChild(new DOMText($text));
  469. }
  470. $number = $element->childNodes->length;
  471. for ($i = $number; $i > 0; $i--)
  472. {
  473. $child = $element->childNodes->item(0);
  474. $fragment->appendChild($child);
  475. }
  476. if (!in_array($tag, array('script', 'style')))
  477. {
  478. $fragment->appendChild(new DOMText('</' . $tag . '>'));
  479. }
  480. $element->parentNode->replaceChild($fragment, $element);
  481. }
  482. return;
  483. }
  484. elseif (in_array($tag, array('script', 'style')))
  485. {
  486. foreach ($elements as $element)
  487. {
  488. $element->parentNode->removeChild($element);
  489. }
  490. return;
  491. }
  492. else
  493. {
  494. foreach ($elements as $element)
  495. {
  496. $fragment = $document->createDocumentFragment();
  497. $number = $element->childNodes->length;
  498. for ($i = $number; $i > 0; $i--)
  499. {
  500. $child = $element->childNodes->item(0);
  501. $fragment->appendChild($child);
  502. }
  503. $element->parentNode->replaceChild($fragment, $element);
  504. }
  505. }
  506. }
  507. protected function strip_attr($attrib, $xpath)
  508. {
  509. $elements = $xpath->query('//*[@' . $attrib . ']');
  510. foreach ($elements as $element)
  511. {
  512. $element->removeAttribute($attrib);
  513. }
  514. }
  515. protected function add_attr($tag, $valuePairs, $document)
  516. {
  517. $elements = $document->getElementsByTagName($tag);
  518. foreach ($elements as $element)
  519. {
  520. foreach ($valuePairs as $attrib => $value)
  521. {
  522. $element->setAttribute($attrib, $value);
  523. }
  524. }
  525. }
  526. }