Advertisement
aridho

simplehtml

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