Shoora
9/18/2019 - 5:50 PM

3qa

3qa

<?
include ("config.php");

$id='500';
$what='12312';
$link='sdv';
$ip="192";


// new data
$title = 'PHP Security';
$author = 'Jack Hijack';

// query
//$sql = "INSERT INTO `shorter`.`short` (little,long) VALUES (:title,:author)";
//$q = $pdo->prepare($sql);
//$q->execute(array(':author'=>$author,  ':title'=>$title));
				  
	try {			  
//$pdos = $pdo->prepare("INSERT INTO `shorter`.`short` (`id`, `little`, `long`,`ip`) VALUES (?,?,?,?)");
//$pdos -> execute(array($id,$what,$link,$ip));
//				$result -> execute(array($id, $what, $link, $ip));

//$stmt = $pdo->query("SELECT `long` FROM `short` WHERE `little` = '404' LIMIT 0 , 30;")->fetch();
//echo $stmt["long"];

//	$last_num = $pdo->query("SELECT `long` FROM `short` WHERE `little` = '404' LIMIT 0 , 30;")->fetch();
//	$last_num = $last_num["long"];
//	echo $last_num;
$last_num = 278;

// $sovpad=mysql_query("SELECT * FROM `short` WHERE `little` =$last_num+1;",$db);
		 // Совпадения?
		 $sovpad  = $pdo->prepare("SELECT `long` FROM `short` WHERE `little` LIKE ?");
		 $sovpad->execute(array($last_num+1));
		 $sovpad = $sovpad->fetch();
		 $sovpad = $sovpad['long'];
		 
		 $i=1;
			while ($sovpads == $last_num+$i) 
				{
					$i=$i+1;
					$sovpad  = $pdo->prepare("SELECT * FROM `short` WHERE `little` LIKE ?");
					$sovpad->execute(array($last_num+$i+1));
					$sovpad = $sovpad->fetch();
					$sovpads = $sovpad['long'];
					echo $sovpad['little'];
				}


//print_r ($data[0]);
echo $sovpad;



//$lastnum=mysql_query("SELECT * FROM `short` WHERE `little` = '404' LIMIT 0 , 30;",$db);
													 // смотрим последнее число
//		 $tablerows = mysql_fetch_row($lastnum);     // построчно

	}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}

// рабоата
//		$last_num = $pdo->query("SELECT `long` FROM `short` WHERE `little` = '404' LIMIT 0 , 30;")->fetch();
//		$last_num = $last_num["long"];



	
	echo "|";
?>


<br><br>

	$sql = "INSERT INTO `shorter`.`short`
				(id, little, long, ip) VALUES (
						:id, :little, :long, :ip)";
				
			$stmt->bindParam(':id', $id, PDO::PARAM_STR);       
	echo "12d2"; exit;	
			$stmt->bindParam(':little', $what, PDO::PARAM_STR); 
			$stmt->bindParam(':long', $link, PDO::PARAM_STR);
			$stmt->bindParam(':ip', $ip, PDO::PARAM_STR); 
			
			$stmt = $pdo->prepare($sql);
			$stmt->execute(); 
			echo "1";
			
			
			
			
			
			
			
			//		include ("safemysql.class.php");
		
		
//		$allowed = array("id","what","link","ip"); // allowed fields
//		$sql = "INSERT INTO `shorter`.`short` SET ".pdoSet($fields,$values);
//		$stm = $dbh->prepare($sql);
//		$stm->execute($values);

		

		//$data    = $stm->filterArray($allowed);
		//$sql     = "INSERT INTO `shorter`.`short` SET ?u";
		//$stm->query($id,$little,$long,$ip);

		//$data = array('id'=>$id,'what'=>$little,'link'=>$long,'ip'=>$ip);		
		//$sql  = "INSERT INTO `shorter`.`short` SET ?u";
		
		//if (!$stm->query($sql, $data)) echo "bad"; exit;
		
		
		$sql = "INSERT INTO `shorter`.`short`
				(id, little, long, ip) VALUES (
						:id, :little, :long, :ip)";
		
			$stmt->bindParam(':id', $id, PDO::PARAM_STR);       
			echo "12d2"; exit;	
			$stmt->bindParam(':little', $what, PDO::PARAM_STR); 
			$stmt->bindParam(':long', $link, PDO::PARAM_STR);
			$stmt->bindParam(':ip', $ip, PDO::PARAM_STR); 
			
			$stmt = $pdo->prepare($sql);
			$stmt->exec(); 
			echo "1";
			

<?
echo"<pre>ss";


$ch = curl_init('http://hm6.ru/poisk-po-bukve/%D8/');

// ��������� �����
curl_setopt($ch, CURLOPT_USERAGENT, 'IE20');
curl_setopt($ch, CURLOPT_HEADER, 0);
// ��������� ����� ���������� ��� ����, ����� ������� curl_exec() ���������� �������� � �� �������� ���������� ���������� �� �����
curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');

// �������� html
$text = curl_exec($ch);


//curl_close($ch);

preg_match_all("#class='b-listing-singers__item__name_m'><a href='\/([A-z0-9.-]+)\/'>([A-z�-�?)#", $text , $links );
print_r ($links[2]);
print_r ($links[1]);




//echo $links[1][0];

?>
<pre>
<?

$ch = curl_init('http://hm6.ru/poisk-po-bukve/%D8/');

// ��������� �����
curl_setopt($ch, CURLOPT_USERAGENT, 'IE20');
curl_setopt($ch, CURLOPT_HEADER, 0);
// ��������� ����� ���������� ��� ����, ����� ������� curl_exec() ���������� �������� � �� �������� ���������� ���������� �� �����
curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');

// �������� html
$text = curl_exec($ch);


//curl_close($ch);

preg_match_all("#class='b-listing-singers__item__name_m'><a href='\/([A-z0-9.-]+)\/'>([^<]+)<\/a#", $text , $links );
 
//iconv("windows-1251","utf-8", $links);
print_r ($links[2]);
print_r ($links[1]);

//echo $links[1][0];

?>
<?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: 210 $)
 * @package PlaceLocalInclude
 * @subpackage simple_html_dom
 */

/**
 * All of the Defines for the classes below.
 * @author S.C. Chen <me578022@gmail.com>
 */
define('HDOM_TYPE_ELEMENT', 1);
define('HDOM_TYPE_COMMENT', 2);
define('HDOM_TYPE_TEXT',	3);
define('HDOM_TYPE_ENDTAG',  4);
define('HDOM_TYPE_ROOT',	5);
define('HDOM_TYPE_UNKNOWN', 6);
define('HDOM_QUOTE_DOUBLE', 0);
define('HDOM_QUOTE_SINGLE', 1);
define('HDOM_QUOTE_NO',	 3);
define('HDOM_INFO_BEGIN',   0);
define('HDOM_INFO_END',	 1);
define('HDOM_INFO_QUOTE',   2);
define('HDOM_INFO_SPACE',   3);
define('HDOM_INFO_TEXT',	4);
define('HDOM_INFO_INNER',   5);
define('HDOM_INFO_OUTER',   6);
define('HDOM_INFO_ENDSPACE',7);
define('DEFAULT_TARGET_CHARSET', 'UTF-8');
define('DEFAULT_BR_TEXT', "\r\n");
define('DEFAULT_SPAN_TEXT', " ");
define('MAX_FILE_SIZE', 600000);
// helper functions
// -----------------------------------------------------------------------------
// get html dom from file
// $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1.
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)
{
	// We DO force the tags to be terminated.
	$dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
	// For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
	$contents = file_get_contents($url, $use_include_path, $context, $offset);
	// Paperg - use our own mechanism for getting the contents as we want to control the timeout.
	//$contents = retrieve_url_contents($url);
	if (empty($contents) || strlen($contents) > MAX_FILE_SIZE)
	{
		return false;
	}
	// The second parameter can force the selectors to all be lowercase.
	$dom->load($contents, $lowercase, $stripRN);
	return $dom;
}

// get html dom from string
function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
	$dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
	if (empty($str) || strlen($str) > MAX_FILE_SIZE)
	{
		$dom->clear();
		return false;
	}
	$dom->load($str, $lowercase, $stripRN);
	return $dom;
}

// dump html dom tree
function dump_html_tree($node, $show_attr=true, $deep=0)
{
	$node->dump($node);
}


/**
 * simple html dom node
 * PaperG - added ability for "find" routine to lowercase the value of the selector.
 * PaperG - added $tag_start to track the start position of the tag in the total byte index
 *
 * @package PlaceLocalInclude
 */
class simple_html_dom_node
{
	public $nodetype = HDOM_TYPE_TEXT;
	public $tag = 'text';
	public $attr = array();
	public $children = array();
	public $nodes = array();
	public $parent = null;
	// The "info" array - see HDOM_INFO_... for what each element contains.
	public $_ = array();
	public $tag_start = 0;
	private $dom = null;

	function __construct($dom)
	{
		$this->dom = $dom;
		$dom->nodes[] = $this;
	}

	function __destruct()
	{
		$this->clear();
	}

	function __toString()
	{
		return $this->outertext();
	}

	// clean up memory due to php5 circular references memory leak...
	function clear()
	{
		$this->dom = null;
		$this->nodes = null;
		$this->parent = null;
		$this->children = null;
	}

	// dump node's tree
	function dump($show_attr=true, $deep=0)
	{
		$lead = str_repeat('	', $deep);

		echo $lead.$this->tag;
		if ($show_attr && count($this->attr)>0)
		{
			echo '(';
			foreach ($this->attr as $k=>$v)
				echo "[$k]=>\"".$this->$k.'", ';
			echo ')';
		}
		echo "\n";

		if ($this->nodes)
		{
			foreach ($this->nodes as $c)
			{
				$c->dump($show_attr, $deep+1);
			}
		}
	}


