dom.php 59 KB

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