PageRenderTime 75ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/components/com_footballclub/models/simple_html_dom.php

https://bitbucket.org/pastor399/newcastleunifc
PHP | 1365 lines | 988 code | 152 blank | 225 comment | 244 complexity | c657cd8025469309204410e2c0ee6759 MD5 | raw file
  1. <?php
  2. /**
  3. * Website: http://sourceforge.net/projects/simplehtmldom/
  4. * Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
  5. * Contributions by:
  6. * Yousuke Kumakura (Attribute filters)
  7. * Vadim Voituk (Negative indexes supports of "find" method)
  8. * Antcs (Constructor with automatically load contents either text or file/url)
  9. *
  10. * all affected sections have comments starting with "PaperG"
  11. *
  12. * Paperg - Added case insensitive testing of the value of the selector.
  13. * Paperg - Added tag_start for the starting index of tags - NOTE: This works but not accurately.
  14. * This tag_start gets counted AFTER \r\n have been crushed out, and after the remove_noice calls so it will not reflect the REAL position of the tag in the source,
  15. * it will almost always be smaller by some amount.
  16. * We use this to determine how far into the file the tag in question is. This "percentage will never be accurate as the $dom->size is the "real" number of bytes the dom was created from.
  17. * but for most purposes, it's a really good estimation.
  18. * Paperg - Added the forceTagsClosed to the dom constructor. Forcing tags closed is great for malformed html, but it CAN lead to parsing errors.
  19. * Allow the user to tell us how much they trust the html.
  20. * Paperg add the text and plaintext to the selectors for the find syntax. plaintext implies text in the innertext of a node. text implies that the tag is a text node.
  21. * This allows for us to find tags based on the text they contain.
  22. * Create find_ancestor_tag to see if a tag is - at any level - inside of another specific tag.
  23. * Paperg: added parse_charset so that we know about the character set of the source document.
  24. * NOTE: If the user's system has a routine called get_last_retrieve_url_contents_content_type availalbe, we will assume it's returning the content-type header from the
  25. * last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection.
  26. *
  27. * Found infinite loop in the case of broken html in restore_noise. Rewrote to protect from that.
  28. * PaperG (John Schlick) Added get_display_size for "IMG" tags.
  29. *
  30. * Licensed under The MIT License
  31. * Redistributions of files must retain the above copyright notice.
  32. *
  33. * @author S.C. Chen <me578022@gmail.com>
  34. * @author John Schlick
  35. * @author Rus Carroll
  36. * @version 1.5 ($Rev: 196 $)
  37. * @package PlaceLocalInclude
  38. * @subpackage simple_html_dom
  39. */
  40. /**
  41. * All of the Defines for the classes below.
  42. * @author S.C. Chen <me578022@gmail.com>
  43. */
  44. define('HDOM_TYPE_ELEMENT', 1);
  45. define('HDOM_TYPE_COMMENT', 2);
  46. define('HDOM_TYPE_TEXT', 3);
  47. define('HDOM_TYPE_ENDTAG', 4);
  48. define('HDOM_TYPE_ROOT', 5);
  49. define('HDOM_TYPE_UNKNOWN', 6);
  50. define('HDOM_QUOTE_DOUBLE', 0);
  51. define('HDOM_QUOTE_SINGLE', 1);
  52. define('HDOM_QUOTE_NO', 3);
  53. define('HDOM_INFO_BEGIN', 0);
  54. define('HDOM_INFO_END', 1);
  55. define('HDOM_INFO_QUOTE', 2);
  56. define('HDOM_INFO_SPACE', 3);
  57. define('HDOM_INFO_TEXT', 4);
  58. define('HDOM_INFO_INNER', 5);
  59. define('HDOM_INFO_OUTER', 6);
  60. define('HDOM_INFO_ENDSPACE',7);
  61. define('DEFAULT_TARGET_CHARSET', 'UTF-8');
  62. define('DEFAULT_BR_TEXT', "\r\n");
  63. define('DEFAULT_SPAN_TEXT', " ");
  64. define('MAX_FILE_SIZE', 600000);
  65. // helper functions
  66. // -----------------------------------------------------------------------------
  67. // get html dom from file
  68. // $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1.
  69. function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
  70. {
  71. // We DO force the tags to be terminated.
  72. $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
  73. // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
  74. $contents = file_get_contents($url, $use_include_path, $context, $offset);
  75. // Paperg - use our own mechanism for getting the contents as we want to control the timeout.
  76. //$contents = retrieve_url_contents($url);
  77. if (empty($contents) || strlen($contents) > MAX_FILE_SIZE)
  78. {
  79. return false;
  80. }
  81. // The second parameter can force the selectors to all be lowercase.
  82. $dom->load($contents, $lowercase, $stripRN);
  83. return $dom;
  84. }
  85. // get html dom from string
  86. function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
  87. {
  88. $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
  89. if (empty($str) || strlen($str) > MAX_FILE_SIZE)
  90. {
  91. $dom->clear();
  92. return false;
  93. }
  94. $dom->load($str, $lowercase, $stripRN);
  95. return $dom;
  96. }
  97. // dump html dom tree
  98. function dump_html_tree($node, $show_attr=true, $deep=0)
  99. {
  100. $node->dump($node);
  101. }
  102. /**
  103. * simple html dom node
  104. * PaperG - added ability for "find" routine to lowercase the value of the selector.
  105. * PaperG - added $tag_start to track the start position of the tag in the total byte index
  106. *
  107. * @package PlaceLocalInclude
  108. */
  109. class simple_html_dom_node
  110. {
  111. public $nodetype = HDOM_TYPE_TEXT;
  112. public $tag = 'text';
  113. public $attr = array();
  114. public $children = array();
  115. public $nodes = array();
  116. public $parent = null;
  117. // The "info" array - see HDOM_INFO_... for what each element contains.
  118. public $_ = array();
  119. public $tag_start = 0;
  120. private $dom = null;
  121. function __construct($dom)
  122. {
  123. $this->dom = $dom;
  124. $dom->nodes[] = $this;
  125. }
  126. function __destruct()
  127. {
  128. $this->clear();
  129. }
  130. function __toString()
  131. {
  132. return $this->outertext();
  133. }
  134. // clean up memory due to php5 circular references memory leak...
  135. function clear()
  136. {
  137. $this->dom = null;
  138. $this->nodes = null;
  139. $this->parent = null;
  140. $this->children = null;
  141. }
  142. // dump node's tree
  143. function dump($show_attr=true, $deep=0)
  144. {
  145. $lead = str_repeat(' ', $deep);
  146. echo $lead.$this->tag;
  147. if ($show_attr && count($this->attr)>0)
  148. {
  149. echo '(';
  150. foreach ($this->attr as $k=>$v)
  151. echo "[$k]=>\"".$this->$k.'", ';
  152. echo ')';
  153. }
  154. echo "\n";
  155. if ($this->nodes)
  156. {
  157. foreach ($this->nodes as $c)
  158. {
  159. $c->dump($show_attr, $deep+1);
  160. }
  161. }
  162. }
  163. // Debugging function to dump a single dom node with a bunch of information about it.
  164. function dump_node($echo=true)
  165. {
  166. $string = $this->tag;
  167. if (count($this->attr)>0)
  168. {
  169. $string .= '(';
  170. foreach ($this->attr as $k=>$v)
  171. {
  172. $string .= "[$k]=>\"".$this->$k.'", ';
  173. }
  174. $string .= ')';
  175. }
  176. if (count($this->_)>0)
  177. {
  178. $string .= ' $_ (';
  179. foreach ($this->_ as $k=>$v)
  180. {
  181. if (is_array($v))
  182. {
  183. $string .= "[$k]=>(";
  184. foreach ($v as $k2=>$v2)
  185. {
  186. $string .= "[$k2]=>\"".$v2.'", ';
  187. }
  188. $string .= ")";
  189. } else {
  190. $string .= "[$k]=>\"".$v.'", ';
  191. }
  192. }
  193. $string .= ")";
  194. }
  195. if (isset($this->text))
  196. {
  197. $string .= " text: (" . $this->text . ")";
  198. }
  199. $string .= " HDOM_INNER_INFO: '";
  200. if (isset($node->_[HDOM_INFO_INNER]))
  201. {
  202. $string .= $node->_[HDOM_INFO_INNER] . "'";
  203. }
  204. else
  205. {
  206. $string .= ' NULL ';
  207. }
  208. $string .= " children: " . count($this->children);
  209. $string .= " nodes: " . count($this->nodes);
  210. $string .= " tag_start: " . $this->tag_start;
  211. $string .= "\n";
  212. if ($echo)
  213. {
  214. echo $string;
  215. return;
  216. }
  217. else
  218. {
  219. return $string;
  220. }
  221. }
  222. // returns the parent of node
  223. // If a node is passed in, it will reset the parent of the current node to that one.
  224. function parent($parent=null)
  225. {
  226. // I am SURE that this doesn't work properly.
  227. // It fails to unset the current node from it's current parents nodes or children list first.
  228. if ($parent !== null)
  229. {
  230. $this->parent = $parent;
  231. $this->parent->nodes[] = $this;
  232. $this->parent->children[] = $this;
  233. }
  234. return $this->parent;
  235. }
  236. // verify that node has children
  237. function has_child()
  238. {
  239. return !empty($this->children);
  240. }
  241. // returns children of node
  242. function children($idx=-1)
  243. {
  244. if ($idx===-1)
  245. {
  246. return $this->children;
  247. }
  248. if (isset($this->children[$idx])) return $this->children[$idx];
  249. return null;
  250. }
  251. // returns the first child of node
  252. function first_child()
  253. {
  254. if (count($this->children)>0)
  255. {
  256. return $this->children[0];
  257. }
  258. return null;
  259. }
  260. // returns the last child of node
  261. function last_child()
  262. {
  263. if (($count=count($this->children))>0)
  264. {
  265. return $this->children[$count-1];
  266. }
  267. return null;
  268. }
  269. // returns the next sibling of node
  270. function next_sibling()
  271. {
  272. if ($this->parent===null)
  273. {
  274. return null;
  275. }
  276. $idx = 0;
  277. $count = count($this->parent->children);
  278. while ($idx<$count && $this!==$this->parent->children[$idx])
  279. {
  280. ++$idx;
  281. }
  282. if (++$idx>=$count)
  283. {
  284. return null;
  285. }
  286. return $this->parent->children[$idx];
  287. }
  288. // returns the previous sibling of node
  289. function prev_sibling()
  290. {
  291. if ($this->parent===null) return null;
  292. $idx = 0;
  293. $count = count($this->parent->children);
  294. while ($idx<$count && $this!==$this->parent->children[$idx])
  295. ++$idx;
  296. if (--$idx<0) return null;
  297. return $this->parent->children[$idx];
  298. }
  299. // function to locate a specific ancestor tag in the path to the root.
  300. function find_ancestor_tag($tag)
  301. {
  302. global $debugObject;
  303. if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
  304. // Start by including ourselves in the comparison.
  305. $returnDom = $this;
  306. while (!is_null($returnDom))
  307. {
  308. if (is_object($debugObject)) { $debugObject->debugLog(2, "Current tag is: " . $returnDom->tag); }
  309. if ($returnDom->tag == $tag)
  310. {
  311. break;
  312. }
  313. $returnDom = $returnDom->parent;
  314. }
  315. return $returnDom;
  316. }
  317. // get dom node's inner html
  318. function innertext()
  319. {
  320. if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
  321. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  322. $ret = '';
  323. foreach ($this->nodes as $n)
  324. $ret .= $n->outertext();
  325. return $ret;
  326. }
  327. // get dom node's outer text (with tag)
  328. function outertext()
  329. {
  330. global $debugObject;
  331. if (is_object($debugObject))
  332. {
  333. $text = '';
  334. if ($this->tag == 'text')
  335. {
  336. if (!empty($this->text))
  337. {
  338. $text = " with text: " . $this->text;
  339. }
  340. }
  341. $debugObject->debugLog(1, 'Innertext of tag: ' . $this->tag . $text);
  342. }
  343. if ($this->tag==='root') return $this->innertext();
  344. // trigger callback
  345. if ($this->dom && $this->dom->callback!==null)
  346. {
  347. call_user_func_array($this->dom->callback, array($this));
  348. }
  349. if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
  350. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  351. // render begin tag
  352. if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
  353. {
  354. $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
  355. } else {
  356. $ret = "";
  357. }
  358. // render inner text
  359. if (isset($this->_[HDOM_INFO_INNER]))
  360. {
  361. // If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added.
  362. if ($this->tag != "br")
  363. {
  364. $ret .= $this->_[HDOM_INFO_INNER];
  365. }
  366. } else {
  367. if ($this->nodes)
  368. {
  369. foreach ($this->nodes as $n)
  370. {
  371. $ret .= $this->convert_text($n->outertext());
  372. }
  373. }
  374. }
  375. // render end tag
  376. if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
  377. $ret .= '</'.$this->tag.'>';
  378. return $ret;
  379. }
  380. // get dom node's plain text
  381. function text()
  382. {
  383. if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
  384. switch ($this->nodetype)
  385. {
  386. case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  387. case HDOM_TYPE_COMMENT: return '';
  388. case HDOM_TYPE_UNKNOWN: return '';
  389. }
  390. if (strcasecmp($this->tag, 'script')===0) return '';
  391. if (strcasecmp($this->tag, 'style')===0) return '';
  392. $ret = '';
  393. // In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL.
  394. // NOTE: This indicates that there is a problem where it's set to NULL without a clear happening.
  395. // WHY is this happening?
  396. if (!is_null($this->nodes))
  397. {
  398. foreach ($this->nodes as $n)
  399. {
  400. $ret .= $this->convert_text($n->text());
  401. }
  402. // If this node is a span... add a space at the end of it so multiple spans don't run into each other. This is plaintext after all.
  403. if ($this->tag == "span")
  404. {
  405. $ret .= $this->dom->default_span_text;
  406. }
  407. }
  408. return $ret;
  409. }
  410. function xmltext()
  411. {
  412. $ret = $this->innertext();
  413. $ret = str_ireplace('<![CDATA[', '', $ret);
  414. $ret = str_replace(']]>', '', $ret);
  415. return $ret;
  416. }
  417. // build node's text with tag
  418. function makeup()
  419. {
  420. // text, comment, unknown
  421. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  422. $ret = '<'.$this->tag;
  423. $i = -1;
  424. foreach ($this->attr as $key=>$val)
  425. {
  426. ++$i;
  427. // skip removed attribute
  428. if ($val===null || $val===false)
  429. continue;
  430. $ret .= $this->_[HDOM_INFO_SPACE][$i][0];
  431. //no value attr: nowrap, checked selected...
  432. if ($val===true)
  433. $ret .= $key;
  434. else {
  435. switch ($this->_[HDOM_INFO_QUOTE][$i])
  436. {
  437. case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
  438. case HDOM_QUOTE_SINGLE: $quote = '\''; break;
  439. default: $quote = '';
  440. }
  441. $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
  442. }
  443. }
  444. $ret = $this->dom->restore_noise($ret);
  445. return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
  446. }
  447. // find elements by css selector
  448. //PaperG - added ability for find to lowercase the value of the selector.
  449. function find($selector, $idx=null, $lowercase=false)
  450. {
  451. $selectors = $this->parse_selector($selector);
  452. if (($count=count($selectors))===0) return array();
  453. $found_keys = array();
  454. // find each selector
  455. for ($c=0; $c<$count; ++$c)
  456. {
  457. // The change on the below line was documented on the sourceforge code tracker id 2788009
  458. // used to be: if (($levle=count($selectors[0]))===0) return array();
  459. if (($levle=count($selectors[$c]))===0) return array();
  460. if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
  461. $head = array($this->_[HDOM_INFO_BEGIN]=>1);
  462. // handle descendant selectors, no recursive!
  463. for ($l=0; $l<$levle; ++$l)
  464. {
  465. $ret = array();
  466. foreach ($head as $k=>$v)
  467. {
  468. $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
  469. //PaperG - Pass this optional parameter on to the seek function.
  470. $n->seek($selectors[$c][$l], $ret, $lowercase);
  471. }
  472. $head = $ret;
  473. }
  474. foreach ($head as $k=>$v)
  475. {
  476. if (!isset($found_keys[$k]))
  477. $found_keys[$k] = 1;
  478. }
  479. }
  480. // sort keys
  481. ksort($found_keys);
  482. $found = array();
  483. foreach ($found_keys as $k=>$v)
  484. $found[] = $this->dom->nodes[$k];
  485. // return nth-element or array
  486. if (is_null($idx)) return $found;
  487. else if ($idx<0) $idx = count($found) + $idx;
  488. return (isset($found[$idx])) ? $found[$idx] : null;
  489. }
  490. // seek for given conditions
  491. // PaperG - added parameter to allow for case insensitive testing of the value of a selector.
  492. protected function seek($selector, &$ret, $lowercase=false)
  493. {
  494. global $debugObject;
  495. if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
  496. list($tag, $key, $val, $exp, $no_key) = $selector;
  497. // xpath index
  498. if ($tag && $key && is_numeric($key))
  499. {
  500. $count = 0;
  501. foreach ($this->children as $c)
  502. {
  503. if ($tag==='*' || $tag===$c->tag) {
  504. if (++$count==$key) {
  505. $ret[$c->_[HDOM_INFO_BEGIN]] = 1;
  506. return;
  507. }
  508. }
  509. }
  510. return;
  511. }
  512. $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
  513. if ($end==0) {
  514. $parent = $this->parent;
  515. while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
  516. $end -= 1;
  517. $parent = $parent->parent;
  518. }
  519. $end += $parent->_[HDOM_INFO_END];
  520. }
  521. for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
  522. $node = $this->dom->nodes[$i];
  523. $pass = true;
  524. if ($tag==='*' && !$key) {
  525. if (in_array($node, $this->children, true))
  526. $ret[$i] = 1;
  527. continue;
  528. }
  529. // compare tag
  530. if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
  531. // compare key
  532. if ($pass && $key) {
  533. if ($no_key) {
  534. if (isset($node->attr[$key])) $pass=false;
  535. } else {
  536. if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
  537. }
  538. }
  539. // compare value
  540. if ($pass && $key && $val && $val!=='*') {
  541. // If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
  542. if ($key == "plaintext") {
  543. // $node->plaintext actually returns $node->text();
  544. $nodeKeyValue = $node->text();
  545. } else {
  546. // this is a normal search, we want the value of that attribute of the tag.
  547. $nodeKeyValue = $node->attr[$key];
  548. }
  549. if (is_object($debugObject)) {$debugObject->debugLog(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}
  550. //PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
  551. if ($lowercase) {
  552. $check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
  553. } else {
  554. $check = $this->match($exp, $val, $nodeKeyValue);
  555. }
  556. if (is_object($debugObject)) {$debugObject->debugLog(2, "after match: " . ($check ? "true" : "false"));}
  557. // handle multiple class
  558. if (!$check && strcasecmp($key, 'class')===0) {
  559. foreach (explode(' ',$node->attr[$key]) as $k) {
  560. // Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
  561. if (!empty($k)) {
  562. if ($lowercase) {
  563. $check = $this->match($exp, strtolower($val), strtolower($k));
  564. } else {
  565. $check = $this->match($exp, $val, $k);
  566. }
  567. if ($check) break;
  568. }
  569. }
  570. }
  571. if (!$check) $pass = false;
  572. }
  573. if ($pass) $ret[$i] = 1;
  574. unset($node);
  575. }
  576. // It's passed by reference so this is actually what this function returns.
  577. if (is_object($debugObject)) {$debugObject->debugLog(1, "EXIT - ret: ", $ret);}
  578. }
  579. protected function match($exp, $pattern, $value) {
  580. global $debugObject;
  581. if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
  582. switch ($exp) {
  583. case '=':
  584. return ($value===$pattern);
  585. case '!=':
  586. return ($value!==$pattern);
  587. case '^=':
  588. return preg_match("/^".preg_quote($pattern,'/')."/", $value);
  589. case '$=':
  590. return preg_match("/".preg_quote($pattern,'/')."$/", $value);
  591. case '*=':
  592. if ($pattern[0]=='/') {
  593. return preg_match($pattern, $value);
  594. }
  595. return preg_match("/".$pattern."/i", $value);
  596. }
  597. return false;
  598. }
  599. protected function parse_selector($selector_string) {
  600. global $debugObject;
  601. if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
  602. // pattern of CSS selectors, modified from mootools
  603. // Paperg: Add the colon to the attrbute, so that it properly finds <tag attr:ibute="something" > like google does.
  604. // Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check.
  605. // Notice the \[ starting the attbute? and the @? following? This implies that an attribute can begin with an @ sign that is not captured.
  606. // This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression.
  607. // farther study is required to determine of this should be documented or removed.
  608. // $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
  609. $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
  610. preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);
  611. if (is_object($debugObject)) {$debugObject->debugLog(2, "Matches Array: ", $matches);}
  612. $selectors = array();
  613. $result = array();
  614. //print_r($matches);
  615. foreach ($matches as $m) {
  616. $m[0] = trim($m[0]);
  617. if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
  618. // for browser generated xpath
  619. if ($m[1]==='tbody') continue;
  620. list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
  621. if (!empty($m[2])) {$key='id'; $val=$m[2];}
  622. if (!empty($m[3])) {$key='class'; $val=$m[3];}
  623. if (!empty($m[4])) {$key=$m[4];}
  624. if (!empty($m[5])) {$exp=$m[5];}
  625. if (!empty($m[6])) {$val=$m[6];}
  626. // convert to lowercase
  627. if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);}
  628. //elements that do NOT have the specified attribute
  629. if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;}
  630. $result[] = array($tag, $key, $val, $exp, $no_key);
  631. if (trim($m[7])===',') {
  632. $selectors[] = $result;
  633. $result = array();
  634. }
  635. }
  636. if (count($result)>0)
  637. $selectors[] = $result;
  638. return $selectors;
  639. }
  640. function __get($name) {
  641. if (isset($this->attr[$name]))
  642. {
  643. return $this->convert_text($this->attr[$name]);
  644. }
  645. switch ($name) {
  646. case 'outertext': return $this->outertext();
  647. case 'innertext': return $this->innertext();
  648. case 'plaintext': return $this->text();
  649. case 'xmltext': return $this->xmltext();
  650. default: return array_key_exists($name, $this->attr);
  651. }
  652. }
  653. function __set($name, $value) {
  654. switch ($name) {
  655. case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
  656. case 'innertext':
  657. if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
  658. return $this->_[HDOM_INFO_INNER] = $value;
  659. }
  660. if (!isset($this->attr[$name])) {
  661. $this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
  662. $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
  663. }
  664. $this->attr[$name] = $value;
  665. }
  666. function __isset($name) {
  667. switch ($name) {
  668. case 'outertext': return true;
  669. case 'innertext': return true;
  670. case 'plaintext': return true;
  671. }
  672. //no value attr: nowrap, checked selected...
  673. return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
  674. }
  675. function __unset($name) {
  676. if (isset($this->attr[$name]))
  677. unset($this->attr[$name]);
  678. }
  679. // PaperG - Function to convert the text from one character set to another if the two sets are not the same.
  680. function convert_text($text)
  681. {
  682. global $debugObject;
  683. if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
  684. $converted_text = $text;
  685. $sourceCharset = "";
  686. $targetCharset = "";
  687. if ($this->dom)
  688. {
  689. $sourceCharset = strtoupper($this->dom->_charset);
  690. $targetCharset = strtoupper($this->dom->_target_charset);
  691. }
  692. if (is_object($debugObject)) {$debugObject->debugLog(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}
  693. if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0))
  694. {
  695. // Check if the reported encoding could have been incorrect and the text is actually already UTF-8
  696. if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text)))
  697. {
  698. $converted_text = $text;
  699. }
  700. else
  701. {
  702. $converted_text = iconv($sourceCharset, $targetCharset, $text);
  703. }
  704. }
  705. // Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output.
  706. if ($targetCharset == 'UTF-8')
  707. {
  708. if (substr($converted_text, 0, 3) == "\xef\xbb\xbf")
  709. {
  710. $converted_text = substr($converted_text, 3);
  711. }
  712. if (substr($converted_text, -3) == "\xef\xbb\xbf")
  713. {
  714. $converted_text = substr($converted_text, 0, -3);
  715. }
  716. }
  717. return $converted_text;
  718. }
  719. /**
  720. * Returns true if $string is valid UTF-8 and false otherwise.
  721. *
  722. * @param mixed $str String to be tested
  723. * @return boolean
  724. */
  725. static function is_utf8($str)
  726. {
  727. $c=0; $b=0;
  728. $bits=0;
  729. $len=strlen($str);
  730. for($i=0; $i<$len; $i++)
  731. {
  732. $c=ord($str[$i]);
  733. if($c > 128)
  734. {
  735. if(($c >= 254)) return false;
  736. elseif($c >= 252) $bits=6;
  737. elseif($c >= 248) $bits=5;
  738. elseif($c >= 240) $bits=4;
  739. elseif($c >= 224) $bits=3;
  740. elseif($c >= 192) $bits=2;
  741. else return false;
  742. if(($i+$bits) > $len) return false;
  743. while($bits > 1)
  744. {
  745. $i++;
  746. $b=ord($str[$i]);
  747. if($b < 128 || $b > 191) return false;
  748. $bits--;
  749. }
  750. }
  751. }
  752. return true;
  753. }
  754. /*
  755. function is_utf8($string)
  756. {
  757. //this is buggy
  758. return (utf8_encode(utf8_decode($string)) == $string);
  759. }
  760. */
  761. /**
  762. * Function to try a few tricks to determine the displayed size of an img on the page.
  763. * NOTE: This will ONLY work on an IMG tag. Returns FALSE on all other tag types.
  764. *
  765. * @author John Schlick
  766. * @version April 19 2012
  767. * @return array an array containing the 'height' and 'width' of the image on the page or -1 if we can't figure it out.
  768. */
  769. function get_display_size()
  770. {
  771. global $debugObject;
  772. $width = -1;
  773. $height = -1;
  774. if ($this->tag !== 'img')
  775. {
  776. return false;
  777. }
  778. // See if there is aheight or width attribute in the tag itself.
  779. if (isset($this->attr['width']))
  780. {
  781. $width = $this->attr['width'];
  782. }
  783. if (isset($this->attr['height']))
  784. {
  785. $height = $this->attr['height'];
  786. }
  787. // Now look for an inline style.
  788. if (isset($this->attr['style']))
  789. {
  790. // Thanks to user gnarf from stackoverflow for this regular expression.
  791. $attributes = array();
  792. preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $this->attr['style'], $matches, PREG_SET_ORDER);
  793. foreach ($matches as $match) {
  794. $attributes[$match[1]] = $match[2];
  795. }
  796. // If there is a width in the style attributes:
  797. if (isset($attributes['width']) && $width == -1)
  798. {
  799. // check that the last two characters are px (pixels)
  800. if (strtolower(substr($attributes['width'], -2)) == 'px')
  801. {
  802. $proposed_width = substr($attributes['width'], 0, -2);
  803. // Now make sure that it's an integer and not something stupid.
  804. if (filter_var($proposed_width, FILTER_VALIDATE_INT))
  805. {
  806. $width = $proposed_width;
  807. }
  808. }
  809. }
  810. // If there is a width in the style attributes:
  811. if (isset($attributes['height']) && $height == -1)
  812. {
  813. // check that the last two characters are px (pixels)
  814. if (strtolower(substr($attributes['height'], -2)) == 'px')
  815. {
  816. $proposed_height = substr($attributes['height'], 0, -2);
  817. // Now make sure that it's an integer and not something stupid.
  818. if (filter_var($proposed_height, FILTER_VALIDATE_INT))
  819. {
  820. $height = $proposed_height;
  821. }
  822. }
  823. }
  824. }
  825. // Future enhancement:
  826. // Look in the tag to see if there is a class or id specified that has a height or width attribute to it.
  827. // Far future enhancement
  828. // Look at all the parent tags of this image to see if they specify a class or id that has an img selector that specifies a height or width
  829. // Note that in this case, the class or id will have the img subselector for it to apply to the image.
  830. // ridiculously far future development
  831. // If the class or id is specified in a SEPARATE css file thats not on the page, go get it and do what we were just doing for the ones on the page.
  832. $result = array('height' => $height,
  833. 'width' => $width);
  834. return $result;
  835. }
  836. // camel naming conventions
  837. function getAllAttributes() {return $this->attr;}
  838. function getAttribute($name) {return $this->__get($name);}
  839. function setAttribute($name, $value) {$this->__set($name, $value);}
  840. function hasAttribute($name) {return $this->__isset($name);}
  841. function removeAttribute($name) {$this->__set($name, null);}
  842. function getElementById($id) {return $this->find("#$id", 0);}
  843. function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
  844. function getElementByTagName($name) {return $this->find($name, 0);}
  845. function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
  846. function parentNode() {return $this->parent();}
  847. function childNodes($idx=-1) {return $this->children($idx);}
  848. function firstChild() {return $this->first_child();}
  849. function lastChild() {return $this->last_child();}
  850. function nextSibling() {return $this->next_sibling();}
  851. function previousSibling() {return $this->prev_sibling();}
  852. function hasChildNodes() {return $this->has_child();}
  853. function nodeName() {return $this->tag;}
  854. function appendChild($node) {$node->parent($this); return $node;}
  855. }
  856. /**
  857. * simple html dom parser
  858. * Paperg - in the find routine: allow us to specify that we want case insensitive testing of the value of the selector.
  859. * Paperg - change $size from protected to public so we can easily access it
  860. * Paperg - added ForceTagsClosed in the constructor which tells us whether we trust the html or not. Default is to NOT trust it.
  861. *
  862. * @package PlaceLocalInclude
  863. */
  864. class simple_html_dom
  865. {
  866. public $root = null;
  867. public $nodes = array();
  868. public $callback = null;
  869. public $lowercase = false;
  870. // Used to keep track of how large the text was when we started.
  871. public $original_size;
  872. public $size;
  873. protected $pos;
  874. protected $doc;
  875. protected $char;
  876. protected $cursor;
  877. protected $parent;
  878. protected $noise = array();
  879. protected $token_blank = " \t\r\n";
  880. protected $token_equal = ' =/>';
  881. protected $token_slash = " />\r\n\t";
  882. protected $token_attr = ' >';
  883. // Note that this is referenced by a child node, and so it needs to be public for that node to see this information.
  884. public $_charset = '';
  885. public $_target_charset = '';
  886. protected $default_br_text = "";
  887. public $default_span_text = "";
  888. // use isset instead of in_array, performance boost about 30%...
  889. protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
  890. protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
  891. // Known sourceforge issue #2977341
  892. // B tags that are not closed cause us to return everything to the end of the document.
  893. protected $optional_closing_tags = array(
  894. 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
  895. 'th'=>array('th'=>1),
  896. 'td'=>array('td'=>1),
  897. 'li'=>array('li'=>1),
  898. 'dt'=>array('dt'=>1, 'dd'=>1),
  899. 'dd'=>array('dd'=>1, 'dt'=>1),
  900. 'dl'=>array('dd'=>1, 'dt'=>1),
  901. 'p'=>array('p'=>1),
  902. 'nobr'=>array('nobr'=>1),
  903. 'b'=>array('b'=>1),
  904. 'option'=>array('option'=>1),
  905. );
  906. function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
  907. {
  908. if ($str)
  909. {
  910. if (preg_match("/^http:\/\//i",$str) || is_file($str))
  911. {
  912. $this->load_file($str);
  913. }
  914. else
  915. {
  916. $this->load($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
  917. }
  918. }
  919. // Forcing tags to be closed implies that we don't trust the html, but it can lead to parsing errors if we SHOULD trust the html.
  920. if (!$forceTagsClosed) {
  921. $this->optional_closing_array=array();
  922. }
  923. $this->_target_charset = $target_charset;
  924. }
  925. function __destruct()
  926. {
  927. $this->clear();
  928. }
  929. // load html from string
  930. function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
  931. {
  932. global $debugObject;
  933. // prepare
  934. $this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
  935. // strip out comments
  936. $this->remove_noise("'<!--(.*?)-->'is");
  937. // strip out cdata
  938. $this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
  939. // Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
  940. // Script tags removal now preceeds style tag removal.
  941. // strip out <script> tags
  942. $this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
  943. $this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
  944. // strip out <style> tags
  945. $this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
  946. $this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
  947. // strip out preformatted tags
  948. $this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
  949. // strip out server side scripts
  950. $this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
  951. // strip smarty scripts
  952. $this->remove_noise("'(\{\w)(.*?)(\})'s", true);
  953. // parsing
  954. while ($this->parse());
  955. // end
  956. $this->root->_[HDOM_INFO_END] = $this->cursor;
  957. $this->parse_charset();
  958. // make load function chainable
  959. return $this;
  960. }
  961. // load html from file
  962. function load_file()
  963. {
  964. $args = func_get_args();
  965. $this->load(call_user_func_array('file_get_contents', $args), true);
  966. // Throw an error if we can't properly load the dom.
  967. if (($error=error_get_last())!==null) {
  968. $this->clear();
  969. return false;
  970. }
  971. }
  972. // set callback function
  973. function set_callback($function_name)
  974. {
  975. $this->callback = $function_name;
  976. }
  977. // remove callback function
  978. function remove_callback()
  979. {
  980. $this->callback = null;
  981. }
  982. // save dom as string
  983. function save($filepath='')
  984. {
  985. $ret = $this->root->innertext();
  986. if ($filepath!=='') file_put_contents($filepath, $ret, LOCK_EX);
  987. return $ret;
  988. }
  989. // find dom node by css selector
  990. // Paperg - allow us to specify that we want case insensitive testing of the value of the selector.
  991. function find($selector, $idx=null, $lowercase=false)
  992. {
  993. return $this->root->find($selector, $idx, $lowercase);
  994. }
  995. // clean up memory due to php5 circular references memory leak...
  996. function clear()
  997. {
  998. foreach ($this->nodes as $n) {$n->clear(); $n = null;}
  999. // 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.
  1000. if (isset($this->children)) foreach ($this->children as $n) {$n->clear(); $n = null;}
  1001. if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
  1002. if (isset($this->root)) {$this->root->clear(); unset($this->root);}
  1003. unset($this->doc);
  1004. unset($this->noise);
  1005. }
  1006. function dump($show_attr=true)
  1007. {
  1008. $this->root->dump($show_attr);
  1009. }
  1010. // prepare HTML data and init everything
  1011. protected function prepare($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
  1012. {
  1013. $this->clear();
  1014. // set the length of content before we do anything to it.
  1015. $this->size = strlen($str);
  1016. // Save the original size of the html that we got in. It might be useful to someone.
  1017. $this->original_size = $this->size;
  1018. //before we save the string as the doc... strip out the \r \n's if we are told to.
  1019. if ($stripRN) {
  1020. $str = str_replace("\r", " ", $str);
  1021. $str = str_replace("\n", " ", $str);
  1022. // set the length of content since we have changed it.
  1023. $this->size = strlen($str);
  1024. }
  1025. $this->doc = $str;
  1026. $this->pos = 0;
  1027. $this->cursor = 1;
  1028. $this->noise = array();
  1029. $this->nodes = array();
  1030. $this->lowercase = $lowercase;
  1031. $this->default_br_text = $defaultBRText;
  1032. $this->default_span_text = $defaultSpanText;
  1033. $this->root = new simple_html_dom_node($this);
  1034. $this->root->tag = 'root';
  1035. $this->root->_[HDOM_INFO_BEGIN] = -1;
  1036. $this->root->nodetype = HDOM_TYPE_ROOT;
  1037. $this->parent = $this->root;
  1038. if ($this->size>0) $this->char = $this->doc[0];
  1039. }
  1040. // parse html content
  1041. protected function parse()
  1042. {
  1043. if (($s = $this->copy_until_char('<'))==='')
  1044. {
  1045. return $this->read_tag();
  1046. }
  1047. // text
  1048. $node = new simple_html_dom_node($this);
  1049. ++$this->cursor;
  1050. $node->_[HDOM_INFO_TEXT] = $s;
  1051. $this->link_nodes($node, false);
  1052. return true;
  1053. }
  1054. // PAPERG - dkchou - added this to try to identify the character set of the page we have just parsed so we know better how to spit it out later.
  1055. // NOTE: IF you provide a routine called get_last_retrieve_url_contents_content_type which returns the CURLINFO_CONTENT_TYPE from the last curl_exec
  1056. // (or the content_type header from the last transfer), we will parse THAT, and if a charset is specified, we will use it over any other mechanism.
  1057. protected function parse_charset()
  1058. {
  1059. global $debugObject;
  1060. $charset = null;
  1061. if (function_exists('get_last_retrieve_url_contents_content_type'))
  1062. {
  1063. $contentTypeHeader = get_last_retrieve_url_contents_content_type();
  1064. $success = preg_match('/charset=(.+)/', $contentTypeHeader, $matches);
  1065. if ($success)
  1066. {
  1067. $charset = $matches[1];
  1068. if (is_object($debugObject)) {$debugObject->debugLog(2, 'header content-type found charset of: ' . $charset);}
  1069. }
  1070. }
  1071. if (empty($charset))
  1072. {
  1073. $el = $this->root->find('meta[http-equiv=Content-Type]',0);
  1074. if (!empty($el))
  1075. {
  1076. $fullvalue = $el->content;
  1077. if (is_object($debugObject)) {$debugObject->debugLog(2, 'meta content-type tag found' . $fullvalue);}
  1078. if (!empty($fullvalue))
  1079. {
  1080. $success = preg_match('/charset=(.+)/', $fullvalue, $matches);
  1081. if ($success)
  1082. {
  1083. $charset = $matches[1];
  1084. }
  1085. else
  1086. {
  1087. // If there is a meta tag, and they don't specify the character set, research says that it's typically ISO-8859-1
  1088. if (is_object($debugObject)) {$debugObject->debugLog(2, 'meta content-type tag couldn\'t be parsed. using iso-8859 default.');}
  1089. $charset = 'ISO-8859-1';
  1090. }
  1091. }
  1092. }
  1093. }
  1094. // If we couldn't find a charset above, then lets try to detect one based on the text we got...
  1095. if (empty($charset))
  1096. {
  1097. // Have php try to detect the encoding from the text given to us.
  1098. $charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array( "UTF-8", "CP1252" ) );
  1099. if (is_object($debugObject)) {$debugObject->debugLog(2, 'mb_detect found: ' . $charset);}
  1100. // and if this doesn't work... then we need to just wrongheadedly assume it's UTF-8 so that we can move on - cause this will usually give us most of what we need...
  1101. if ($charset === false)
  1102. {
  1103. if (is_object($debugObject)) {$debugObject->debugLog(2, 'since mb_detect failed - using default of utf-8');}
  1104. $charset = 'UTF-8';
  1105. }
  1106. }
  1107. // Since CP1252 is a superset, if we get one of it's subsets, we want it instead.
  1108. if ((strtolower($charset) == strtolower('ISO-8859-1')) || (strtolower($charset) == strtolower('Latin1')) || (strtolower($charset) == strtolower('Latin-1')))
  1109. {
  1110. if (is_object($debugObject)) {$debugObject->debugLog(2, 'replacing ' . $charset . ' with CP1252 as its a superset');}
  1111. $charset = 'CP1252';
  1112. }
  1113. if (is_object($debugObject)) {$debugObject->debugLog(1, 'EXIT - ' . $charset);}
  1114. return $this->_charset = $charset;
  1115. }
  1116. // read tag info
  1117. protected function read_tag()
  1118. {
  1119. if ($this->char!=='<')
  1120. {
  1121. $this->root->_[HDOM_INFO_END] = $this->cursor;
  1122. return false;
  1123. }
  1124. $begin_tag_pos = $this->pos;
  1125. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  1126. // end tag
  1127. if ($this->char==='/')
  1128. {
  1129. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  1130. // This represents the change in the simple_html_dom trunk from revision 180 to 181.
  1131. // $this->skip($this->token_blank_t);
  1132. $this->skip($this->token_blank);
  1133. $tag = $this->copy_until_char('>');
  1134. // skip attributes in end tag
  1135. if (($pos = strpos($tag, ' '))!==false)
  1136. $tag = substr($tag, 0, $pos);
  1137. $parent_lower = strtolower($this->parent->tag);
  1138. $tag_lower = strtolower($tag);
  1139. if ($parent_lower!==$tag_lower)
  1140. {
  1141. if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower]))
  1142. {
  1143. $this->parent->_[HDOM_INFO_END] = 0;
  1144. $org_parent = $this->parent;
  1145. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  1146. $this->parent = $this->parent->parent;
  1147. if (strtolower($this->parent->tag)!==$tag_lower) {
  1148. $this->parent = $org_parent; // restore origonal parent
  1149. if ($this->parent->parent) $this->parent = $this->parent->parent;
  1150. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  1151. return $this->as_text_node($tag);
  1152. }
  1153. }
  1154. else if (($this->parent->parent) && isset($this->block_tags[$tag_lower]))
  1155. {
  1156. $this->parent->_[HDOM_INFO_END] = 0;
  1157. $org_parent = $this->parent;
  1158. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  1159. $this->parent = $this->parent->parent;
  1160. if (strtolower($this->parent->tag)!==$tag_lower)
  1161. {
  1162. $this->parent = $org_parent; // restore origonal parent
  1163. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  1164. return $this->as_text_node($tag);
  1165. }
  1166. }
  1167. else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower)
  1168. {
  1169. $this->parent->_[HDOM_INFO_END] = 0;
  1170. $this->parent = $this->parent->parent;
  1171. }
  1172. else
  1173. return $this->as_text_node($tag);
  1174. }
  1175. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  1176. if ($this->parent->parent) $this->parent = $this->parent->parent;
  1177. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  1178. return true;
  1179. }
  1180. $node = new simple_html_dom_node($this);
  1181. $node->_[HDOM_INFO_BEGIN] = $this->cursor;
  1182. ++$this->cursor;
  1183. $tag = $this->copy_until($this->token_slash);
  1184. $node->tag_start = $begin_tag_pos;
  1185. // doctype, cdata & comments...
  1186. if (isset($tag[0]) && $tag[0]==='!') {
  1187. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
  1188. if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
  1189. $node->nodetype = HDOM_TYPE_COMMENT;
  1190. $node->tag = 'comment';
  1191. } else {
  1192. $node->nodetype = HDOM_TYPE_UNKNOWN;
  1193. $node->tag = 'unknown';
  1194. }
  1195. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  1196. $this->link_nodes($node, true);
  1197. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  1198. return true;
  1199. }
  1200. // text
  1201. if ($pos=strpos($tag, '<')!==false) {
  1202. $tag = '<' . substr($tag, 0, -1);
  1203. $node->_[HDOM_INFO_TEXT] = $tag;
  1204. $this->link_nodes($node, false);
  1205. $this->char = $this->doc[--$this->pos]; // prev
  1206. return true;
  1207. }
  1208. if (!preg_match("/^[\w-:]+$/", $tag)) {
  1209. $node->_[HDOM_INFO_TEX