	// Debugging function to dump a single dom node with a bunch of information about it.
	function dump_node($echo=true)
	{

		$string = $this->tag;
		if (count($this->attr)>0)
		{
			$string .= '(';
			foreach ($this->attr as $k=>$v)
			{
				$string .= "[$k]=>\"".$this->$k.'", ';
			}
			$string .= ')';
		}
		if (count($this->_)>0)
		{
			$string .= ' $_ (';
			foreach ($this->_ as $k=>$v)
			{
				if (is_array($v))
				{
					$string .= "[$k]=>(";
					foreach ($v as $k2=>$v2)
					{
						$string .= "[$k2]=>\"".$v2.'", ';
					}
					$string .= ")";
				} else {
					$string .= "[$k]=>\"".$v.'", ';
				}
			}
			$string .= ")";
		}

		if (isset($this->text))
		{
			$string .= " text: (" . $this->text . ")";
		}

		$string .= " HDOM_INNER_INFO: '";
		if (isset($node->_[HDOM_INFO_INNER]))
		{
			$string .= $node->_[HDOM_INFO_INNER] . "'";
		}
		else
		{
			$string .= ' NULL ';
		}

		$string .= " children: " . count($this->children);
		$string .= " nodes: " . count($this->nodes);
		$string .= " tag_start: " . $this->tag_start;
		$string .= "\n";

		if ($echo)
		{
			echo $string;
			return;
		}
		else
		{
			return $string;
		}
	}

