<?php
/**
* Website: http://sourceforge.net/projects/simplehtmldom/
* Additional projects that may be used: http://sourceforge.net/projects/debugobject/
* Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
* Contributions by:
* Yousuke Kumakura (Attribute filters)
* Vadim Voituk (Negative indexes supports of “find” method)
* Antcs (Constructor with automatically load contents either text or file/url)
*
* all affected sections have comments starting with “PaperG”
*
* Paperg – Added case insensitive testing of the value of the selector.
* Paperg – Added tag_start for the starting index of tags – NOTE: This works but not accurately.
* 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,
* it will almost always be smaller by some amount.
* 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.
* but for most purposes, it’s a really good estimation.
* Paperg – Added the forceTagsClosed to the dom constructor. Forcing tags closed is great for malformed html, but it CAN lead to parsing errors.
* Allow the user to tell us how much they trust the html.
* 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.
* This allows for us to find tags based on the text they contain.
* Create find_ancestor_tag to see if a tag is – at any level – inside of another specific tag.
* Paperg: added parse_charset so that we know about the character set of the source document.
* 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
* last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection.
*
* Found infinite loop in the case of broken html in restore_noise. Rewrote to protect from that.
* PaperG (John Schlick) Added get_display_size for “IMG” tags.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author S.C. Chen <me578022@gmail.com>
* @author John Schlick
* @author Rus Carroll
* @version 1.5 ($Rev: 208 $)
* @package PlaceLocalInclude
* @subpackage simple_html_dom
*/

// returns the parent of node
// If a node is passed in, it will reset the parent of the current node to that one.
function parent($parent=null)
{
// I am SURE that this doesn’t work properly.
// It fails to unset the current node from it’s current parents nodes or children list first.
if ($parent !== null)
{
$this->parent = $parent;
$this->parent->nodes[] = $this;
$this->parent->children[] = $this;
}

$ret = ”;
// 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.
// NOTE: This indicates that there is a problem where it’s set to NULL without a clear happening.
// WHY is this happening?
if (!is_null($this->nodes))
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->text());
}

// 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.
if ($this->tag == “span”)
{
$ret .= $this->dom->default_span_text;
}
}
return $ret;
}

// find each selector
for ($c=0; $c<$count; ++$c)
{
// The change on the below line was documented on the sourceforge code tracker id 2788009
// used to be: if (($levle=count($selectors[0]))===0) return array();
if (($levle=count($selectors[$c]))===0) return array();
if (!isset($this->_[HDOM_INFO_BEGIN])) return array();

// pattern of CSS selectors, modified from mootools
// Paperg: Add the colon to the attrbute, so that it properly finds <tag attr:ibute=”something” > like google does.
// Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check.
// Notice the \[ starting the attbute? and the @? following? This implies that an attribute can begin with an @ sign that is not captured.
// This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression.
// farther study is required to determine of this should be documented or removed.
// $pattern = “/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\”‘]?(.*?)[\”‘]?)?\])?([\/, ]+)/is”;
$pattern = “/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\”‘]?(.*?)[\”‘]?)?\])?([\/, ]+)/is”;
preg_match_all($pattern, trim($selector_string).’ ‘, $matches, PREG_SET_ORDER);
if (is_object($debug_object)) {$debug_object->debug_log(2, “Matches Array: “, $matches);}

// convert to lowercase
if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);}
//elements that do NOT have the specified attribute
if (isset($key[0]) && $key[0]===’!’) {$key=substr($key, 1); $no_key=true;}

// PaperG – Function to convert the text from one character set to another if the two sets are not the same.
function convert_text($text)
{
global $debug_object;
if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}

/**
* Function to try a few tricks to determine the displayed size of an img on the page.
* NOTE: This will ONLY work on an IMG tag. Returns FALSE on all other tag types.
*
* @author John Schlick
* @version April 19 2012
* @return array an array containing the ‘height’ and ‘width’ of the image on the page or -1 if we can’t figure it out.
*/
function get_display_size()
{
global $debug_object;

$width = -1;
$height = -1;

if ($this->tag !== ‘img’)
{
return false;
}

// See if there is aheight or width attribute in the tag itself.
if (isset($this->attr[‘width’]))
{
$width = $this->attr[‘width’];
}

// If there is a width in the style attributes:
if (isset($attributes[‘width’]) && $width == -1)
{
// check that the last two characters are px (pixels)
if (strtolower(substr($attributes[‘width’], -2)) == ‘px’)
{
$proposed_width = substr($attributes[‘width’], 0, -2);
// Now make sure that it’s an integer and not something stupid.
if (filter_var($proposed_width, FILTER_VALIDATE_INT))
{
$width = $proposed_width;
}
}
}

// If there is a width in the style attributes:
if (isset($attributes[‘height’]) && $height == -1)
{
// check that the last two characters are px (pixels)
if (strtolower(substr($attributes[‘height’], -2)) == ‘px’)
{
$proposed_height = substr($attributes[‘height’], 0, -2);
// Now make sure that it’s an integer and not something stupid.
if (filter_var($proposed_height, FILTER_VALIDATE_INT))
{
$height = $proposed_height;
}
}
}

}

