PluginProbe
Taboola / 1.0.12
Taboola v1.0.12
1.0.4 1.0.5 1.0.6 1.0.8 2.0.1 2.0.2 2.1.0 2.1.1 2.2.2 2.2.3 3.0.0 3.0.1 3.0.2 3.1.0 trunk 1.0 1.0.1 1.0.10 1.0.11 1.0.12 1.0.13 1.0.14 1.0.15 1.0.2 1.0.3
taboola / simple_html_dom.php

simple_html_dom.php in Taboola 1.0.12, at simple_html_dom.php

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