	// 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;
		}

		return $this->parent;
	}

	// verify that node has children
	function has_child()
	{
		return !empty($this->children);
	}

	// returns children of node
	function children($idx=-1)
	{
		if ($idx===-1)
		{
			return $this->children;
		}
		if (isset($this->children[$idx]))
		{
			return $this->children[$idx];
		}
		return null;
	}

	// returns the first child of node
	function first_child()
	{
		if (count($this->children)>0)
		{
			return $this->children[0];
		}
		return null;
	}

	// returns the last child of node
	function last_child()
	{
		if (($count=count($this->children))>0)
		{
			return $this->children[$count-1];
		}
		return null;
	}

	// returns the next sibling of node
	function next_sibling()
	{
		if ($this->parent===null)
		{
			return null;
		}

		$idx = 0;
		$count = count($this->parent->children);
		while ($idx<$count && $this!==$this->parent->children[$idx])
		{
			++$idx;
		}
		if (++$idx>=$count)
		{
			return null;
		}
		return $this->parent->children[$idx];
	}

	// returns the previous sibling of node
	function prev_sibling()
	{
		if ($this->parent===null) return null;
		$idx = 0;
		$count = count($this->parent->children);
		while ($idx<$count && $this!==$this->parent->children[$idx])
			++$idx;
		if (--$idx<0) return null;
		return $this->parent->children[$idx];
	}

	// function to locate a specific ancestor tag in the path to the root.
	function find_ancestor_tag($tag)
	{
		global $debug_object;
		if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }

		// Start by including ourselves in the comparison.
		$returnDom = $this;

		while (!is_null($returnDom))
		{
			if (is_object($debug_object)) { $debug_object->debug_log(2, "Current tag is: " . $returnDom->tag); }

			if ($returnDom->tag == $tag)
			{
				break;
			}
			$returnDom = $returnDom->parent;
		}
		return $returnDom;
	}

	// get dom node's inner html
	function innertext()
	{
		if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
		if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);

		$ret = '';
		foreach ($this->nodes as $n)
			$ret .= $n->outertext();
		return $ret;
	}

	// get dom node's outer text (with tag)
	function outertext()
	{
		global $debug_object;
		if (is_object($debug_object))
		{
			$text = '';
			if ($this->tag == 'text')
			{
				if (!empty($this->text))
				{
					$text = " with text: " . $this->text;
				}
			}
			$debug_object->debug_log(1, 'Innertext of tag: ' . $this->tag . $text);
		}

		if ($this->tag==='root') return $this->innertext();

		// trigger callback
		if ($this->dom && $this->dom->callback!==null)
		{
			call_user_func_array($this->dom->callback, array($this));
		}

		if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
		if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);

		// render begin tag
		if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
		{
			$ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
		} else {
			$ret = "";
		}

		// render inner text
		if (isset($this->_[HDOM_INFO_INNER]))
		{
			// If it's a br tag...  don't return the HDOM_INNER_INFO that we may or may not have added.
			if ($this->tag != "br")
			{
				$ret .= $this->_[HDOM_INFO_INNER];
			}
		} else {
			if ($this->nodes)
			{
				foreach ($this->nodes as $n)
				{
					$ret .= $this->convert_text($n->outertext());
				}
			}
		}

		// render end tag
		if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
			$ret .= '</'.$this->tag.'>';
		return $ret;
	}

	// get dom node's plain text
	function text()
	{
		if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
		switch ($this->nodetype)
		{
			case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
			case HDOM_TYPE_COMMENT: return '';
			case HDOM_TYPE_UNKNOWN: return '';
		}
		if (strcasecmp($this->tag, 'script')===0) return '';
		if (strcasecmp($this->tag, 'style')===0) return '';

		$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;
	}

	function xmltext()
	{
		$ret = $this->innertext();
		$ret = str_ireplace('<![CDATA[', '', $ret);
		$ret = str_replace(']]>', '', $ret);
		return $ret;
	}

	// build node's text with tag
	function makeup()
	{
		// text, comment, unknown
		if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);

		$ret = '<'.$this->tag;
		$i = -1;

		foreach ($this->attr as $key=>$val)
		{
			++$i;

			// skip removed attribute
			if ($val===null || $val===false)
				continue;

			$ret .= $this->_[HDOM_INFO_SPACE][$i][0];
			//no value attr: nowrap, checked selected...
			if ($val===true)
				$ret .= $key;
			else {
				switch ($this->_[HDOM_INFO_QUOTE][$i])
				{
					case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
					case HDOM_QUOTE_SINGLE: $quote = '\''; break;
					default: $quote = '';
				}
				$ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
			}
		}
		$ret = $this->dom->restore_noise($ret);
		return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
	}

	// find elements by css selector
	//PaperG - added ability for find to lowercase the value of the selector.
	function find($selector, $idx=null, $lowercase=false)
	{
		$selectors = $this->parse_selector($selector);
		if (($count=count($selectors))===0) return array();
		$found_keys = array();

		// 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();

			$head = array($this->_[HDOM_INFO_BEGIN]=>1);

			// handle descendant selectors, no recursive!
			for ($l=0; $l<$levle; ++$l)
			{
				$ret = array();
				foreach ($head as $k=>$v)
				{
					$n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
					//PaperG - Pass this optional parameter on to the seek function.
					$n->seek($selectors[$c][$l], $ret, $lowercase);
				}
				$head = $ret;
			}

			foreach ($head as $k=>$v)
			{
				if (!isset($found_keys[$k]))
				{
					$found_keys[$k] = 1;
				}
			}
		}

		// sort keys
		ksort($found_keys);

		$found = array();
		foreach ($found_keys as $k=>$v)
			$found[] = $this->dom->nodes[$k];

		// return nth-element or array
		if (is_null($idx)) return $found;
		else if ($idx<0) $idx = count($found) + $idx;
		return (isset($found[$idx])) ? $found[$idx] : null;
	}

	// seek for given conditions
	// PaperG - added parameter to allow for case insensitive testing of the value of a selector.
	protected function seek($selector, &$ret, $lowercase=false)
	{
		global $debug_object;
		if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }

		list($tag, $key, $val, $exp, $no_key) = $selector;

		// xpath index
		if ($tag && $key && is_numeric($key))
		{
			$count = 0;
			foreach ($this->children as $c)
			{
				if ($tag==='*' || $tag===$c->tag) {
					if (++$count==$key) {
						$ret[$c->_[HDOM_INFO_BEGIN]] = 1;
						return;
					}
				}
			}
			return;
		}

		$end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
		if ($end==0) {
			$parent = $this->parent;
			while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
				$end -= 1;
				$parent = $parent->parent;
			}
			$end += $parent->_[HDOM_INFO_END];
		}

		for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
			$node = $this->dom->nodes[$i];

			$pass = true;

			if ($tag==='*' && !$key) {
				if (in_array($node, $this->children, true))
					$ret[$i] = 1;
				continue;
			}

			// compare tag
			if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
			// compare key
			if ($pass && $key) {
				if ($no_key) {
					if (isset($node->attr[$key])) $pass=false;
				} else {
					if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
				}
			}
			// compare value
			if ($pass && $key && $val  && $val!=='*') {
				// If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
				if ($key == "plaintext") {
					// $node->plaintext actually returns $node->text();
					$nodeKeyValue = $node->text();
				} else {
					// this is a normal search, we want the value of that attribute of the tag.
					$nodeKeyValue = $node->attr[$key];
				}
				if (is_object($debug_object)) {$debug_object->debug_log(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}

				//PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
				if ($lowercase) {
					$check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
				} else {
					$check = $this->match($exp, $val, $nodeKeyValue);
				}
				if (is_object($debug_object)) {$debug_object->debug_log(2, "after match: " . ($check ? "true" : "false"));}

				// handle multiple class
				if (!$check && strcasecmp($key, 'class')===0) {
					foreach (explode(' ',$node->attr[$key]) as $k) {
						// Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
						if (!empty($k)) {
							if ($lowercase) {
								$check = $this->match($exp, strtolower($val), strtolower($k));
							} else {
								$check = $this->match($exp, $val, $k);
							}
							if ($check) break;
						}
					}
				}
				if (!$check) $pass = false;
			}
			if ($pass) $ret[$i] = 1;
			unset($node);
		}
		// It's passed by reference so this is actually what this function returns.
		if (is_object($debug_object)) {$debug_object->debug_log(1, "EXIT - ret: ", $ret);}
	}

	protected function match($exp, $pattern, $value) {
		global $debug_object;
		if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}

		switch ($exp) {
			case '=':
				return ($value===$pattern);
			case '!=':
				return ($value!==$pattern);
			case '^=':
				return preg_match("/^".preg_quote($pattern,'/')."/", $value);
			case '$=':
				return preg_match("/".preg_quote($pattern,'/')."$/", $value);
			case '*=':
				if ($pattern[0]=='/') {
					return preg_match($pattern, $value);
				}
				return preg_match("/".$pattern."/i", $value);
		}
		return false;
	}

	protected function parse_selector($selector_string) {
		global $debug_object;
		if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}

		// 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);}

		$selectors = array();
		$result = array();
		//print_r($matches);

		foreach ($matches as $m) {
			$m[0] = trim($m[0]);
			if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
			// for browser generated xpath
			if ($m[1]==='tbody') continue;

			list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
			if (!empty($m[2])) {$key='id'; $val=$m[2];}
			if (!empty($m[3])) {$key='class'; $val=$m[3];}
			if (!empty($m[4])) {$key=$m[4];}
			if (!empty($m[5])) {$exp=$m[5];}
			if (!empty($m[6])) {$val=$m[6];}

			// 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;}

			$result[] = array($tag, $key, $val, $exp, $no_key);
			if (trim($m[7])===',') {
				$selectors[] = $result;
				$result = array();
			}
		}
		if (count($result)>0)
			$selectors[] = $result;
		return $selectors;
	}

	function __get($name)
	{
		if (isset($this->attr[$name]))
		{
			return $this->convert_text($this->attr[$name]);
		}
		switch ($name)
		{
			case 'outertext': return $this->outertext();
			case 'innertext': return $this->innertext();
			case 'plaintext': return $this->text();
			case 'xmltext': return $this->xmltext();
			default: return array_key_exists($name, $this->attr);
		}
	}

	function __set($name, $value)
	{
		global $debug_object;
		if (is_object($debug_object)) {$debug_object->debug_log_entry(1);}

		switch ($name)
		{
			case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
			case 'innertext':
				if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
				return $this->_[HDOM_INFO_INNER] = $value;
		}
		if (!isset($this->attr[$name]))
		{
			$this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
			$this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
		}
		$this->attr[$name] = $value;
	}

	function __isset($name)
	{
		switch ($name)
		{
			case 'outertext': return true;
			case 'innertext': return true;
			case 'plaintext': return true;
		}
		//no value attr: nowrap, checked selected...
		return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
	}

	function __unset($name) {
		if (isset($this->attr[$name]))
			unset($this->attr[$name]);
	}

	// 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);}

		$converted_text = $text;

		$sourceCharset = "";
		$targetCharset = "";

		if ($this->dom)
		{
			$sourceCharset = strtoupper($this->dom->_charset);
			$targetCharset = strtoupper($this->dom->_target_charset);
		}
		if (is_object($debug_object)) {$debug_object->debug_log(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}

		if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0))
		{
			// Check if the reported encoding could have been incorrect and the text is actually already UTF-8
			if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text)))
			{
				$converted_text = $text;
			}
			else
			{
				$converted_text = iconv($sourceCharset, $targetCharset, $text);
			}
		}

		// Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output.
		if ($targetCharset == 'UTF-8')
		{
			if (substr($converted_text, 0, 3) == "\xef\xbb\xbf")
			{
				$converted_text = substr($converted_text, 3);
			}
			if (substr($converted_text, -3) == "\xef\xbb\xbf")
			{
				$converted_text = substr($converted_text, 0, -3);
			}
		}

		return $converted_text;
	}

	/**
	* Returns true if $string is valid UTF-8 and false otherwise.
	*
	* @param mixed $str String to be tested
	* @return boolean
	*/
	static function is_utf8($str)
	{
		$c=0; $b=0;
		$bits=0;
		$len=strlen($str);
		for($i=0; $i<$len; $i++)
		{
			$c=ord($str[$i]);
			if($c > 128)
			{
				if(($c >= 254)) return false;
				elseif($c >= 252) $bits=6;
				elseif($c >= 248) $bits=5;
				elseif($c >= 240) $bits=4;
				elseif($c >= 224) $bits=3;
				elseif($c >= 192) $bits=2;
				else return false;
				if(($i+$bits) > $len) return false;
				while($bits > 1)
				{
					$i++;
					$b=ord($str[$i]);
					if($b < 128 || $b > 191) return false;
					$bits--;
				}
			}
		}
		return true;
	}
	/*
	function is_utf8($string)
	{
		//this is buggy
		return (utf8_encode(utf8_decode($string)) == $string);
	}
	*/

	/**
	 * 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 (isset($this->attr['height']))
		{
			$height = $this->attr['height'];
		}

		// Now look for an inline style.
		if (isset($this->attr['style']))
		{
			// Thanks to user gnarf from stackoverflow for this regular expression.
			$attributes = array();
			preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $this->attr['style'], $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
			  $attributes[$match[1]] = $match[2];
			}

			// 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.

		$result = array('height' => $height,
						'width' => $width);
		return $result;
	}

	// camel naming conventions
	function getAllAttributes() {return $this->attr;}
	function getAttribute($name) {return $this->__get($name);}
	function setAttribute($name, $value) {$this->__set($name, $value);}
	function hasAttribute($name) {return $this->__isset($name);}
	function removeAttribute($name) {$this->__set($name, null);}
	function getElementById($id) {return $this->find("#$id", 0);}
	function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
	function getElementByTagName($name) {return $this->find($name, 0);}
	function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
	function parentNode() {return $this->parent();}
	function childNodes($idx=-1) {return $this->children($idx);}
	function firstChild() {return $this->first_child();}
	function lastChild() {return $this->last_child();}
	function nextSibling() {return $this->next_sibling();}
	function previousSibling() {return $this->prev_sibling();}
	function hasChildNodes() {return $this->has_child();}
	function nodeName() {return $this->tag;}
	function appendChild($node) {$node->parent($this); return $node;}

}

/**
 * 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 = "";

	// use isset instead of in_array, performance boost about 30%...
	protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
	protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
	// Known sourceforge issue #2977341
	// B tags that are not closed cause us to return everything to the end of the document.
	protected $optional_closing_tags = array(
		'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
		'th'=>array('th'=>1),
		'td'=>array('td'=>1),
		'li'=>array('li'=>1),
		'dt'=>array('dt'=>1, 'dd'=>1),
		'dd'=>array('dd'=>1, 'dt'=>1),
		'dl'=>array('dd'=>1, 'dt'=>1),
		'p'=>array('p'=>1),
		'nobr'=>array('nobr'=>1),
		'b'=>array('b'=>1),
		'option'=>array('option'=>1),
	);

	function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
	{
		if ($str)
		{
			if (preg_match("/^http:\/\//i",$str) || is_file($str))
			{
				$this->load_file($str);
			}
			else
			{
				$this->load($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
			}
		}
		// 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.
		if (!$forceTagsClosed) {
			$this->optional_closing_array=array();
		}
		$this->_target_charset = $target_charset;
	}

	function __destruct()
	{
		$this->clear();
	}

	// load html from string
	function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
	{
		global $debug_object;

		// prepare
		$this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
		// strip out cdata
		$this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
		// strip out comments
		$this->remove_noise("'<!--(.*?)-->'is");
		// Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
		// Script tags removal now preceeds style tag removal.
		// strip out <script> tags
		$this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
		$this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
		// strip out <style> tags
		$this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
		$this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
		// strip out preformatted tags
		$this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
		// strip out server side scripts
		$this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
		// strip smarty scripts
		$this->remove_noise("'(\{\w)(.*?)(\})'s", true);

		// parsing
		while ($this->parse());
		// end
		$this->root->_[HDOM_INFO_END] = $this->cursor;
		$this->parse_charset();

		// make load function chainable
		return $this;

	}

	// load html from file
	function load_file()
	{
		$args = func_get_args();
		$this->load(call_user_func_array('file_get_contents', $args), true);
		// Throw an error if we can't properly load the dom.
		if (($error=error_get_last())!==null) {
			$this->clear();
			return false;
		}
	}

	// set callback function
	function set_callback($function_name)
	{
		$this->callback = $function_name;
	}

	// remove callback function
	function remove_callback()
	{
		$this->callback = null;
	}

	// save dom as string
	function save($filepath='')
	{
		$ret = $this->root->innertext();
		if ($filepath!=='') file_put_contents($filepath, $ret, LOCK_EX);
		return $ret;
	}

	// find dom node by css selector
	// Paperg - allow us to specify that we want case insensitive testing of the value of the selector.
	function find($selector, $idx=null, $lowercase=false)
	{
		return $this->root->find($selector, $idx, $lowercase);
	}

	// 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);
	}

	function dump($show_attr=true)
	{
		$this->root->dump($show_attr);
	}

	// prepare HTML data and init everything
	protected function prepare($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
	{
		$this->clear();

		// 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);
		}

		$this->doc = $str;
		$this->pos = 0;
		$this->cursor = 1;
		$this->noise = array();
		$this->nodes = array();
		$this->lowercase = $lowercase;
		$this->default_br_text = $defaultBRText;
		$this->default_span_text = $defaultSpanText;
		$this->root = new simple_html_dom_node($this);
		$this->root->tag = 'root';
		$this->root->_[HDOM_INFO_BEGIN] = -1;
		$this->root->nodetype = HDOM_TYPE_ROOT;
		$this->parent = $this->root;
		if ($this->size>0) $this->char = $this->doc[0];
	}

	// parse html content
	protected function parse()
	{
		if (($s = $this->copy_until_char('<'))==='')
		{
			return $this->read_tag();
		}

		// text
		$node = new simple_html_dom_node($this);
		++$this->cursor;
		$node->_[HDOM_INFO_TEXT] = $s;
		$this->link_nodes($node, false);
		return true;
	}

	// 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;

		$charset = null;

		if (function_exists('get_last_retrieve_url_contents_content_type'))
		{
			$contentTypeHeader = get_last_retrieve_url_contents_content_type();
			$success = preg_match('/charset=(.+)/', $contentTypeHeader, $matches);
			if ($success)
			{
				$charset = $matches[1];
				if (is_object($debug_object)) {$debug_object->debug_log(2, 'header content-type found charset of: ' . $charset);}
			}

		}

		if (empty($charset))
		{
			$el = $this->root->find('meta[http-equiv=Content-Type]',0, true);
			if (!empty($el))
			{
				$fullvalue = $el->content;
				if (is_object($debug_object)) {$debug_object->debug_log(2, 'meta content-type tag found' . $fullvalue);}

				if (!empty($fullvalue))
				{
					$success = preg_match('/charset=(.+)/i', $fullvalue, $matches);
					if ($success)
					{
						$charset = $matches[1];
					}
					else
					{
						// If there is a meta tag, and they don't specify the character set, research says that it's typically ISO-8859-1
						if (is_object($debug_object)) {$debug_object->debug_log(2, 'meta content-type tag couldn\'t be parsed. using iso-8859 default.');}
						$charset = 'ISO-8859-1';
					}
				}
			}
		}

		// 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 (is_object($debug_object)) {$debug_object->debug_log(1, 'EXIT - ' . $charset);}

		return $this->_charset = $charset;
	}

	// read tag info
	protected function read_tag()
	{
		if ($this->char!=='<')
		{
			$this->root->_[HDOM_INFO_END] = $this->cursor;
			return false;
		}
		$begin_tag_pos = $this->pos;
		$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next

		// end tag
		if ($this->char==='/')
		{
			$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
			// This represents the change in the simple_html_dom trunk from revision 180 to 181.
			// $this->skip($this->token_blank_t);
			$this->skip($this->token_blank);
			$tag = $this->copy_until_char('>');

			// skip attributes in end tag
			if (($pos = strpos($tag, ' '))!==false)
				$tag = substr($tag, 0, $pos);

			$parent_lower = strtolower($this->parent->tag);
			$tag_lower = strtolower($tag);

			if ($parent_lower!==$tag_lower)
			{
				if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower]))
				{
					$this->parent->_[HDOM_INFO_END] = 0;
					$org_parent = $this->parent;

					while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
						$this->parent = $this->parent->parent;

					if (strtolower($this->parent->tag)!==$tag_lower) {
						$this->parent = $org_parent; // restore origonal parent
						if ($this->parent->parent) $this->parent = $this->parent->parent;
						$this->parent->_[HDOM_INFO_END] = $this->cursor;
						return $this->as_text_node($tag);
					}
				}
				else if (($this->parent->parent) && isset($this->block_tags[$tag_lower]))
				{
					$this->parent->_[HDOM_INFO_END] = 0;
					$org_parent = $this->parent;

					while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
						$this->parent = $this->parent->parent;

					if (strtolower($this->parent->tag)!==$tag_lower)
					{
						$this->parent = $org_parent; // restore origonal parent
						$this->parent->_[HDOM_INFO_END] = $this->cursor;
						return $this->as_text_node($tag);
					}
				}
				else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower)
				{
					$this->parent->_[HDOM_INFO_END] = 0;
					$this->parent = $this->parent->parent;
				}
				else
					return $this->as_text_node($tag);
			}

			$this->parent->_[HDOM_INFO_END] = $this->cursor;
			if ($this->parent->parent) $this->parent = $this->parent->parent;

			$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
			return true;
		}

		$node = new simple_html_dom_node($this);
		$node->_[HDOM_INFO_BEGIN] = $this->cursor;
		++$this->cursor;
		$tag = $this->copy_until($this->token_slash);
		$node->tag_start = $begin_tag_pos;

		// doctype, cdata & comments...
		if (isset($tag[0]) && $tag[0]==='!') {
			$node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');

			if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
				$node->nodetype = HDOM_TYPE_COMMENT;
				$node->tag = 'comment';
			} else {
				$node->nodetype = HDOM_TYPE_UNKNOWN;
				$node->tag = 'unknown';
			}
			if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
			$this->link_nodes($node, true);
			$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
			return true;
		}

		// text
		if ($pos=strpos($tag, '<')!==false) {
			$tag = '<' . substr($tag, 0, -1);
			$node->_[HDOM_INFO_TEXT] = $tag;
			$this->link_nodes($node, false);
			$this->char = $this->doc[--$this->pos]; // prev
			return true;
		}

		if (!preg_match("/^[\w-:]+$/", $tag)) {
			$node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
			if ($this->char==='<') {
				$this->link_nodes($node, false);
				return true;
			}

			if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
			$this->link_nodes($node, false);
			$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
			return true;
		}

		// begin tag
		$node->nodetype = HDOM_TYPE_ELEMENT;
		$tag_lower = strtolower($tag);
		$node->tag = ($this->lowercase) ? $tag_lower : $tag;

		// handle optional closing tags
		if (isset($this->optional_closing_tags[$tag_lower]) )
		{
			while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)]))
			{
				$this->parent->_[HDOM_INFO_END] = 0;
				$this->parent = $this->parent->parent;
			}
			$node->parent = $this->parent;
		}

		$guard = 0; // prevent infinity loop
		$space = array($this->copy_skip($this->token_blank), '', '');

		// attributes
		do
		{
			if ($this->char!==null && $space[0]==='')
			{
				break;
			}
			$name = $this->copy_until($this->token_equal);
			if ($guard===$this->pos)
			{
				$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
				continue;
			}
			$guard = $this->pos;

			// handle endless '<'
			if ($this->pos>=$this->size-1 && $this->char!=='>') {
				$node->nodetype = HDOM_TYPE_TEXT;
				$node->_[HDOM_INFO_END] = 0;
				$node->_[HDOM_INFO_TEXT] = '<'.$tag . $space[0] . $name;
				$node->tag = 'text';
				$this->link_nodes($node, false);
				return true;
			}

			// handle mismatch '<'
			if ($this->doc[$this->pos-1]=='<') {
				$node->nodetype = HDOM_TYPE_TEXT;
				$node->tag = 'text';
				$node->attr = array();
				$node->_[HDOM_INFO_END] = 0;
				$node->_[HDOM_INFO_TEXT] = substr($this->doc, $begin_tag_pos, $this->pos-$begin_tag_pos-1);
				$this->pos -= 2;
				$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
				$this->link_nodes($node, false);
				return true;
			}

			if ($name!=='/' && $name!=='') {
				$space[1] = $this->copy_skip($this->token_blank);
				$name = $this->restore_noise($name);
				if ($this->lowercase) $name = strtolower($name);
				if ($this->char==='=') {
					$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
					$this->parse_attr($node, $name, $space);
				}
				else {
					//no value attr: nowrap, checked selected...
					$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
					$node->attr[$name] = true;
					if ($this->char!='>') $this->char = $this->doc[--$this->pos]; // prev
				}
				$node->_[HDOM_INFO_SPACE][] = $space;
				$space = array($this->copy_skip($this->token_blank), '', '');
			}
			else
				break;
		} while ($this->char!=='>' && $this->char!=='/');

		$this->link_nodes($node, true);
		$node->_[HDOM_INFO_ENDSPACE] = $space[0];

		// check self closing
		if ($this->copy_until_char_escape('>')==='/')
		{
			$node->_[HDOM_INFO_ENDSPACE] .= '/';
			$node->_[HDOM_INFO_END] = 0;
		}
		else
		{
			// reset parent
			if (!isset($this->self_closing_tags[strtolower($node->tag)])) $this->parent = $node;
		}
		$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next

		// 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;
		}

		return true;
	}

	// parse attributes
	protected function parse_attr($node, $name, &$space)
	{
		// Per sourceforge: http://sourceforge.net/tracker/?func=detail&aid=3061408&group_id=218559&atid=1044037
		// If the attribute is already defined inside a tag, only pay atetntion to the first one as opposed to the last one.
		if (isset($node->attr[$name]))
		{
			return;
		}

		$space[2] = $this->copy_skip($this->token_blank);
		switch ($this->char) {
			case '"':
				$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
				$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
				$node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('"'));
				$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
				break;
			case '\'':
				$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_SINGLE;
				$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
				$node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('\''));
				$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
				break;
			default:
				$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
				$node->attr[$name] = $this->restore_noise($this->copy_until($this->token_attr));
		}
		// PaperG: Attributes should not have \r or \n in them, that counts as html whitespace.
		$node->attr[$name] = str_replace("\r", "", $node->attr[$name]);
		$node->attr[$name] = str_replace("\n", "", $node->attr[$name]);
		// 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.
		if ($name == "class") {
			$node->attr[$name] = trim($node->attr[$name]);
		}
	}

	// link node's parent
	protected function link_nodes(&$node, $is_child)
	{
		$node->parent = $this->parent;
		$this->parent->nodes[] = $node;
		if ($is_child)
		{
			$this->parent->children[] = $node;
		}
	}

	// as a text node
	protected function as_text_node($tag)
	{
		$node = new simple_html_dom_node($this);
		++$this->cursor;
		$node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
		$this->link_nodes($node, false);
		$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
		return true;
	}

	protected function skip($chars)
	{
		$this->pos += strspn($this->doc, $chars, $this->pos);
		$this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
	}

	protected function copy_skip($chars)
	{
		$pos = $this->pos;
		$len = strspn($this->doc, $chars, $pos);
		$this->pos += $len;
		$this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
		if ($len===0) return '';
		return substr($this->doc, $pos, $len);
	}

	protected function copy_until($chars)
	{
		$pos = $this->pos;
		$len = strcspn($this->doc, $chars, $pos);
		$this->pos += $len;
		$this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
		return substr($this->doc, $pos, $len);
	}

	protected function copy_until_char($char)
	{
		if ($this->char===null) return '';

		if (($pos = strpos($this->doc, $char, $this->pos))===false) {
			$ret = substr($this->doc, $this->pos, $this->size-$this->pos);
			$this->char = null;
			$this->pos = $this->size;
			return $ret;
		}

		if ($pos===$this->pos) return '';
		$pos_old = $this->pos;
		$this->char = $this->doc[$pos];
		$this->pos = $pos;
		return substr($this->doc, $pos_old, $pos-$pos_old);
	}

	protected function copy_until_char_escape($char)
	{
		if ($this->char===null) return '';

		$start = $this->pos;
		while (1)
		{
			if (($pos = strpos($this->doc, $char, $start))===false)
			{
				$ret = substr($this->doc, $this->pos, $this->size-$this->pos);
				$this->char = null;
				$this->pos = $this->size;
				return $ret;
			}

			if ($pos===$this->pos) return '';

			if ($this->doc[$pos-1]==='\\') {
				$start = $pos+1;
				continue;
			}

			$pos_old = $this->pos;
			$this->char = $this->doc[$pos];
			$this->pos = $pos;
			return substr($this->doc, $pos_old, $pos-$pos_old);
		}
	}

	// remove noise from html content
	// save the noise in the $this->noise array.
	protected function remove_noise($pattern, $remove_tag=false)
	{
		global $debug_object;
		if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }

		$count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);

		for ($i=$count-1; $i>-1; --$i)
		{
			$key = '___noise___'.sprintf('% 5d', count($this->noise)+1000);
			if (is_object($debug_object)) { $debug_object->debug_log(2, 'key is: ' . $key); }
			$idx = ($remove_tag) ? 0 : 1;
			$this->noise[$key] = $matches[$i][$idx][0];
			$this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
		}

		// reset the length of content
		$this->size = strlen($this->doc);
		if ($this->size>0)
		{
			$this->char = $this->doc[0];
		}
	}

	// restore noise to html content
	function restore_noise($text)
	{
		global $debug_object;
		if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }

		while (($pos=strpos($text, '___noise___'))!==false)
		{
			// 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...
			if (strlen($text) > $pos+15)
			{
				$key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13].$text[$pos+14].$text[$pos+15];
				if (is_object($debug_object)) { $debug_object->debug_log(2, 'located key of: ' . $key); }

				if (isset($this->noise[$key]))
				{
					$text = substr($text, 0, $pos).$this->noise[$key].substr($text, $pos+16);
				}
				else
				{
					// do this to prevent an infinite loop.
					$text = substr($text, 0, $pos).'UNDEFINED NOISE FOR KEY: '.$key . substr($text, $pos+16);
				}
			}
			else
			{
				// There is no valid key being given back to us... We must get rid of the ___noise___ or we will have a problem.
				$text = substr($text, 0, $pos).'NO NUMERIC NOISE KEY' . substr($text, $pos+11);
			}
		}
		return $text;
	}

	// Sometimes we NEED one of the noise elements.
	function search_noise($text)
	{
		global $debug_object;
		if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }

		foreach($this->noise as $noiseElement)
		{
			if (strpos($noiseElement, $text)!==false)
			{
				return $noiseElement;
			}
		}
	}
	function __toString()
	{
		return $this->root->innertext();
	}

	function __get($name)
	{
		switch ($name)
		{
			case 'outertext':
				return $this->root->innertext();
			case 'innertext':
				return $this->root->innertext();
			case 'plaintext':
				return $this->root->text();
			case 'charset':
				return $this->_charset;
			case 'target_charset':
				return $this->_target_charset;
		}
	}

	// camel naming conventions
	function childNodes($idx=-1) {return $this->root->childNodes($idx);}
	function firstChild() {return $this->root->first_child();}
	function lastChild() {return $this->root->last_child();}
	function createElement($name, $value=null) {return @str_get_html("<$name>$value</$name>")->first_child();}
	function createTextNode($value) {return @end(str_get_html($value)->nodes);}
	function getElementById($id) {return $this->find("#$id", 0);}
	function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
	function getElementByTagName($name) {return $this->find($name, 0);}
	function getElementsByTagName($name, $idx=-1) {return $this->find($name, $idx);}
	function loadFile() {$args = func_get_args();$this->load_file($args);}
}

?>
<!DOCTYPE HTML>
<html>
<head>

<!-- Кодирование -->
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 
<title>
Админка. Запросы с IP адреса <? echo $_SERVER["REMOTE_ADDR"] ?>
</title>
</head>

<body>

<?php

include ("config.php");

$ip = $_SERVER["REMOTE_ADDR"];
			
$stmt = $pdo->prepare('SELECT * FROM `short` WHERE `ip` = ?');
$stmt->execute([$ip]);
while ($row = $stmt->fetch(PDO::FETCH_LAZY))
{
	if ((is_numeric($row[2])) && ($row[1]<12))
					echo "<font color='red'>".$row[2]."</font>    <a href='".$row[3]."'>".$row[3]."</a><br>";
				
}


?>

</body>
</html>
<?php
// Подключение БД через PDO
$host="localhost";
$dbname="shorter";
$charset="UTF8";
$user="root";
$pass="Expl\$osion9200";


// Гуглокаптча
$secret_key = "6LfKfwYTAAAAANb9E_GrZ3zOa26KBsmQhhQCApAg";
$public_key = "6LfKfwYTAAAAAIFPeT0CSy6CA9s6mfRzudDNWt78";

$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);

try {
$pdo = new PDO($dsn, $user, $pass, $opt);
} catch (PDOException $e) {
     die("Конфигурация БД неверна. Это фатальная ошибка, обратитесь к администратору. <br> Подробности:". $e->getMessage());
}

/* ========================================================================
 * Bootstrap: dropdown.js v3.3.4
 * http://getbootstrap.com/javascript/#dropdowns
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // DROPDOWN CLASS DEFINITION
  // =========================

  var backdrop = '.dropdown-backdrop'
  var toggle   = '[data-toggle="dropdown"]'
  var Dropdown = function (element) {
    $(element).on('click.bs.dropdown', this.toggle)
  }

  Dropdown.VERSION = '3.3.4'

  function getParent($this) {
    var selector = $this.attr('data-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = selector && $(selector)

    return $parent && $parent.length ? $parent : $this.parent()
  }

  function clearMenus(e) {
    if (e && e.which === 3) return
    $(backdrop).remove()
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var relatedTarget = { relatedTarget: this }

      if (!$parent.hasClass('open')) return

      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return

      $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))

      if (e.isDefaultPrevented()) return

      $this.attr('aria-expanded', 'false')
      $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
    })
  }

  Dropdown.prototype.toggle = function (e) {
    var $this = $(this)

    if ($this.is('.disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('open')

    clearMenus()

    if (!isActive) {
      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
        // if mobile we use a backdrop because click events don't delegate
        $(document.createElement('div'))
          .addClass('dropdown-backdrop')
          .insertAfter($(this))
          .on('click', clearMenus)
      }

      var relatedTarget = { relatedTarget: this }
      $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))

      if (e.isDefaultPrevented()) return

      $this
        .trigger('focus')
        .attr('aria-expanded', 'true')

      $parent
        .toggleClass('open')
        .trigger('shown.bs.dropdown', relatedTarget)
    }

    return false
  }

  Dropdown.prototype.keydown = function (e) {
    if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return

    var $this = $(this)

    e.preventDefault()
    e.stopPropagation()

    if ($this.is('.disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('open')

    if (!isActive && e.which != 27 || isActive && e.which == 27) {
      if (e.which == 27) $parent.find(toggle).trigger('focus')
      return $this.trigger('click')
    }

    var desc = ' li:not(.disabled):visible a'
    var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)

    if (!$items.length) return

    var index = $items.index(e.target)

    if (e.which == 38 && index > 0)                 index--         // up
    if (e.which == 40 && index < $items.length - 1) index++         // down
    if (!~index)                                    index = 0

    $items.eq(index).trigger('focus')
  }


  // DROPDOWN PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.dropdown')

      if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  var old = $.fn.dropdown

  $.fn.dropdown             = Plugin
  $.fn.dropdown.Constructor = Dropdown


  // DROPDOWN NO CONFLICT
  // ====================

  $.fn.dropdown.noConflict = function () {
    $.fn.dropdown = old
    return this
  }


  // APPLY TO STANDARD DROPDOWN ELEMENTS
  // ===================================

  $(document)
    .on('click.bs.dropdown.data-api', clearMenus)
    .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
    .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
    .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)

}(jQuery);
/* ===========================================================
 * bootstrap-tooltip.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#tooltips
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ===========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function ($) {

  "use strict"; // jshint ;_;


 /* TOOLTIP PUBLIC CLASS DEFINITION
  * =============================== */

  var Tooltip = function (element, options) {
    this.init('tooltip', element, options)
  }

  Tooltip.prototype = {

    constructor: Tooltip

  , init: function (type, element, options) {
      var eventIn
        , eventOut
        , triggers
        , trigger
        , i

      this.type = type
      this.$element = $(element)
      this.options = this.getOptions(options)
      this.enabled = true

      triggers = this.options.trigger.split(' ')

      for (i = triggers.length; i--;) {
        trigger = triggers[i]
        if (trigger == 'click') {
          this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
        } else if (trigger != 'manual') {
          eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
          eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
          this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
          this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
        }
      }

      this.options.selector ?
        (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
        this.fixTitle()
    }

  , getOptions: function (options) {
      options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)

      if (options.delay && typeof options.delay == 'number') {
        options.delay = {
          show: options.delay
        , hide: options.delay
        }
      }

      return options
    }

  , enter: function (e) {
      var defaults = $.fn[this.type].defaults
        , options = {}
        , self

      this._options && $.each(this._options, function (key, value) {
        if (defaults[key] != value) options[key] = value
      }, this)

      self = $(e.currentTarget)[this.type](options).data(this.type)

      if (!self.options.delay || !self.options.delay.show) return self.show()

      clearTimeout(this.timeout)
      self.hoverState = 'in'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'in') self.show()
      }, self.options.delay.show)
    }

  , leave: function (e) {
      var self = $(e.currentTarget)[this.type](this._options).data(this.type)

      if (this.timeout) clearTimeout(this.timeout)
      if (!self.options.delay || !self.options.delay.hide) return self.hide()

      self.hoverState = 'out'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'out') self.hide()
      }, self.options.delay.hide)
    }

  , show: function () {
      var $tip
        , pos
        , actualWidth
        , actualHeight
        , placement
        , tp
        , e = $.Event('show')

      if (this.hasContent() && this.enabled) {
        this.$element.trigger(e)
        if (e.isDefaultPrevented()) return
        $tip = this.tip()
        this.setContent()

        if (this.options.animation) {
          $tip.addClass('fade')
        }

        placement = typeof this.options.placement == 'function' ?
          this.options.placement.call(this, $tip[0], this.$element[0]) :
          this.options.placement

        $tip
          .detach()
          .css({ top: 0, left: 0, display: 'block' })

        this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

        pos = this.getPosition()

        actualWidth = $tip[0].offsetWidth
        actualHeight = $tip[0].offsetHeight

        switch (placement) {
          case 'bottom':
            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'top':
            tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'left':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
            break
          case 'right':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
            break
        }

        this.applyPlacement(tp, placement)
        this.$element.trigger('shown')
      }
    }

  , applyPlacement: function(offset, placement){
      var $tip = this.tip()
        , width = $tip[0].offsetWidth
        , height = $tip[0].offsetHeight
        , actualWidth
        , actualHeight
        , delta
        , replace

      $tip
        .offset(offset)
        .addClass(placement)
        .addClass('in')

      actualWidth = $tip[0].offsetWidth
      actualHeight = $tip[0].offsetHeight

      if (placement == 'top' && actualHeight != height) {
        offset.top = offset.top + height - actualHeight
        replace = true
      }

      if (placement == 'bottom' || placement == 'top') {
        delta = 0

        if (offset.left < 0){
          delta = offset.left * -2
          offset.left = 0
          $tip.offset(offset)
          actualWidth = $tip[0].offsetWidth
          actualHeight = $tip[0].offsetHeight
        }

        this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
      } else {
        this.replaceArrow(actualHeight - height, actualHeight, 'top')
      }

      if (replace) $tip.offset(offset)
    }

  , replaceArrow: function(delta, dimension, position){
      this
        .arrow()
        .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
    }

  , setContent: function () {
      var $tip = this.tip()
        , title = this.getTitle()

      $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
      $tip.removeClass('fade in top bottom left right')
    }

  , hide: function () {
      var that = this
        , $tip = this.tip()
        , e = $.Event('hide')

      this.$element.trigger(e)
      if (e.isDefaultPrevented()) return

      $tip.removeClass('in')

      function removeWithAnimation() {
        var timeout = setTimeout(function () {
          $tip.off($.support.transition.end).detach()
        }, 500)

        $tip.one($.support.transition.end, function () {
          clearTimeout(timeout)
          $tip.detach()
        })
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        removeWithAnimation() :
        $tip.detach()

      this.$element.trigger('hidden')

      return this
    }

  , fixTitle: function () {
      var $e = this.$element
      if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
        $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
      }
    }

  , hasContent: function () {
      return this.getTitle()
    }

  , getPosition: function () {
      var el = this.$element[0]
      return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
        width: el.offsetWidth
      , height: el.offsetHeight
      }, this.$element.offset())
    }

  , getTitle: function () {
      var title
        , $e = this.$element
        , o = this.options

      title = $e.attr('data-original-title')
        || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

      return title
    }

  , tip: function () {
      return this.$tip = this.$tip || $(this.options.template)
    }

  , arrow: function(){
      return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
    }

  , validate: function () {
      if (!this.$element[0].parentNode) {
        this.hide()
        this.$element = null
        this.options = null
      }
    }

  , enable: function () {
      this.enabled = true
    }

  , disable: function () {
      this.enabled = false
    }

  , toggleEnabled: function () {
      this.enabled = !this.enabled
    }

  , toggle: function (e) {
      var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
      self.tip().hasClass('in') ? self.hide() : self.show()
    }

  , destroy: function () {
      this.hide().$element.off('.' + this.type).removeData(this.type)
    }

  }


 /* TOOLTIP PLUGIN DEFINITION
  * ========================= */

  var old = $.fn.tooltip

  $.fn.tooltip = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tooltip')
        , options = typeof option == 'object' && option
      if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tooltip.Constructor = Tooltip

  $.fn.tooltip.defaults = {
    animation: true
  , placement: 'top'
  , selector: false
  , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
  , trigger: 'hover focus'
  , title: ''
  , delay: 0
  , html: false
  , container: false
  }


 /* TOOLTIP NO CONFLICT
  * =================== */

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(window.jQuery);
/*!
 * Bootstrap v3.2.0 (http://getbootstrap.com)
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.2.0",d.prototype.close=function(b){function c(){f.detach().trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",c).emulateTransitionEnd(150):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.2.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),d[e](null==f[b]?this.options[b]:f[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b).on("keydown.bs.carousel",a.proxy(this.keydown,this)),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.2.0",c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.to=function(b){var c=this,d=this.getItemIndex(this.$active=this.$element.find(".item.active"));return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=e[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:g});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,f&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(e)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:g});return a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one("bsTransitionEnd",function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger(m)),f&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(b=!b),e||d.data("bs.collapse",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};c.VERSION="3.2.0",c.DEFAULTS={toggle:!0},c.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},c.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var c=a.Event("show.bs.collapse");if(this.$element.trigger(c),!c.isDefaultPrevented()){var d=this.$parent&&this.$parent.find("> .panel > .in");if(d&&d.length){var e=d.data("bs.collapse");if(e&&e.transitioning)return;b.call(d,"hide"),e||d.data("bs.collapse",null)}var f=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[f](0),this.transitioning=1;var g=function(){this.$element.removeClass("collapsing").addClass("collapse in")[f](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return g.call(this);var h=a.camelCase(["scroll",f].join("-"));this.$element.one("bsTransitionEnd",a.proxy(g,this)).emulateTransitionEnd(350)[f](this.$element[0][h])}}},c.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},c.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var d=a.fn.collapse;a.fn.collapse=b,a.fn.collapse.Constructor=c,a.fn.collapse.noConflict=function(){return a.fn.collapse=d,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(c){var d,e=a(this),f=e.attr("data-target")||c.preventDefault()||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),g=a(f),h=g.data("bs.collapse"),i=h?"toggle":e.data(),j=e.attr("data-parent"),k=j&&a(j);h&&h.transitioning||(k&&k.find('[data-toggle="collapse"][data-parent="'+j+'"]').not(e).addClass("collapsed"),e[g.hasClass("in")?"addClass":"removeClass"]("collapsed")),b.call(g,i)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.2.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(i.filter(":focus"));38==b.keyCode&&j>0&&j--,40==b.keyCode&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f+', [role="menu"], [role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.2.0",c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.$body.addClass("modal-open"),this.setScrollbar(),this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(c.$body),c.$element.show().scrollTop(0),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one("bsTransitionEnd",function(){c.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(300):c.$element.trigger("focus").trigger(e)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.$body.removeClass("modal-open"),this.resetScrollbar(),this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;if(this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;e?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(150):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var f=function(){c.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",f).emulateTransitionEnd(150):f()}else b&&b()},c.prototype.checkScrollbar=function(){document.body.clientWidth>=window.innerWidth||(this.scrollbarWidth=this.scrollbarWidth||this.measureScrollbar())},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.2.0",c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show()},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var c=a.contains(document.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!c)return;var d=this,e=this.tip(),f=this.getUID(this.type);this.setContent(),e.attr("id",f),this.$element.attr("aria-describedby",f),this.options.animation&&e.addClass("fade");var g="function"==typeof this.options.placement?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement,h=/\s?auto?\s?/i,i=h.test(g);i&&(g=g.replace(h,"")||"top"),e.detach().css({top:0,left:0,display:"block"}).addClass(g).data("bs."+this.type,this),this.options.container?e.appendTo(this.options.container):e.insertAfter(this.$element);var j=this.getPosition(),k=e[0].offsetWidth,l=e[0].offsetHeight;if(i){var m=g,n=this.$element.parent(),o=this.getPosition(n);g="bottom"==g&&j.top+j.height+l-o.scroll>o.height?"top":"top"==g&&j.top-o.scroll-l<0?"bottom":"right"==g&&j.right+k>o.width?"left":"left"==g&&j.left-k<o.left?"right":g,e.removeClass(m).addClass(g)}var p=this.getCalculatedOffset(g,j,k,l);this.applyPlacement(p,g);var q=function(){d.$element.trigger("shown.bs."+d.type),d.hoverState=null};a.support.transition&&this.$tip.hasClass("fade")?e.one("bsTransitionEnd",q).emulateTransitionEnd(150):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=k.left?2*k.left-e+i:2*k.top-f+j,m=k.left?"left":"top",n=k.left?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(l,d[0][n],m)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach(),c.$element.trigger("hidden.bs."+c.type)}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.removeAttr("aria-describedby"),this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one("bsTransitionEnd",b).emulateTransitionEnd(150):b(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName;return a.extend({},"function"==typeof c.getBoundingClientRect?c.getBoundingClientRect():null,{scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop(),width:d?a(window).width():b.outerWidth(),height:d?a(window).height():b.outerHeight()},d?{top:0,left:0}:b.offset())},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){clearTimeout(this.timeout),this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.2.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").empty()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.2.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.2.0",c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.closest("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},c.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one("bsTransitionEnd",e).emulateTransitionEnd(150):e(),f.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(c){c.preventDefault(),b.call(a(this),"show")})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.2.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=a(document).height(),d=this.$target.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=b-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){null!=this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:b-this.$element.height()-h}))}}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},d.offsetBottom&&(d.offset.bottom=d.offsetBottom),d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
<?php
$db=mysql_connect("localhost", "root", "Expl\$osion9200");
mysql_select_db("shorter" ,$db);
?>
<!DOCTYPE HTML>
<html>
<head>

<!-- Кодирование -->
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <meta name='yandex-verification' content='595e54a28ff5ebed' />
 <meta name="google-site-verification" content="Ww7zu_aQeqn8ROJWS5446gasnWDuwvaGuvZUuLpQjeI" />
 
 <meta name="keywords" content="сокращалка ссылок, сокращение ссылки, сократи ссылку, уменьшить ссылку, сокращение ссылки, укоротить ссылку" />
 <meta name="description" content="Сокращалка ссылок. Тут можно сделать из длинной ссылки короткую, а также сохранить картинку">
 <meta name="version" content="2.3">
 <meta name="author" content="Максим Анархистов" />
 <meta name="copyright" lang="ru" content="Bright Studio" />
 <meta name="document-state" content="Static" />
 <meta name="robots" content="index,nofollow" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 
<title>
Сокращалка ссылкок
</title>

<style type="text/css">

body {
	background: url("/data/back3.png");
	 }

.row {  margin:0!important;
		margin-top:2px!important;
}

</style>
	
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
	<link href="data/bootstrap.min.css" rel="stylesheet">
	<script src="data/bootstrap.min.js"></script>
	<script src='https://www.google.com/recaptcha/api.js'></script>
	

    <script type="text/javascript">
        $(document).ready(function() {
			
            $('#short_button').click(function() {
                $.post('save.php', {link : $('#link').attr('value'), 
									 what : $('#what').attr('value'),
									  auto : $('#auto').attr('checked'),
									   nolink : $('#nolink').attr('checked'),
										captcha : $('form').serialize()
				}, function(data) {
                    $('#user_data').html(data);
                });
            });
        });
    </script>
	
	
    <script type="text/javascript">
        $(document).ready(function() {
            $('#save_button').click(function() {
                $.post('save.php', {link : $('#link').attr('value'), 
									what : $('#what').attr('value'),
									 auto : $('#auto').attr('checked'),
									  image : 'checked',
									   nolink : $('#nolink').attr('checked'),
				}, function(data) {
                    $('#user_data').html(data);
                });
            });		
        });
    </script>
	
	
  <script>
  jQuery(document).ready(function($) {
	
      $('[data-toggle="tooltip"]').tooltip({
			trigger: "hover",
			container: 'body'			
		});  

	 $('.dropdown-toggle').dropdown();
	 
	 $('#myModal').on('shown.bs.modal', function () {
		$('#myInput').focus()
	 })
		
    })
  </script>


<!-- Иконка _black-->
<link rel="shortcut icon" href="http://anim.0hd.ru/favicon.ico" type="image/ico">
    

</head>

<?php

// Функция однократного перемещения. Чтобы выкинуть http
function str_ireplace_once($search, $replace, $text) 
{ 
   $pos = stripos($text, $search); 
   return $pos!==false ? substr_replace($text, $replace, $pos, strlen($search)) : $text; 
} 
//

// Сам линк 
if (isset($_REQUEST['request'])) { $request=$_REQUEST['request']; } else $request='';

// Эта строчка сразу вставится в поле короткой ссылки
if (isset($_REQUEST['shortlink'])) { $shortlink=$_REQUEST['shortlink']; } else $shortlink='';

if ($request=='404') {echo 'Ou shi! Ou fuck!';} else {

if ($request=='') 
  {									
	echo "

<div class='row'>
  <div class='col-md-3 col-md-offset-5'> 
   <div class='dropdown'>
	<div class='dropdown dropdown-toggle' data-toggle='dropdown' aria-expanded='true' role='button'>
		<img src='data/3qa.png' width='90' alt='3qa.ru'><span class='caret' aria-hidden='true'></span>
	</div>	
	<ul class='dropdown-menu' role='menu'>
		<li role='presentation'><a role='menuitem' tabindex='-1' href='#' data-toggle='modal' data-target='#inform'>Войти</a></li>
		<li role='presentation'><a role='menuitem' tabindex='-1' href='#' data-toggle='modal' data-target='#inform'>Зарегистрироваться </a></li>
		<li role='presentation'><a role='menuitem' tabindex='-1' href='#' data-toggle='modal' data-target='#inform'>Бонусные функции</a></li>
		<li role='presentation'><a role='menuitem' tabindex='-1' href='#' data-toggle='modal' data-target='#inform'>Что происходит?</a></li>
	</ul>
   </div>
  </div>
</div>



<div class='modal fade bs-example-modal-lg' tabindex='-1' role='dialog' aria-labelledby='myLargeModalLabel' aria-hidden='true' id='inform'>
<div class='modal-dialog'>
    <div class='modal-content'>
      <div class='modal-header'>
        <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
        <h4 class='modal-title' id='myModalLabel'>Информация к размышлению</h4>
      </div>
      <div class='modal-body'>
        Привет! Этот сайт позволяет сделать из длинной ссылки короткую для быстрого её запоминания, а также создать для длинной ссылки ссылку-синоним вида <a href='http://".$_SERVER['SERVER_NAME']."/anything'>".$_SERVER['SERVER_NAME']."/anything</a>. На данный момент проект имеет базовую (вполне рабочую) функциональность, и не имеет специфических (хитрозадуманных) функций вроде запоминания всех ранее введенных ссылок и возможности их удалить (хотя тестовая страничка с этим функционалом уже <a href='http://admin.3qa.ru'>имеется</a>), но сервис будет развиваться и совершенствоваться.<br>
		<br>
		В дальнейшем планируется создать страницу при переходе по сокращенной ссылке, на которой будет размещен десятисекундный таймер с рекламой (или любой другой информацией), с помощью которой вы можете зарабатывать. Также планируются собственные поддомены, статистика, сохранение файлов по короткой ссылке, ссылка позволяющую отследить и сохранить данные посетившего её пользователя и торрент трекер (шутка).<br>
		<br>		
		Список текущих задач:<br>
		Сохранение картинок - тестовый режим (доступен при регистрации).<br>
		Регистрация - в разработке<br>
		Админка - в разработке <br>
		Сохранение данных пользователя - в разработке<br>
		Сохранение файлов - в планах<br>
		Реклама - в планах<br>
			
		
      </div>
      <div class='modal-footer'>
        <button type='button' class='btn btn-default' data-dismiss='modal'>Закрыть</button>
      </div>
    </div>
  </div>
</div>



	
<div class='row'>
  <div class='col-md-1 col-md-offset-4'> 
			Сюда&nbsp;ссылку:
  </div>
  
  
  <div class='col-md-3'>
  <div class='input-group'>
   <input type='text' class='form-control' id='link'>
      <span class='input-group-addon' rel='tooltip' data-toggle='tooltip' data-placement='bottom' title='Поставьте здесь галочку, если необходим просто текст. Будут работать перенос строк по /n и не будет ссылки'>
        <input type='checkbox' id='nolink'>
      </span>
  </div>
  </div>
</div>



<div class='row'>
  <div class='col-md-1 col-md-offset-4 example-1'> 
  
			3qa.ru/
	
	<a class='btn-mini btn-info' data-toggle='tooltip' data-placement='bottom' title='Сюда можно ввести короткую ссылку'>?</a>
  </div>
  
  
  <div class='col-md-3'>
  <div class='input-group'>
   <input type='text' class='form-control' id='what' value='$shortlink'>
      <span class='input-group-addon' rel='tooltip' data-toggle='tooltip' data-placement='bottom' title='Поставьте здесь галочку, если не хотите, чтобы перемещение на сайт происходило автоматически'>
        <input type='checkbox' id='auto'>
      </span>
  </div>
  </div>
  
  
  
</div>

<div class='row'>
  <div class='col-md-3 col-md-offset-5'> 
		<input type='submit' value='Сократить' class='searchfield btn btn-primary' name='submit' id='short_button'>		
		<input type='submit' value='Сохранить' class='searchfield btn btn' name='submit' id='save_button'>	
		<br>

  </div>
</div>

<br>

<div class='row'>
  <div class='col-md-4 col-md-offset-4'> 
		<div id='user_data'></div>
  </div>
</div>
";

  }
  else {
  
	$link_not_exists = true;
	
    include ("config.php");
	echo "<a href='http://3qa.ru'>&crarr;</a>";

		$stmt = $pdo->prepare('SELECT * FROM `short` WHERE `little` = ?');
		$stmt->execute([$request]);
		while ($tablerows = $stmt->fetch(PDO::FETCH_LAZY))
			
			{
				$link_not_exists = false;
			   $clearlink=$tablerows[3];
			     
					if  (stripos($clearlink, 'http://') < 5 and stripos($clearlink, 'http://') !== false) 
					{ $clearlink=str_ireplace_once('http://','',$clearlink); $addn='//'; }

			   else if  (stripos($clearlink, 'https://') < 5 and stripos($clearlink, 'https://') !== false) 
					{ $clearlink=str_ireplace_once('https://','',$clearlink); $addn='https://'; }	
					
			   else if  (stripos($clearlink, 'ftp://') < 5 	and stripos($clearlink, 'ftp://') !== false) 
					{ $clearlink=str_ireplace_once('ftp://','',$clearlink); $addn='ftp://'; }				

			   else if  (stripos($clearlink, '//') < 1 	and stripos($clearlink, '//') !== false) 
					{ $clearlink=str_ireplace_once('//','',$clearlink); $addn='//'; }					
			
			   else if  (stripos($clearlink, ':') < 10 	and stripos($clearlink, ':') !== false) 
					{  $addn=''; }					
					
			   else if  ((stripos($clearlink, '://') === false) or
						(stripos($clearlink, '://') >=7) ) $addn='//';
			   
			   else $addn='';
			   
			// --------

				echo "<div class='row'>
						<div class='col-md-3 col-md-offset-4'>"; 
							
					if ($tablerows[1]==12) // При отсутсвии форматирования добавляем переносы
						{
							$clearlink=str_ireplace('/n','<br>',$clearlink);		
							$clearlink=str_ireplace('\n','<br>',$clearlink);		
							echo "$clearlink";
						}
						
					if ($tablerows[1]==6)  echo "<a href='$addn$clearlink'>$clearlink</a>";
					
					if ($tablerows[1]==24) echo "<img width=400 src='$clearlink' alt='img'>";
/*							
							echo "	</div>
					 </div>
					 
		<script>		
			function relink() 
				{
					window.open('$addn$clearlink', '_parent');
				}
			if ($tablerows[1]===0) relink();
			</script>     ";
			
*/			if ($tablerows[1]==0)
			header ('Location: '.$addn.$clearlink);

			}
			
			// Если ничего не нашлось
			if ($link_not_exists) 
			{
				echo "
<div class='row'>
  <div class='col-md-5 col-md-offset-4'> 
		<b>Запрошенная вами ссылка не найдёна.</b> <br><br>
		Попробуйте уточнить почему её тут нет у человека который ваc сюда привёл. <br>
		Ну или не парьтсь и создайте новую ссылку на <a href = 'http://".$_SERVER['SERVER_NAME']."'> главной</a>.<br><br>
		Вы даже можете занять именно эту страницу, и все люди, пришедшие сюда могут попадать совершенно в другое место, мухаха! *потирает руки*. <a href='http://".$_SERVER['SERVER_NAME']."/?shortlink=".ucfirst(strtolower($request))."'>Вот тут </a> для этого уже всё подготовлено.
		<br>
  </div>
</div>";
			}
			
	}
} ?>



