/products/photocrati_nextgen/modules/simplehtmldom/simplehtmldom/simple_html_dom.php

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