Sanitize.php 16 KB

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