Guest User

Untitled

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