<div class='invisible'>Сокращалка ссылок. Максим Анархистов. ver 2.3 </div>

<!-- Yandex.Metrika counter -->
<script type="text/javascript">
    (function (d, w, c) {
        (w[c] = w[c] || []).push(function() {
            try {
                w.yaCounter30166244 = new Ya.Metrika({
                    id:30166244,
                    clickmap:true,
                    trackLinks:true,
                    accurateTrackBounce:true,
                    webvisor:true,
                    trackHash:true
                });
            } catch(e) { }
        });

        var n = d.getElementsByTagName("script")[0],
            s = d.createElement("script"),
            f = function () { n.parentNode.insertBefore(s, n); };
        s.type = "text/javascript";
        s.async = true;
        s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js";

        if (w.opera == "[object Opera]") {
            d.addEventListener("DOMContentLoaded", f, false);
        } else { f(); }
    })(document, window, "yandex_metrika_callbacks");
</script>
<!-- /Yandex.Metrika counter -->


</body>
</html>
<?php

include ("db.php"); error_reporting(0); // Подключаем БД
include ("config.php");

function filter( $var , $sql = 0) { // Фильтрация строки от XSS

	$var=str_replace ("\n","/n", $var);
        $var=str_replace ("\r","", $var);
	$var=str_ireplace('<br>','/n',$var); 
	
	$var = strip_tags($var); // html and php tags
	if ( $sql == 1) { 
		$var = mysql_real_escape_string($var);
	}
	return $var;
	}
	
