PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/transposh-translation-filter-for-wordpress/core/shd/simple_html_dom.php

https://bitbucket.org/lgorence/quickpress
PHP | 985 lines | 850 code | 68 blank | 67 comment | 88 complexity | 58b4d0a5e55adef7db08ea4ffa99ac46 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, AGPL-1.0
  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. *******************************************************************************/
  14. // avoid duplicate loading on different files
  15. if (!function_exists("file_get_html")) {
  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 $nodetype = HDOM_TYPE_TEXT;
  79. public $tag = 'text';
  80. public $attr = array();
  81. public $children = array();
  82. public $nodes = array();
  83. public $parent = null;
  84. public $_ = array();
  85. private $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. }
  420. // simple html dom parser
  421. // -----------------------------------------------------------------------------
  422. class simple_html_dom {
  423. public $root = null;
  424. public $nodes = array();
  425. public $callback = null;
  426. public $lowercase = false;
  427. protected $pos;
  428. protected $doc;
  429. protected $char;
  430. protected $size;
  431. protected $cursor;
  432. protected $parent;
  433. public $noise = array();
  434. protected $token_blank = " \t\r\n";
  435. protected $token_equal = ' =/>';
  436. protected $token_slash = " />\r\n\t";
  437. protected $token_attr = ' >';
  438. // use isset instead of in_array, performance boost about 30%...
  439. protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
  440. protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
  441. protected $optional_closing_tags = array(
  442. 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
  443. 'th'=>array('th'=>1),
  444. 'td'=>array('td'=>1),
  445. 'li'=>array('li'=>1),
  446. 'dt'=>array('dt'=>1, 'dd'=>1),
  447. 'dd'=>array('dd'=>1, 'dt'=>1),
  448. 'dl'=>array('dd'=>1, 'dt'=>1),
  449. 'p'=>array('p'=>1),
  450. 'nobr'=>array('nobr'=>1),
  451. 'link'=>array('link'=>1),
  452. );
  453. function __construct($str=null) {
  454. if ($str) {
  455. if (preg_match("/^http:\/\//i",$str) || is_file($str))
  456. $this->load_file($str);
  457. else
  458. $this->load($str);
  459. }
  460. }
  461. function __destruct() {
  462. $this->clear();
  463. }
  464. // load html from string
  465. function load($str, $lowercase=true) {
  466. // prepare
  467. $this->prepare($str, $lowercase);
  468. // strip out comments
  469. //
  470. /* $this->remove_noise("'<?xml(.*?)?>'is", true);*/
  471. $this->remove_noise("'<!--(.*?)-->'is");
  472. // strip out cdata
  473. $this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
  474. // strip out <script> tags
  475. $this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
  476. $this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
  477. // strip out <style> tags
  478. $this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
  479. $this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
  480. // strip out preformatted tags
  481. $this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
  482. // strip out server side scripts
  483. $this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
  484. // strip smarty scripts
  485. $this->remove_noise("'(\{\w)(.*?)(\})'s", true);
  486. // parsing
  487. while ($this->parse());
  488. // end
  489. $this->root->_[HDOM_INFO_END] = $this->cursor;
  490. }
  491. // load html from file
  492. function load_file() {
  493. $args = func_get_args();
  494. $this->load(call_user_func_array('file_get_contents', $args), true);
  495. }
  496. // set callback function
  497. function set_callback($function_name) {
  498. $this->callback = $function_name;
  499. }
  500. // remove callback function
  501. function remove_callback() {
  502. $this->callback = null;
  503. }
  504. // save dom as string
  505. function save($filepath='') {
  506. $ret = $this->root->innertext();
  507. if ($filepath!=='') file_put_contents($filepath, $ret);
  508. return $ret;
  509. }
  510. // find dom node by css selector
  511. function find($selector, $idx=null) {
  512. return $this->root->find($selector, $idx);
  513. }
  514. // clean up memory due to php5 circular references memory leak...
  515. function clear() {
  516. foreach($this->nodes as $n) {$n->clear(); $n = null;}
  517. // This add next line is documented in the sourceforge repository. 2977248 as a fix for ongoing memory leaks that occur even with the use of clear.
  518. if (isset($this->children)) foreach ($this->children as $n) {$n->clear(); $n = null;}
  519. if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
  520. if (isset($this->root)) {$this->root->clear(); unset($this->root);}
  521. unset($this->doc);
  522. unset($this->noise);
  523. }
  524. function dump($show_attr=true) {
  525. $this->root->dump($show_attr);
  526. }
  527. // prepare HTML data and init everything
  528. protected function prepare($str, $lowercase=true) {
  529. $this->clear();
  530. $this->doc = $str;
  531. $this->pos = 0;
  532. $this->cursor = 1;
  533. $this->noise = array();
  534. $this->nodes = array();
  535. $this->lowercase = $lowercase;
  536. $this->root = new simple_html_dom_node($this);
  537. $this->root->tag = 'root';
  538. $this->root->_[HDOM_INFO_BEGIN] = -1;
  539. $this->root->nodetype = HDOM_TYPE_ROOT;
  540. $this->parent = $this->root;
  541. // set the length of content
  542. $this->size = strlen($str);
  543. if ($this->size>0) $this->char = $this->doc[0];
  544. }
  545. // parse html content
  546. protected function parse() {
  547. if (($s = $this->copy_until_char('<'))==='')
  548. return $this->read_tag();
  549. // text
  550. $node = new simple_html_dom_node($this);
  551. ++$this->cursor;
  552. $node->_[HDOM_INFO_TEXT] = $s;
  553. $this->link_nodes($node, false);
  554. return true;
  555. }
  556. // read tag info
  557. protected function read_tag() {
  558. if ($this->char!=='<') {
  559. $this->root->_[HDOM_INFO_END] = $this->cursor;
  560. return false;
  561. }
  562. $begin_tag_pos = $this->pos;
  563. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  564. // end tag
  565. if ($this->char==='/') {
  566. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  567. $this->skip($this->token_blank);
  568. $tag = $this->copy_until_char('>');
  569. // skip attributes in end tag
  570. if (($pos = strpos($tag, ' '))!==false)
  571. $tag = substr($tag, 0, $pos);
  572. $parent_lower = strtolower($this->parent->tag);
  573. $tag_lower = strtolower($tag);
  574. if ($parent_lower!==$tag_lower) {
  575. if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower])) {
  576. $this->parent->_[HDOM_INFO_END] = 0;
  577. $org_parent = $this->parent;
  578. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  579. $this->parent = $this->parent->parent;
  580. if (strtolower($this->parent->tag)!==$tag_lower) {
  581. $this->parent = $org_parent; // restore origonal parent
  582. if ($this->parent->parent) $this->parent = $this->parent->parent;
  583. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  584. return $this->as_text_node($tag);
  585. }
  586. }
  587. else if (($this->parent->parent) && isset($this->block_tags[$tag_lower])) {
  588. $this->parent->_[HDOM_INFO_END] = 0;
  589. $org_parent = $this->parent;
  590. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  591. $this->parent = $this->parent->parent;
  592. if (strtolower($this->parent->tag)!==$tag_lower) {
  593. $this->parent = $org_parent; // restore origonal parent
  594. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  595. return $this->as_text_node($tag);
  596. }
  597. }
  598. else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower) {
  599. $this->parent->_[HDOM_INFO_END] = 0;
  600. $this->parent = $this->parent->parent;
  601. }
  602. else
  603. return $this->as_text_node($tag);
  604. }
  605. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  606. if ($this->parent->parent) $this->parent = $this->parent->parent;
  607. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  608. return true;
  609. }
  610. $node = new simple_html_dom_node($this);
  611. $node->_[HDOM_INFO_BEGIN] = $this->cursor;
  612. ++$this->cursor;
  613. $tag = $this->copy_until($this->token_slash);
  614. // doctype, cdata & comments...
  615. if (isset($tag[0]) && $tag[0]==='!') {
  616. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
  617. if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
  618. $node->nodetype = HDOM_TYPE_COMMENT;
  619. $node->tag = 'comment';
  620. } else {
  621. $node->nodetype = HDOM_TYPE_UNKNOWN;
  622. $node->tag = 'unknown';
  623. }
  624. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  625. $this->link_nodes($node, true);
  626. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  627. return true;
  628. }
  629. // text
  630. if ($pos=strpos($tag, '<')!==false) {
  631. $tag = '<' . substr($tag, 0, -1);
  632. $node->_[HDOM_INFO_TEXT] = $tag;
  633. $this->link_nodes($node, false);
  634. $this->char = $this->doc[--$this->pos]; // prev
  635. return true;
  636. }
  637. if (!preg_match("/^[\w-:]+$/", $tag)) {
  638. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
  639. if ($this->char==='<') {
  640. $this->link_nodes($node, false);
  641. return true;
  642. }
  643. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  644. $this->link_nodes($node, false);
  645. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  646. return true;
  647. }
  648. // begin tag
  649. $node->nodetype = HDOM_TYPE_ELEMENT;
  650. $tag_lower = strtolower($tag);
  651. $node->tag = ($this->lowercase) ? $tag_lower : $tag;
  652. // handle optional closing tags
  653. if (isset($this->optional_closing_tags[$tag_lower]) ) {
  654. while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)])) {
  655. $this->parent->_[HDOM_INFO_END] = 0;
  656. $this->parent = $this->parent->parent;
  657. }
  658. $node->parent = $this->parent;
  659. }
  660. $guard = 0; // prevent infinity loop
  661. $space = array($this->copy_skip($this->token_blank), '', '');
  662. // attributes
  663. do {
  664. if ($this->char!==null && $space[0]==='') break;
  665. $name = $this->copy_until($this->token_equal);
  666. if($guard===$this->pos) {
  667. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  668. continue;
  669. }
  670. $guard = $this->pos;
  671. // handle endless '<'
  672. if($this->pos>=$this->size-1 && $this->char!=='>') {
  673. $node->nodetype = HDOM_TYPE_TEXT;
  674. $node->_[HDOM_INFO_END] = 0;
  675. $node->_[HDOM_INFO_TEXT] = '<'.$tag . $space[0] . $name;
  676. $node->tag = 'text';
  677. $this->link_nodes($node, false);
  678. return true;
  679. }
  680. // handle mismatch '<'
  681. if($this->doc[$this->pos-1]=='<') {
  682. $node->nodetype = HDOM_TYPE_TEXT;
  683. $node->tag = 'text';
  684. $node->attr = array();
  685. $node->_[HDOM_INFO_END] = 0;
  686. $node->_[HDOM_INFO_TEXT] = substr($this->doc, $begin_tag_pos, $this->pos-$begin_tag_pos-1);
  687. $this->pos -= 2;
  688. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  689. $this->link_nodes($node, false);
  690. return true;
  691. }
  692. if ($name!=='/' && $name!=='') {
  693. $space[1] = $this->copy_skip($this->token_blank);
  694. $name = $this->restore_noise($name);
  695. if ($this->lowercase) $name = strtolower($name);
  696. if ($this->char==='=') {
  697. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  698. $this->parse_attr($node, $name, $space);
  699. }
  700. else {
  701. //no value attr: nowrap, checked selected...
  702. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
  703. $node->attr[$name] = true;
  704. if ($this->char!='>') $this->char = $this->doc[--$this->pos]; // prev
  705. }
  706. $node->_[HDOM_INFO_SPACE][] = $space;
  707. $space = array($this->copy_skip($this->token_blank), '', '');
  708. }
  709. else
  710. break;
  711. } while($this->char!=='>' && $this->char!=='/');
  712. $this->link_nodes($node, true);
  713. $node->_[HDOM_INFO_ENDSPACE] = $space[0];
  714. // check self closing
  715. if ($this->copy_until_char_escape('>')==='/') {
  716. $node->_[HDOM_INFO_ENDSPACE] .= '/';
  717. $node->_[HDOM_INFO_END] = 0;
  718. }
  719. else {
  720. // reset parent
  721. if (!isset($this->self_closing_tags[strtolower($node->tag)])) $this->parent = $node;
  722. }
  723. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  724. return true;
  725. }
  726. // parse attributes
  727. protected function parse_attr($node, $name, &$space) {
  728. $space[2] = $this->copy_skip($this->token_blank);
  729. switch($this->char) {
  730. case '"':
  731. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
  732. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  733. $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('"'));
  734. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  735. break;
  736. case '\'':
  737. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_SINGLE;
  738. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  739. $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('\''));
  740. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  741. break;
  742. default:
  743. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
  744. $node->attr[$name] = $this->restore_noise($this->copy_until($this->token_attr));
  745. }
  746. }
  747. // link node's parent
  748. protected function link_nodes(&$node, $is_child) {
  749. $node->parent = $this->parent;
  750. $this->parent->nodes[] = $node;
  751. if ($is_child)
  752. $this->parent->children[] = $node;
  753. }
  754. // as a text node
  755. protected function as_text_node($tag) {
  756. $node = new simple_html_dom_node($this);
  757. ++$this->cursor;
  758. $node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
  759. $this->link_nodes($node, false);
  760. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  761. return true;
  762. }
  763. protected function skip($chars) {
  764. $this->pos += strspn($this->doc, $chars, $this->pos);
  765. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  766. }
  767. protected function copy_skip($chars) {
  768. $pos = $this->pos;
  769. $len = strspn($this->doc, $chars, $pos);
  770. $this->pos += $len;
  771. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  772. if ($len===0) return '';
  773. return substr($this->doc, $pos, $len);
  774. }
  775. protected function copy_until($chars) {
  776. $pos = $this->pos;
  777. $len = strcspn($this->doc, $chars, $pos);
  778. $this->pos += $len;
  779. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  780. return substr($this->doc, $pos, $len);
  781. }
  782. protected function copy_until_char($char) {
  783. if ($this->char===null) return '';
  784. if (($pos = strpos($this->doc, $char, $this->pos))===false) {
  785. $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
  786. $this->char = null;
  787. $this->pos = $this->size;
  788. return $ret;
  789. }
  790. if ($pos===$this->pos) return '';
  791. $pos_old = $this->pos;
  792. $this->char = $this->doc[$pos];
  793. $this->pos = $pos;
  794. return substr($this->doc, $pos_old, $pos-$pos_old);
  795. }
  796. protected function copy_until_char_escape($char) {
  797. if ($this->char===null) return '';
  798. $start = $this->pos;
  799. while(1) {
  800. if (($pos = strpos($this->doc, $char, $start))===false) {
  801. $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
  802. $this->char = null;
  803. $this->pos = $this->size;
  804. return $ret;
  805. }
  806. if ($pos===$this->pos) return '';
  807. if ($this->doc[$pos-1]==='\\') {
  808. $start = $pos+1;
  809. continue;
  810. }
  811. $pos_old = $this->pos;
  812. $this->char = $this->doc[$pos];
  813. $this->pos = $pos;
  814. return substr($this->doc, $pos_old, $pos-$pos_old);
  815. }
  816. }
  817. // remove noise from html content
  818. protected function remove_noise($pattern, $remove_tag=false) {
  819. $count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
  820. //
  821. for ($i=$count-1; $i>-1; --$i) {
  822. $key = '___noise___'.sprintf('% 3d', count($this->noise)+100);
  823. $idx = ($remove_tag) ? 0 : 1;
  824. $this->noise[$key] = $matches[$i][$idx][0];
  825. $this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
  826. }
  827. // reset the length of content
  828. $this->size = strlen($this->doc);
  829. if ($this->size>0) $this->char = $this->doc[0];
  830. }
  831. // restore noise to html content
  832. function restore_noise($text) {
  833. //
  834. while(($pos=strpos($text, '___noise___'))!==false) {
  835. $key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13];
  836. if (isset($this->noise[$key]))
  837. $text = substr($text, 0, $pos).$this->noise[$key].substr($text, $pos+14);
  838. }
  839. return $text;
  840. }
  841. function __toString() {
  842. return $this->root->innertext();
  843. }
  844. function __get($name) {
  845. switch($name) {
  846. case 'outertext': return $this->root->innertext();
  847. case 'innertext': return $this->root->innertext();
  848. case 'plaintext': return $this->root->text();
  849. }
  850. }
  851. // camel naming conventions
  852. function childNodes($idx=-1) {return $this->root->childNodes($idx);}
  853. function firstChild() {return $this->root->first_child();}
  854. function lastChild() {return $this->root->last_child();}
  855. function getElementById($id) {return $this->find("#$id", 0);}
  856. function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
  857. function getElementByTagName($name) {return $this->find($name, 0);}
  858. function getElementsByTagName($name, $idx=-1) {return $this->find($name, $idx);}
  859. function loadFile() {$args = func_get_args();$this->load(call_user_func_array('file_get_contents', $args), true);}
  860. }
  861. }
  862. ?>