PageRenderTime 57ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/ml-slider/inc/simple_html_dom.php

https://gitlab.com/gevvvvv/Tumo-Workshop-Cafe
PHP | 1703 lines | 1283 code | 182 blank | 238 comment | 285 complexity | c39f0c6ac88dd19acb545a5a6330165d MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file