function google_curl ($captcha, $secret_key) {
		json_decode($captcha);
		$captcha=substr($captcha,21);
	
		if( $curl == curl_init() ) {
		curl_setopt($curl, CURLOPT_URL, 
			'https://www.google.com/recaptcha/api/siteverify');
		curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, "secret=$secret_key&response=".$captcha);
		$out = curl_exec($curl);
		$out = json_decode($out);
		
		$out = (array)$out;
		curl_close($curl);
		//print_r($out); echo "<br>";
		//echo $secret_key."?<br>";
		return $out['success'];
		}
}
	
function generate_code($length = 5){  // Not used NOW
    $num = rand(11111, 99999);
    $code = md5($num);
    $code = substr($code, 0, (int)$length);
    return $code;
}

	
// Получаем данные с предыдущей формы
	$link=    filter($_REQUEST['link']);
	$what=    filter($_REQUEST['what']);
	$auto=    $_REQUEST['auto'];
	$nolink=  $_REQUEST['nolink'];
	$image=   $_REQUEST['image'];
	$captcha= $_REQUEST['captcha'];

// Костыль для сохранения картинки/файла
	if (($what=='630077') and ($image==true)) {
		$passw = $what;
		$what = '';
	}	
  
// Обработка исключения если в поле ссылки нет ничего
	if  ($link=='') 
	{
			 echo " <div class='alert alert-danger' role='alert'>
						<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
						Нет ничего же!
					</div>"; 		
	}
