lib_simple_html_dom.php 53 KB

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