// Future enhancement:
// Look in the tag to see if there is a class or id specified that has a height or width attribute to it.

// Far future enhancement
// 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
// Note that in this case, the class or id will have the img subselector for it to apply to the image.

// ridiculously far future development
// 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.

/**
* simple html dom parser
* Paperg – in the find routine: allow us to specify that we want case insensitive testing of the value of the selector.
* Paperg – change $size from protected to public so we can easily access it
* Paperg – added ForceTagsClosed in the constructor which tells us whether we trust the html or not. Default is to NOT trust it.
*
* @package PlaceLocalInclude
*/
class simple_html_dom
{
public $root = null;
public $nodes = array();
public $callback = null;
public $lowercase = false;
// Used to keep track of how large the text was when we started.
public $original_size;
public $size;
protected $pos;
protected $doc;
protected $char;
protected $cursor;
protected $parent;
protected $noise = array();
protected $token_blank = ” \t\r\n”;
protected $token_equal = ‘ =/>’;
protected $token_slash = ” />\r\n\t”;
protected $token_attr = ‘ >’;
// Note that this is referenced by a child node, and so it needs to be public for that node to see this information.
public $_charset = ”;
public $_target_charset = ”;
protected $default_br_text = “”;
public $default_span_text = “”;

// clean up memory due to php5 circular references memory leak…
function clear()
{
foreach ($this->nodes as $n) {$n->clear(); $n = null;}
// 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.
if (isset($this->children)) foreach ($this->children as $n) {$n->clear(); $n = null;}
if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
if (isset($this->root)) {$this->root->clear(); unset($this->root);}
unset($this->doc);
unset($this->noise);
}

// set the length of content before we do anything to it.
$this->size = strlen($str);
// Save the original size of the html that we got in. It might be useful to someone.
$this->original_size = $this->size;

//before we save the string as the doc… strip out the \r \n’s if we are told to.
if ($stripRN) {
$str = str_replace(“\r”, ” “, $str);
$str = str_replace(“\n”, ” “, $str);

// set the length of content since we have changed it.
$this->size = strlen($str);
}

// 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.
// 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
// (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.
protected function parse_charset()
{
global $debug_object;

// If we couldn’t find a charset above, then lets try to detect one based on the text we got…
if (empty($charset))
{
// Use this in case mb_detect_charset isn’t installed/loaded on this machine.
$charset = false;
if (function_exists(‘mb_detect_encoding’))
{
// Have php try to detect the encoding from the text given to us.
$charset = mb_detect_encoding($this->root->plaintext . “ascii”, $encoding_list = array( “UTF-8”, “CP1252” ) );
if (is_object($debug_object)) {$debug_object->debug_log(2, ‘mb_detect found: ‘ . $charset);}
}

// 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…
if ($charset === false)
{
if (is_object($debug_object)) {$debug_object->debug_log(2, ‘since mb_detect failed – using default of utf-8’);}
$charset = ‘UTF-8’;
}
}

// Since CP1252 is a superset, if we get one of it’s subsets, we want it instead.
if ((strtolower($charset) == strtolower(‘ISO-8859-1’)) || (strtolower($charset) == strtolower(‘Latin1’)) || (strtolower($charset) == strtolower(‘Latin-1’)))
{
if (is_object($debug_object)) {$debug_object->debug_log(2, ‘replacing ‘ . $charset . ‘ with CP1252 as its a superset’);}
$charset = ‘CP1252’;
}

// If it’s a BR tag, we need to set it’s text to the default text.
// This way when we see it in plaintext, we can generate formatting that the user wants.
// since a br tag never has sub nodes, this works well.
if ($node->tag == “br”)
{
$node->_[HDOM_INFO_INNER] = $this->default_br_text;
}