else {	
			
	// Обработка исключения если в поле сокращения нет ничего. Тогда присваиваем цифру
	if ($what=='') 
		{
			
		// Каптча проверка	
		if (!google_curl($captcha,$secret_key)) 
		{
			$result=mysql_query("SELECT `ip` FROM `short` WHERE `long` LIKE '$link';",$db);
			while ($tablerows = mysql_fetch_row($result))
			{
				
				if ($tablerows[0] == $_SERVER["REMOTE_ADDR"]) 
				{
					echo "<div class='alert alert-danger' role='alert'>
							<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
							Подозрительный вы какой-то. Пройдите тест:
						  </div>"; 
					
					echo "<form id='mainform'><div class='g-recaptcha' data-sitekey='$public_key'></div></form> <script src='https://www.google.com/recaptcha/api.js'></script>";
					exit;
					
				}
			}
		}	
		
	
						// смотрим последнее число (PDO)
		 $last_num = $pdo->query("SELECT `long` FROM `short` WHERE `little` = '404' LIMIT 0 , 30;")->fetch();
		 $last_num = $last_num["long"];
		
		 // Совпадения?
		 $sovpad  = $pdo->prepare("SELECT `long` FROM `short` WHERE `little` LIKE ?");
		 $sovpad->execute(array($last_num+1));
		 $sovpad = $sovpad->fetch();
		 $sovpad = $sovpad['long'];

		$i=1;			
			while ($sovpad == $last_num+$i) 
				{
					$i=$i+1;
					$sovpad  = $pdo->prepare("SELECT `long` FROM `short` WHERE `little` LIKE ?");
					$sovpad->execute(array($last_num+$i+1));
					$sovpad = $sovpad->fetch();
					$sovpad = $sovpad['long'];
				}
				$what=$last_num+$i;

				mysql_query("UPDATE `shorter`.`short` SET `long` = $what WHERE `short`.`id` =100 AND `short`.`little` = '404';",$db);
		}
	// Конец присвоения цифры

$abp=mysql_query("SELECT * FROM `short` WHERE `little` = '$what' ",$db);    // проверка на повторение
$apb=mysql_fetch_row($abp);													// костыль или нет?

if ( $apb=='') 
	{
	if ($auto==true) { $id=6; } else { $id=0; } // Если 6 - релинка не будет, если 0 - будет
	if ($nolink==true) { $id=12; } // Если 12 - покажу без ссылки. Костыль, да.
	
	// Сохранить изображение или файл
	if ($image==true) 
		{
			if ($passw!='630077') {
				echo "<div class='alert alert-danger' role='alert'>
						<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
						Для данной функции необходим пароль
					  </div>"; 
				exit;
			}
			
			$id=24;
			$fileFrom = $link;
			$filenameFrom = basename($fileFrom);
			$uploadToDir = 'images/'.$filenameFrom; //path путь на нашем сервере
			if (!copy($fileFrom, $uploadToDir)) {
				echo "<div class='alert alert-danger' role='alert'>
						<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
						Неопознанная ошибка загрузки $uploadToDir
					   </div>"; 
				exit;
			}
			$link='images/'.basename($link);
		}

		// Всё, сохраняем (PDO)
		$ip = $_SERVER["REMOTE_ADDR"];
		
			try {			  
				$result = $pdo->prepare("INSERT INTO `shorter`.`short` (`id`, `little`, `long`,`ip`) VALUES (?,?,?,?)");
				$result -> execute(array($id, $what, $link, $ip));
				}
			catch(PDOException $e){
					echo " <div class='alert alert-danger' role='alert'>
							<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
							Сайт допустил недопустимое, выполнил невыполнимое.
							</div>";
					exit();
				}

			if ($result>0) {
			echo "<div class='alert alert-success' role='alert'>Запись добавлена. Короткая ссылка:  
					<a href='http://".$_SERVER['SERVER_NAME']."/".$what."' >".$_SERVER['SERVER_NAME']."/".$what."</a></div>";}  
					// Вы приняты. Распишитесь.
	} 
	else
		echo " <div class='alert alert-danger' role='alert'>
				<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
				Такой индентификатор уже существует
			   </div>";
				// ...идите нахуй
	
} // Закрытие условия, есть ли что-то в поле ссылки
	mysql_close($db);
?>