PageRenderTime 46ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/plaintext/classes/class.simple_html_dom.inc.php

https://github.com/xong/rexsearch
PHP | 1023 lines | 876 code | 76 blank | 71 comment | 92 complexity | 00e470db0a7f8ab571eda51be5582def MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /*******************************************************************************
  3. Version: 1.11 ($Rev: 175 $)
  4. Website: http://sourceforge.net/projects/simplehtmldom/
  5. Author: S.C. Chen <me578022@gmail.com>
  6. Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
  7. Contributions by:
  8. Yousuke Kumakura (Attribute filters)
  9. Vadim Voituk (Negative indexes supports of "find" method)
  10. Antcs (Constructor with automatically load contents either text or file/url)
  11. Licensed under The MIT License
  12. Redistributions of files must retain the above copyright notice.
  13. Edited by Robert Rupf: Added the remove-method, which allows to remove nodes in
  14. the same way you can find them.
  15. *******************************************************************************/
  16. define('HDOM_TYPE_ELEMENT', 1);
  17. define('HDOM_TYPE_COMMENT', 2);
  18. define('HDOM_TYPE_TEXT', 3);
  19. define('HDOM_TYPE_ENDTAG', 4);
  20. define('HDOM_TYPE_ROOT', 5);
  21. define('HDOM_TYPE_UNKNOWN', 6);
  22. define('HDOM_QUOTE_DOUBLE', 0);
  23. define('HDOM_QUOTE_SINGLE', 1);
  24. define('HDOM_QUOTE_NO', 3);
  25. define('HDOM_INFO_BEGIN', 0);
  26. define('HDOM_INFO_END', 1);
  27. define('HDOM_INFO_QUOTE', 2);
  28. define('HDOM_INFO_SPACE', 3);
  29. define('HDOM_INFO_TEXT', 4);
  30. define('HDOM_INFO_INNER', 5);
  31. define('HDOM_INFO_OUTER', 6);
  32. define('HDOM_INFO_ENDSPACE',7);
  33. // helper functions
  34. // -----------------------------------------------------------------------------
  35. // get html dom form file
  36. function file_get_html() {
  37. $dom = new simple_html_dom;
  38. $args = func_get_args();
  39. $dom->load(call_user_func_array('file_get_contents', $args), true);
  40. return $dom;
  41. }
  42. // get html dom form string
  43. function str_get_html($str, $lowercase=true) {
  44. $dom = new simple_html_dom;
  45. $dom->load($str, $lowercase);
  46. return $dom;
  47. }
  48. // dump html dom tree
  49. function dump_html_tree($node, $show_attr=true, $deep=0) {
  50. $lead = str_repeat(' ', $deep);
  51. echo $lead.$node->tag;
  52. if ($show_attr && count($node->attr)>0) {
  53. echo '(';
  54. foreach($node->attr as $k=>$v)
  55. echo "[$k]=>\"".$node->$k.'", ';
  56. echo ')';
  57. }
  58. echo "\n";
  59. foreach($node->nodes as $c)
  60. dump_html_tree($c, $show_attr, $deep+1);
  61. }
  62. // get dom form file (deprecated)
  63. function file_get_dom() {
  64. $dom = new simple_html_dom;
  65. $args = func_get_args();
  66. $dom->load(call_user_func_array('file_get_contents', $args), true);
  67. return $dom;
  68. }
  69. // get dom form string (deprecated)
  70. function str_get_dom($str, $lowercase=true) {
  71. $dom = new simple_html_dom;
  72. $dom->load($str, $lowercase);
  73. return $dom;
  74. }
  75. // simple html dom node
  76. // -----------------------------------------------------------------------------
  77. class simple_html_dom_node {
  78. /*public*/ var $nodetype = HDOM_TYPE_TEXT;
  79. /*public*/ var $tag = 'text';
  80. /*public*/ var $attr = array();
  81. /*public*/ var $children = array();
  82. /*public*/ var $nodes = array();
  83. /*public*/ var $parent = null;
  84. /*public*/ var $_ = array();
  85. /*private*/ var $dom = null;
  86. function __construct($dom) {
  87. $this->dom = $dom;
  88. $dom->nodes[] = $this;
  89. }
  90. function __destruct() {
  91. $this->clear();
  92. }
  93. function __toString() {
  94. return $this->outertext();
  95. }
  96. // clean up memory due to php5 circular references memory leak...
  97. function clear() {
  98. $this->dom = null;
  99. $this->nodes = null;
  100. $this->parent = null;
  101. $this->children = null;
  102. }
  103. // dump node's tree
  104. function dump($show_attr=true) {
  105. dump_html_tree($this, $show_attr);
  106. }
  107. // returns the parent of node
  108. function parent() {
  109. return $this->parent;
  110. }
  111. // returns children of node
  112. function children($idx=-1) {
  113. if ($idx===-1) return $this->children;
  114. if (isset($this->children[$idx])) return $this->children[$idx];
  115. return null;
  116. }
  117. // returns the first child of node
  118. function first_child() {
  119. if (count($this->children)>0) return $this->children[0];
  120. return null;
  121. }
  122. // returns the last child of node
  123. function last_child() {
  124. if (($count=count($this->children))>0) return $this->children[$count-1];
  125. return null;
  126. }
  127. // returns the next sibling of node
  128. function next_sibling() {
  129. if ($this->parent===null) return null;
  130. $idx = 0;
  131. $count = count($this->parent->children);
  132. while ($idx<$count && $this!==$this->parent->children[$idx])
  133. ++$idx;
  134. if (++$idx>=$count) return null;
  135. return $this->parent->children[$idx];
  136. }
  137. // returns the previous sibling of node
  138. function prev_sibling() {
  139. if ($this->parent===null) return null;
  140. $idx = 0;
  141. $count = count($this->parent->children);
  142. while ($idx<$count && $this!==$this->parent->children[$idx])
  143. ++$idx;
  144. if (--$idx<0) return null;
  145. return $this->parent->children[$idx];
  146. }
  147. // get dom node's inner html
  148. function innertext() {
  149. if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
  150. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  151. $ret = '';
  152. foreach($this->nodes as $n)
  153. $ret .= $n->outertext();
  154. return $ret;
  155. }
  156. // get dom node's outer text (with tag)
  157. function outertext() {
  158. if ($this->tag==='root') return $this->innertext();
  159. // trigger callback
  160. if ($this->dom->callback!==null)
  161. call_user_func_array($this->dom->callback, array($this));
  162. if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
  163. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  164. // render begin tag
  165. $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
  166. // render inner text
  167. if (isset($this->_[HDOM_INFO_INNER]))
  168. $ret .= $this->_[HDOM_INFO_INNER];
  169. else {
  170. foreach($this->nodes as $n)
  171. $ret .= $n->outertext();
  172. }
  173. // render end tag
  174. if(isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
  175. $ret .= '</'.$this->tag.'>';
  176. return $ret;
  177. }
  178. // get dom node's plain text
  179. function text() {
  180. if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
  181. switch ($this->nodetype) {
  182. case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  183. case HDOM_TYPE_COMMENT: return '';
  184. case HDOM_TYPE_UNKNOWN: return '';
  185. }
  186. if (strcasecmp($this->tag, 'script')===0) return '';
  187. if (strcasecmp($this->tag, 'style')===0) return '';
  188. $ret = '';
  189. foreach($this->nodes as $n)
  190. $ret .= $n->text().' ';
  191. return $ret;
  192. }
  193. function xmltext() {
  194. $ret = $this->innertext();
  195. $ret = str_ireplace('<![CDATA[', '', $ret);
  196. $ret = str_replace(']]>', '', $ret);
  197. return $ret;
  198. }
  199. // build node's text with tag
  200. function makeup() {
  201. // text, comment, unknown
  202. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  203. $ret = '<'.$this->tag;
  204. $i = -1;
  205. foreach($this->attr as $key=>$val) {
  206. ++$i;
  207. // skip removed attribute
  208. if ($val===null || $val===false)
  209. continue;
  210. $ret .= $this->_[HDOM_INFO_SPACE][$i][0];
  211. //no value attr: nowrap, checked selected...
  212. if ($val===true)
  213. $ret .= $key;
  214. else {
  215. switch($this->_[HDOM_INFO_QUOTE][$i]) {
  216. case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
  217. case HDOM_QUOTE_SINGLE: $quote = '\''; break;
  218. default: $quote = '';
  219. }
  220. $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
  221. }
  222. }
  223. $ret = $this->dom->restore_noise($ret);
  224. return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
  225. }
  226. // find elements by css selector
  227. function find($selector, $idx=null) {
  228. $selectors = $this->parse_selector($selector);
  229. if (($count=count($selectors))===0) return array();
  230. $found_keys = array();
  231. // find each selector
  232. for ($c=0; $c<$count; ++$c) {
  233. if (($levle=count($selectors[0]))===0) return array();
  234. if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
  235. $head = array($this->_[HDOM_INFO_BEGIN]=>1);
  236. // handle descendant selectors, no recursive!
  237. for ($l=0; $l<$levle; ++$l) {
  238. $ret = array();
  239. foreach($head as $k=>$v) {
  240. $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
  241. $n->seek($selectors[$c][$l], $ret);
  242. }
  243. $head = $ret;
  244. }
  245. foreach($head as $k=>$v) {
  246. if (!isset($found_keys[$k]))
  247. $found_keys[$k] = 1;
  248. }
  249. }
  250. // sort keys
  251. ksort($found_keys);
  252. $found = array();
  253. foreach($found_keys as $k=>$v)
  254. $found[] = $this->dom->nodes[$k];
  255. // return nth-element or array
  256. if (is_null($idx)) return $found;
  257. else if ($idx<0) $idx = count($found) + $idx;
  258. return (isset($found[$idx])) ? $found[$idx] : null;
  259. }
  260. // seek for given conditions
  261. /*protected*/ function seek($selector, &$ret) {
  262. list($tag, $key, $val, $exp, $no_key) = $selector;
  263. // xpath index
  264. if ($tag && $key && is_numeric($key)) {
  265. $count = 0;
  266. foreach ($this->children as $c) {
  267. if ($tag==='*' || $tag===$c->tag) {
  268. if (++$count==$key) {
  269. $ret[$c->_[HDOM_INFO_BEGIN]] = 1;
  270. return;
  271. }
  272. }
  273. }
  274. return;
  275. }
  276. $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
  277. if ($end==0) {
  278. $parent = $this->parent;
  279. while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
  280. $end -= 1;
  281. $parent = $parent->parent;
  282. }
  283. $end += $parent->_[HDOM_INFO_END];
  284. }
  285. for($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
  286. $node = $this->dom->nodes[$i];
  287. $pass = true;
  288. if ($tag==='*' && !$key) {
  289. if (in_array($node, $this->children, true))
  290. $ret[$i] = 1;
  291. continue;
  292. }
  293. // compare tag
  294. if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
  295. // compare key
  296. if ($pass && $key) {
  297. if ($no_key) {
  298. if (isset($node->attr[$key])) $pass=false;
  299. }
  300. else if (!isset($node->attr[$key])) $pass=false;
  301. }
  302. // compare value
  303. if ($pass && $key && $val && $val!=='*') {
  304. $check = $this->match($exp, $val, $node->attr[$key]);
  305. // handle multiple class
  306. if (!$check && strcasecmp($key, 'class')===0) {
  307. foreach(explode(' ',$node->attr[$key]) as $k) {
  308. $check = $this->match($exp, $val, $k);
  309. if ($check) break;
  310. }
  311. }
  312. if (!$check) $pass = false;
  313. }
  314. if ($pass) $ret[$i] = 1;
  315. unset($node);
  316. }
  317. }
  318. /*protected*/ function match($exp, $pattern, $value) {
  319. switch ($exp) {
  320. case '=':
  321. return ($value===$pattern);
  322. case '!=':
  323. return ($value!==$pattern);
  324. case '^=':
  325. return preg_match("/^".preg_quote($pattern,'/')."/", $value);
  326. case '$=':
  327. return preg_match("/".preg_quote($pattern,'/')."$/", $value);
  328. case '*=':
  329. if ($pattern[0]=='/')
  330. return preg_match($pattern, $value);
  331. return preg_match("/".$pattern."/i", $value);
  332. }
  333. return false;
  334. }
  335. /*protected*/ function parse_selector($selector_string) {
  336. // pattern of CSS selectors, modified from mootools
  337. $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
  338. preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);
  339. $selectors = array();
  340. $result = array();
  341. //print_r($matches);
  342. foreach ($matches as $m) {
  343. $m[0] = trim($m[0]);
  344. if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
  345. // for borwser grnreated xpath
  346. if ($m[1]==='tbody') continue;
  347. list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
  348. if(!empty($m[2])) {$key='id'; $val=$m[2];}
  349. if(!empty($m[3])) {$key='class'; $val=$m[3];}
  350. if(!empty($m[4])) {$key=$m[4];}
  351. if(!empty($m[5])) {$exp=$m[5];}
  352. if(!empty($m[6])) {$val=$m[6];}
  353. // convert to lowercase
  354. if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);}
  355. //elements that do NOT have the specified attribute
  356. if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;}
  357. $result[] = array($tag, $key, $val, $exp, $no_key);
  358. if (trim($m[7])===',') {
  359. $selectors[] = $result;
  360. $result = array();
  361. }
  362. }
  363. if (count($result)>0)
  364. $selectors[] = $result;
  365. return $selectors;
  366. }
  367. function __get($name) {
  368. if (isset($this->attr[$name])) return $this->attr[$name];
  369. switch($name) {
  370. case 'outertext': return $this->outertext();
  371. case 'innertext': return $this->innertext();
  372. case 'plaintext': return $this->text();
  373. case 'xmltext': return $this->xmltext();
  374. default: return array_key_exists($name, $this->attr);
  375. }
  376. }
  377. function __set($name, $value) {
  378. switch($name) {
  379. case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
  380. case 'innertext':
  381. if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
  382. return $this->_[HDOM_INFO_INNER] = $value;
  383. }
  384. if (!isset($this->attr[$name])) {
  385. $this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
  386. $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
  387. }
  388. $this->attr[$name] = $value;
  389. }
  390. function __isset($name) {
  391. switch($name) {
  392. case 'outertext': return true;
  393. case 'innertext': return true;
  394. case 'plaintext': return true;
  395. }
  396. //no value attr: nowrap, checked selected...
  397. return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
  398. }
  399. function __unset($name) {
  400. if (isset($this->attr[$name]))
  401. unset($this->attr[$name]);
  402. }
  403. // camel naming conventions
  404. function getAllAttributes() {return $this->attr;}
  405. function getAttribute($name) {return $this->__get($name);}
  406. function setAttribute($name, $value) {$this->__set($name, $value);}
  407. function hasAttribute($name) {return $this->__isset($name);}
  408. function removeAttribute($name) {$this->__set($name, null);}
  409. function getElementById($id) {return $this->find("#$id", 0);}
  410. function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
  411. function getElementByTagName($name) {return $this->find($name, 0);}
  412. function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
  413. function parentNode() {return $this->parent();}
  414. function childNodes($idx=-1) {return $this->children($idx);}
  415. function firstChild() {return $this->first_child();}
  416. function lastChild() {return $this->last_child();}
  417. function nextSibling() {return $this->next_sibling();}
  418. function previousSibling() {return $this->prev_sibling();}
  419. // Added by Robert Rupf
  420. // remove elements by css selector
  421. function remove($selector) {
  422. $selectors = $this->parse_selector($selector);
  423. if (($count=count($selectors))===0) return array();
  424. $found_keys = array();
  425. // find each selector
  426. for ($c=0; $c<$count; ++$c) {
  427. if (($levle=count($selectors[0]))===0) return array();
  428. if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
  429. $head = array($this->_[HDOM_INFO_BEGIN]=>1);
  430. // handle descendant selectors, no recursive!
  431. for ($l=0; $l<$levle; ++$l) {
  432. $ret = array();
  433. foreach($head as $k=>$v) {
  434. $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
  435. $n->seek($selectors[$c][$l], $ret);
  436. }
  437. $head = $ret;
  438. }
  439. foreach($head as $k=>$v) {
  440. if (!isset($found_keys[$k]))
  441. $found_keys[$k] = 1;
  442. }
  443. }
  444. // sort keys
  445. ksort($found_keys);
  446. $found = array();
  447. foreach($found_keys as $k=>$v)
  448. $this->dom->nodes[$k]->outertext = '';
  449. }
  450. }
  451. // simple html dom parser
  452. // -----------------------------------------------------------------------------
  453. class simple_html_dom {
  454. /*public*/ var $root = null;
  455. /*public*/ var $nodes = array();
  456. /*public*/ var $callback = null;
  457. /*public*/ var $lowercase = false;
  458. /*protected*/ var $pos;
  459. /*protected*/ var $doc;
  460. /*protected*/ var $char;
  461. /*protected*/ var $size;
  462. /*protected*/ var $cursor;
  463. /*protected*/ var $parent;
  464. /*protected*/ var $noise = array();
  465. /*protected*/ var $token_blank = " \t\r\n";
  466. /*protected*/ var $token_equal = ' =/>';
  467. /*protected*/ var $token_slash = " />\r\n\t";
  468. /*protected*/ var $token_attr = ' >';
  469. // use isset instead of in_array, performance boost about 30%...
  470. /*protected*/ var $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
  471. /*protected*/ var $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
  472. /*protected*/ var $optional_closing_tags = array(
  473. 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
  474. 'th'=>array('th'=>1),
  475. 'td'=>array('td'=>1),
  476. 'li'=>array('li'=>1),
  477. 'dt'=>array('dt'=>1, 'dd'=>1),
  478. 'dd'=>array('dd'=>1, 'dt'=>1),
  479. 'dl'=>array('dd'=>1, 'dt'=>1),
  480. 'p'=>array('p'=>1),
  481. 'nobr'=>array('nobr'=>1),
  482. );
  483. function __construct($str=null) {
  484. if ($str) {
  485. if (preg_match("/^http:\/\//i",$str) || is_file($str))
  486. $this->load_file($str);
  487. else
  488. $this->load($str);
  489. }
  490. }
  491. function __destruct() {
  492. $this->clear();
  493. }
  494. // load html from string
  495. function load($str, $lowercase=true) {
  496. // prepare
  497. $this->prepare($str, $lowercase);
  498. // strip out comments
  499. $this->remove_noise("'<!--(.*?)-->'is");
  500. // strip out cdata
  501. $this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
  502. // strip out <style> tags
  503. $this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
  504. $this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
  505. // strip out <script> tags
  506. $this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
  507. $this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
  508. // strip out preformatted tags
  509. $this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
  510. // strip out server side scripts
  511. $this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
  512. // strip smarty scripts
  513. $this->remove_noise("'(\{\w)(.*?)(\})'s", true);
  514. // parsing
  515. while ($this->parse());
  516. // end
  517. $this->root->_[HDOM_INFO_END] = $this->cursor;
  518. }
  519. // load html from file
  520. function load_file() {
  521. $args = func_get_args();
  522. $this->load(call_user_func_array('file_get_contents', $args), true);
  523. }
  524. // set callback function
  525. function set_callback($function_name) {
  526. $this->callback = $function_name;
  527. }
  528. // remove callback function
  529. function remove_callback() {
  530. $this->callback = null;
  531. }
  532. // save dom as string
  533. function save($filepath='') {
  534. $ret = $this->root->innertext();
  535. if ($filepath!=='') file_put_contents($filepath, $ret);
  536. return $ret;
  537. }
  538. // find dom node by css selector
  539. function find($selector, $idx=null) {
  540. return $this->root->find($selector, $idx);
  541. }
  542. // clean up memory due to php5 circular references memory leak...
  543. function clear() {
  544. foreach($this->nodes as $n) {$n->clear(); $n = null;}
  545. if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
  546. if (isset($this->root)) {$this->root->clear(); unset($this->root);}
  547. unset($this->doc);
  548. unset($this->noise);
  549. }
  550. function dump($show_attr=true) {
  551. $this->root->dump($show_attr);
  552. }
  553. // prepare HTML data and init everything
  554. /*protected*/ function prepare($str, $lowercase=true) {
  555. $this->clear();
  556. $this->doc = $str;
  557. $this->pos = 0;
  558. $this->cursor = 1;
  559. $this->noise = array();
  560. $this->nodes = array();
  561. $this->lowercase = $lowercase;
  562. $this->root = new simple_html_dom_node($this);
  563. $this->root->tag = 'root';
  564. $this->root->_[HDOM_INFO_BEGIN] = -1;
  565. $this->root->nodetype = HDOM_TYPE_ROOT;
  566. $this->parent = $this->root;
  567. // set the length of content
  568. $this->size = strlen($str);
  569. if ($this->size>0) $this->char = $this->doc[0];
  570. }
  571. // parse html content
  572. /*protected*/ function parse() {
  573. if (($s = $this->copy_until_char('<'))==='')
  574. return $this->read_tag();
  575. // text
  576. $node = new simple_html_dom_node($this);
  577. ++$this->cursor;
  578. $node->_[HDOM_INFO_TEXT] = $s;
  579. $this->link_nodes($node, false);
  580. return true;
  581. }
  582. // read tag info
  583. /*protected*/ function read_tag() {
  584. if ($this->char!=='<') {
  585. $this->root->_[HDOM_INFO_END] = $this->cursor;
  586. return false;
  587. }
  588. $begin_tag_pos = $this->pos;
  589. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  590. // end tag
  591. if ($this->char==='/') {
  592. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  593. $this->skip($this->token_blank_t);
  594. $tag = $this->copy_until_char('>');
  595. // skip attributes in end tag
  596. if (($pos = strpos($tag, ' '))!==false)
  597. $tag = substr($tag, 0, $pos);
  598. $parent_lower = strtolower($this->parent->tag);
  599. $tag_lower = strtolower($tag);
  600. if ($parent_lower!==$tag_lower) {
  601. if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower])) {
  602. $this->parent->_[HDOM_INFO_END] = 0;
  603. $org_parent = $this->parent;
  604. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  605. $this->parent = $this->parent->parent;
  606. if (strtolower($this->parent->tag)!==$tag_lower) {
  607. $this->parent = $org_parent; // restore origonal parent
  608. if ($this->parent->parent) $this->parent = $this->parent->parent;
  609. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  610. return $this->as_text_node($tag);
  611. }
  612. }
  613. else if (($this->parent->parent) && isset($this->block_tags[$tag_lower])) {
  614. $this->parent->_[HDOM_INFO_END] = 0;
  615. $org_parent = $this->parent;
  616. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  617. $this->parent = $this->parent->parent;
  618. if (strtolower($this->parent->tag)!==$tag_lower) {
  619. $this->parent = $org_parent; // restore origonal parent
  620. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  621. return $this->as_text_node($tag);
  622. }
  623. }
  624. else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower) {
  625. $this->parent->_[HDOM_INFO_END] = 0;
  626. $this->parent = $this->parent->parent;
  627. }
  628. else
  629. return $this->as_text_node($tag);
  630. }
  631. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  632. if ($this->parent->parent) $this->parent = $this->parent->parent;
  633. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  634. return true;
  635. }
  636. $node = new simple_html_dom_node($this);
  637. $node->_[HDOM_INFO_BEGIN] = $this->cursor;
  638. ++$this->cursor;
  639. $tag = $this->copy_until($this->token_slash);
  640. // doctype, cdata & comments...
  641. if (isset($tag[0]) && $tag[0]==='!') {
  642. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
  643. if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
  644. $node->nodetype = HDOM_TYPE_COMMENT;
  645. $node->tag = 'comment';
  646. } else {
  647. $node->nodetype = HDOM_TYPE_UNKNOWN;
  648. $node->tag = 'unknown';
  649. }
  650. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  651. $this->link_nodes($node, true);
  652. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  653. return true;
  654. }
  655. // text
  656. if ($pos=strpos($tag, '<')!==false) {
  657. $tag = '<' . substr($tag, 0, -1);
  658. $node->_[HDOM_INFO_TEXT] = $tag;
  659. $this->link_nodes($node, false);
  660. $this->char = $this->doc[--$this->pos]; // prev
  661. return true;
  662. }
  663. if (!preg_match("/^[\w-:]+$/", $tag)) {
  664. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
  665. if ($this->char==='<') {
  666. $this->link_nodes($node, false);
  667. return true;
  668. }
  669. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  670. $this->link_nodes($node, false);
  671. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  672. return true;
  673. }
  674. // begin tag
  675. $node->nodetype = HDOM_TYPE_ELEMENT;
  676. $tag_lower = strtolower($tag);
  677. $node->tag = ($this->lowercase) ? $tag_lower : $tag;
  678. // handle optional closing tags
  679. if (isset($this->optional_closing_tags[$tag_lower]) ) {
  680. while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)])) {
  681. $this->parent->_[HDOM_INFO_END] = 0;
  682. $this->parent = $this->parent->parent;
  683. }
  684. $node->parent = $this->parent;
  685. }
  686. $guard = 0; // prevent infinity loop
  687. $space = array($this->copy_skip($this->token_blank), '', '');
  688. // attributes
  689. do {
  690. if ($this->char!==null && $space[0]==='') break;
  691. $name = $this->copy_until($this->token_equal);
  692. if($guard===$this->pos) {
  693. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  694. continue;
  695. }
  696. $guard = $this->pos;
  697. // handle endless '<'
  698. if($this->pos>=$this->size-1 && $this->char!=='>') {
  699. $node->nodetype = HDOM_TYPE_TEXT;
  700. $node->_[HDOM_INFO_END] = 0;
  701. $node->_[HDOM_INFO_TEXT] = '<'.$tag . $space[0] . $name;
  702. $node->tag = 'text';
  703. $this->link_nodes($node, false);
  704. return true;
  705. }
  706. // handle mismatch '<'
  707. if($this->doc[$this->pos-1]=='<') {
  708. $node->nodetype = HDOM_TYPE_TEXT;
  709. $node->tag = 'text';
  710. $node->attr = array();
  711. $node->_[HDOM_INFO_END] = 0;
  712. $node->_[HDOM_INFO_TEXT] = substr($this->doc, $begin_tag_pos, $this->pos-$begin_tag_pos-1);
  713. $this->pos -= 2;
  714. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  715. $this->link_nodes($node, false);
  716. return true;
  717. }
  718. if ($name!=='/' && $name!=='') {
  719. $space[1] = $this->copy_skip($this->token_blank);
  720. $name = $this->restore_noise($name);
  721. if ($this->lowercase) $name = strtolower($name);
  722. if ($this->char==='=') {
  723. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  724. $this->parse_attr($node, $name, $space);
  725. }
  726. else {
  727. //no value attr: nowrap, checked selected...
  728. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
  729. $node->attr[$name] = true;
  730. if ($this->char!='>') $this->char = $this->doc[--$this->pos]; // prev
  731. }
  732. $node->_[HDOM_INFO_SPACE][] = $space;
  733. $space = array($this->copy_skip($this->token_blank), '', '');
  734. }
  735. else
  736. break;
  737. } while($this->char!=='>' && $this->char!=='/');
  738. $this->link_nodes($node, true);
  739. $node->_[HDOM_INFO_ENDSPACE] = $space[0];
  740. // check self closing
  741. if ($this->copy_until_char_escape('>')==='/') {
  742. $node->_[HDOM_INFO_ENDSPACE] .= '/';
  743. $node->_[HDOM_INFO_END] = 0;
  744. }
  745. else {
  746. // reset parent
  747. if (!isset($this->self_closing_tags[strtolower($node->tag)])) $this->parent = $node;
  748. }
  749. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  750. return true;
  751. }
  752. // parse attributes
  753. /*protected*/ function parse_attr($node, $name, &$space) {
  754. $space[2] = $this->copy_skip($this->token_blank);
  755. switch($this->char) {
  756. case '"':
  757. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
  758. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  759. $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('"'));
  760. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  761. break;
  762. case '\'':
  763. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_SINGLE;
  764. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  765. $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('\''));
  766. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  767. break;
  768. default:
  769. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
  770. $node->attr[$name] = $this->restore_noise($this->copy_until($this->token_attr));
  771. }
  772. }
  773. // link node's parent
  774. /*protected*/ function link_nodes(&$node, $is_child) {
  775. $node->parent = $this->parent;
  776. $this->parent->nodes[] = $node;
  777. if ($is_child)
  778. $this->parent->children[] = $node;
  779. }
  780. // as a text node
  781. /*protected*/ function as_text_node($tag) {
  782. $node = new simple_html_dom_node($this);
  783. ++$this->cursor;
  784. $node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
  785. $this->link_nodes($node, false);
  786. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  787. return true;
  788. }
  789. /*protected*/ function skip($chars) {
  790. $this->pos += strspn($this->doc, $chars, $this->pos);
  791. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  792. }
  793. /*protected*/ function copy_skip($chars) {
  794. $pos = $this->pos;
  795. $len = strspn($this->doc, $chars, $pos);
  796. $this->pos += $len;
  797. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  798. if ($len===0) return '';
  799. return substr($this->doc, $pos, $len);
  800. }
  801. /*protected*/ function copy_until($chars) {
  802. $pos = $this->pos;
  803. $len = strcspn($this->doc, $chars, $pos);
  804. $this->pos += $len;
  805. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  806. return substr($this->doc, $pos, $len);
  807. }
  808. /*protected*/ function copy_until_char($char) {
  809. if ($this->char===null) return '';
  810. if (($pos = strpos($this->doc, $char, $this->pos))===false) {
  811. $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
  812. $this->char = null;
  813. $this->pos = $this->size;
  814. return $ret;
  815. }
  816. if ($pos===$this->pos) return '';
  817. $pos_old = $this->pos;
  818. $this->char = $this->doc[$pos];
  819. $this->pos = $pos;
  820. return substr($this->doc, $pos_old, $pos-$pos_old);
  821. }
  822. /*protected*/ function copy_until_char_escape($char) {
  823. if ($this->char===null) return '';
  824. $start = $this->pos;
  825. while(1) {
  826. if (($pos = strpos($this->doc, $char, $start))===false) {
  827. $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
  828. $this->char = null;
  829. $this->pos = $this->size;
  830. return $ret;
  831. }
  832. if ($pos===$this->pos) return '';
  833. if ($this->doc[$pos-1]==='\\') {
  834. $start = $pos+1;
  835. continue;
  836. }
  837. $pos_old = $this->pos;
  838. $this->char = $this->doc[$pos];
  839. $this->pos = $pos;
  840. return substr($this->doc, $pos_old, $pos-$pos_old);
  841. }
  842. }
  843. // remove noise from html content
  844. /*protected*/ function remove_noise($pattern, $remove_tag=false) {
  845. $count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
  846. for ($i=$count-1; $i>-1; --$i) {
  847. $key = '___noise___'.sprintf('% 3d', count($this->noise)+100);
  848. $idx = ($remove_tag) ? 0 : 1;
  849. $this->noise[$key] = $matches[$i][$idx][0];
  850. $this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
  851. }
  852. // reset the length of content
  853. $this->size = strlen($this->doc);
  854. if ($this->size>0) $this->char = $this->doc[0];
  855. }
  856. // restore noise to html content
  857. function restore_noise($text) {
  858. while(($pos=strpos($text, '___noise___'))!==false) {
  859. $key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13];
  860. if (isset($this->noise[$key]))
  861. $text = substr($text, 0, $pos).$this->noise[$key].substr($text, $pos+14);
  862. }
  863. return $text;
  864. }
  865. function __toString() {
  866. return $this->root->innertext();
  867. }
  868. function __get($name) {
  869. switch($name) {
  870. case 'outertext': return $this->root->innertext();
  871. case 'innertext': return $this->root->innertext();
  872. case 'plaintext': return $this->root->text();
  873. }
  874. }
  875. // camel naming conventions
  876. function childNodes($idx=-1) {return $this->root->childNodes($idx);}
  877. function firstChild() {return $this->root->first_child();}
  878. function lastChild() {return $this->root->last_child();}
  879. function getElementById($id) {return $this->find("#$id", 0);}
  880. function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
  881. function getElementByTagName($name) {return $this->find($name, 0);}
  882. function getElementsByTagName($name, $idx=-1) {return $this->find($name, $idx);}
  883. function loadFile() {$args = func_get_args();$this->load(call_user_func_array('file_get_contents', $args), true);}
  884. // Added by Robert Rupf
  885. // remove dom node by css selector
  886. function remove($selector) {
  887. $this->root->remove($selector);
  888. }
  889. }