simple_html_dom.php 54 KB

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