PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/SimplePie/Sanitize.php

https://bitbucket.org/abnopanda/wordpress
PHP | 549 lines | 416 code | 54 blank | 79 comment | 57 complexity | dd645cf5e9b2064290eec85a6715a349 MD5 | raw file
  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.3.1
  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 $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', 'class', '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 strip_comments($strip = false)
  167. {
  168. $this->strip_comments = (bool) $strip;
  169. }
  170. public function set_output_encoding($encoding = 'UTF-8')
  171. {
  172. $this->output_encoding = (string) $encoding;
  173. }
  174. /**
  175. * Set element/attribute key/value pairs of HTML attributes
  176. * containing URLs that need to be resolved relative to the feed
  177. *
  178. * Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
  179. * |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
  180. * |q|@cite
  181. *
  182. * @since 1.0
  183. * @param array|null $element_attribute Element/attribute key/value pairs, null for default
  184. */
  185. public function set_url_replacements($element_attribute = null)
  186. {
  187. if ($element_attribute === null)
  188. {
  189. $element_attribute = array(
  190. 'a' => 'href',
  191. 'area' => 'href',
  192. 'blockquote' => 'cite',
  193. 'del' => 'cite',
  194. 'form' => 'action',
  195. 'img' => array(
  196. 'longdesc',
  197. 'src'
  198. ),
  199. 'input' => 'src',
  200. 'ins' => 'cite',
  201. 'q' => 'cite'
  202. );
  203. }
  204. $this->replace_url_attributes = (array) $element_attribute;
  205. }
  206. public function sanitize($data, $type, $base = '')
  207. {
  208. $data = trim($data);
  209. if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI)
  210. {
  211. if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML)
  212. {
  213. 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))
  214. {
  215. $type |= SIMPLEPIE_CONSTRUCT_HTML;
  216. }
  217. else
  218. {
  219. $type |= SIMPLEPIE_CONSTRUCT_TEXT;
  220. }
  221. }
  222. if ($type & SIMPLEPIE_CONSTRUCT_BASE64)
  223. {
  224. $data = base64_decode($data);
  225. }
  226. if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML))
  227. {
  228. $document = new DOMDocument();
  229. $document->encoding = 'UTF-8';
  230. $data = $this->preprocess($data, $type);
  231. set_error_handler(array('SimplePie_Misc', 'silence_errors'));
  232. $document->loadHTML($data);
  233. restore_error_handler();
  234. // Strip comments
  235. if ($this->strip_comments)
  236. {
  237. $xpath = new DOMXPath($document);
  238. $comments = $xpath->query('//comment()');
  239. foreach ($comments as $comment)
  240. {
  241. $comment->parentNode->removeChild($comment);
  242. }
  243. }
  244. // Strip out HTML tags and attributes that might cause various security problems.
  245. // Based on recommendations by Mark Pilgrim at:
  246. // http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
  247. if ($this->strip_htmltags)
  248. {
  249. foreach ($this->strip_htmltags as $tag)
  250. {
  251. $this->strip_tag($tag, $document, $type);
  252. }
  253. }
  254. if ($this->strip_attributes)
  255. {
  256. foreach ($this->strip_attributes as $attrib)
  257. {
  258. $this->strip_attr($attrib, $document);
  259. }
  260. }
  261. // Replace relative URLs
  262. $this->base = $base;
  263. foreach ($this->replace_url_attributes as $element => $attributes)
  264. {
  265. $this->replace_urls($document, $element, $attributes);
  266. }
  267. // If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
  268. if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache)
  269. {
  270. $images = $document->getElementsByTagName('img');
  271. foreach ($images as $img)
  272. {
  273. if ($img->hasAttribute('src'))
  274. {
  275. $image_url = call_user_func($this->cache_name_function, $img->getAttribute('src'));
  276. $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, $image_url, 'spi'));
  277. if ($cache->load())
  278. {
  279. $img->setAttribute('src', $this->image_handler . $image_url);
  280. }
  281. else
  282. {
  283. $file = $this->registry->create('File', array($img['attribs']['src']['data'], $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen));
  284. $headers = $file->headers;
  285. if ($file->success && ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300)))
  286. {
  287. if ($cache->save(array('headers' => $file->headers, 'body' => $file->body)))
  288. {
  289. $img->setAttribute('src', $this->image_handler . $image_url);
  290. }
  291. else
  292. {
  293. 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);
  294. }
  295. }
  296. }
  297. }
  298. }
  299. }
  300. // Remove the DOCTYPE
  301. // Seems to cause segfaulting if we don't do this
  302. if ($document->firstChild instanceof DOMDocumentType)
  303. {
  304. $document->removeChild($document->firstChild);
  305. }
  306. // Move everything from the body to the root
  307. $real_body = $document->getElementsByTagName('body')->item(0)->childNodes->item(0);
  308. $document->replaceChild($real_body, $document->firstChild);
  309. // Finally, convert to a HTML string
  310. $data = trim($document->saveHTML());
  311. if ($this->remove_div)
  312. {
  313. $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data);
  314. $data = preg_replace('/<\/div>$/', '', $data);
  315. }
  316. else
  317. {
  318. $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
  319. }
  320. }
  321. if ($type & SIMPLEPIE_CONSTRUCT_IRI)
  322. {
  323. $absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base));
  324. if ($absolute !== false)
  325. {
  326. $data = $absolute;
  327. }
  328. }
  329. if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI))
  330. {
  331. $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
  332. }
  333. if ($this->output_encoding !== 'UTF-8')
  334. {
  335. $data = $this->registry->call('Misc', 'change_encoding', array($data, 'UTF-8', $this->output_encoding));
  336. }
  337. }
  338. return $data;
  339. }
  340. protected function preprocess($html, $type)
  341. {
  342. $ret = '';
  343. if ($type & ~SIMPLEPIE_CONSTRUCT_XHTML)
  344. {
  345. // Atom XHTML constructs are wrapped with a div by default
  346. // Note: No protection if $html contains a stray </div>!
  347. $html = '<div>' . $html . '</div>';
  348. $ret .= '<!DOCTYPE html>';
  349. $content_type = 'text/html';
  350. }
  351. else
  352. {
  353. $ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  354. $content_type = 'application/xhtml+xml';
  355. }
  356. $ret .= '<html><head>';
  357. $ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />';
  358. $ret .= '</head><body>' . $html . '</body></html>';
  359. return $ret;
  360. }
  361. public function replace_urls($document, $tag, $attributes)
  362. {
  363. if (!is_array($attributes))
  364. {
  365. $attributes = array($attributes);
  366. }
  367. if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags))
  368. {
  369. $elements = $document->getElementsByTagName($tag);
  370. foreach ($elements as $element)
  371. {
  372. foreach ($attributes as $attribute)
  373. {
  374. if ($element->hasAttribute($attribute))
  375. {
  376. $value = $this->registry->call('Misc', 'absolutize_url', array($element->getAttribute($attribute), $this->base));
  377. if ($value !== false)
  378. {
  379. $element->setAttribute($attribute, $value);
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }
  386. public function do_strip_htmltags($match)
  387. {
  388. if ($this->encode_instead_of_strip)
  389. {
  390. if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
  391. {
  392. $match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8');
  393. $match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8');
  394. return "&lt;$match[1]$match[2]&gt;$match[3]&lt;/$match[1]&gt;";
  395. }
  396. else
  397. {
  398. return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8');
  399. }
  400. }
  401. elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
  402. {
  403. return $match[4];
  404. }
  405. else
  406. {
  407. return '';
  408. }
  409. }
  410. protected function strip_tag($tag, $document, $type)
  411. {
  412. $xpath = new DOMXPath($document);
  413. $elements = $xpath->query('body//' . $tag);
  414. if ($this->encode_instead_of_strip)
  415. {
  416. foreach ($elements as $element)
  417. {
  418. $fragment = $document->createDocumentFragment();
  419. // For elements which aren't script or style, include the tag itself
  420. if (!in_array($tag, array('script', 'style')))
  421. {
  422. $text = '<' . $tag;
  423. if ($element->hasAttributes())
  424. {
  425. $attrs = array();
  426. foreach ($element->attributes as $name => $attr)
  427. {
  428. $value = $attr->value;
  429. // In XHTML, empty values should never exist, so we repeat the value
  430. if (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_XHTML))
  431. {
  432. $value = $name;
  433. }
  434. // For HTML, empty is fine
  435. elseif (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_HTML))
  436. {
  437. $attrs[] = $name;
  438. continue;
  439. }
  440. // Standard attribute text
  441. $attrs[] = $name . '="' . $attr->value . '"';
  442. }
  443. $text .= ' ' . implode(' ', $attrs);
  444. }
  445. $text .= '>';
  446. $fragment->appendChild(new DOMText($text));
  447. }
  448. $number = $element->childNodes->length;
  449. for ($i = $number; $i > 0; $i--)
  450. {
  451. $child = $element->childNodes->item(0);
  452. $fragment->appendChild($child);
  453. }
  454. if (!in_array($tag, array('script', 'style')))
  455. {
  456. $fragment->appendChild(new DOMText('</' . $tag . '>'));
  457. }
  458. $element->parentNode->replaceChild($fragment, $element);
  459. }
  460. return;
  461. }
  462. elseif (in_array($tag, array('script', 'style')))
  463. {
  464. foreach ($elements as $element)
  465. {
  466. $element->parentNode->removeChild($element);
  467. }
  468. return;
  469. }
  470. else
  471. {
  472. foreach ($elements as $element)
  473. {
  474. $fragment = $document->createDocumentFragment();
  475. $number = $element->childNodes->length;
  476. for ($i = $number; $i > 0; $i--)
  477. {
  478. $child = $element->childNodes->item(0);
  479. $fragment->appendChild($child);
  480. }
  481. $element->parentNode->replaceChild($fragment, $element);
  482. }
  483. }
  484. }
  485. protected function strip_attr($attrib, $document)
  486. {
  487. $xpath = new DOMXPath($document);
  488. $elements = $xpath->query('//*[@' . $attrib . ']');
  489. foreach ($elements as $element)
  490. {
  491. $element->removeAttribute($attrib);
  492. }
  493. }
  494. }