<?php
/*
=====================
Модуль скачен с сайта:
Понедельников НЕТ! - Сайт альтернативной поддержки Slaed CMS! (http://www.ponedelnikov.net)
=====================
SHAKA1, 2009
e-mail: seregam007@mail.ru
=====================
*/
include_once ('config.inc.php');

/**
 * This function pring message to your output (browser or console)
 */
function showMsg($msg) {
	echo date(LOG_MESSAGE_DATE_FORMAT).': '.$msg.LOG_MESSAGE_SEPARATOR;
}

/**
 * fnuction which read XML elements and put it into array
 */
function readXmlElements ($xml, $split_xml = false) {
	$element = array();
	preg_match_all('/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s', $xml, $array_params);
	foreach ($array_params[1] as $param_key => $tag_name) {
		if ( strpos($array_params[3][$param_key], "<") !== false) {
			if ($split_xml == true) {
				$subelements = readXmlElements($array_params[3][$param_key], $split_xml);
				foreach ($subelements as $key => $value) {
					$element[$tag_name."_".$key] = $value;
				}
			}
			continue;
		}
		$element[$tag_name] = $array_params[3][$param_key];
	}
	return $element;
}

/**
 * parse XML data into array
 */
class xml2Array {

	var $arrOutput = array();
	var $resParser;
	var $strXmlData;

	function &parse(&$strInputXML) {

		$this->resParser = xml_parser_create ();
		xml_set_object($this->resParser,$this);
		xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

		xml_set_character_data_handler($this->resParser, "tagData");

		$this->strXmlData = xml_parse($this->resParser,$strInputXML );
		if(!$this->strXmlData) {
			return sprintf("XML error: %s at line %d",
			xml_error_string(xml_get_error_code($this->resParser)),
			xml_get_current_line_number($this->resParser));
		}

		xml_parser_free($this->resParser);

		return $this->arrOutput;
	}

	function tagOpen($parser, $name, $attrs) {
		$tag=array("name"=>$name,"attrs"=>$attrs);
		array_push($this->arrOutput,$tag);
	}

	function tagData($parser, $tagData) {
		if(trim($tagData) != '') {
			if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
				$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
			}
			else {
				$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
			}
		}
	}

	function tagClosed($parser, $name) {
		$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
		array_pop($this->arrOutput);
	}
}

/**
 * send request via HTTP
 */
function http_post2($url,$data, &$line, &$response_header_array, $method = "POST"){
	$cookie_text = "";
	$referer = "";

	if (isset($response_header_array["cookies"]) && is_array($response_header_array["cookies"])) {
		$cookie_strings = array();
		reset($response_header_array["cookies"]);
		foreach($response_header_array{"cookies"} as $key => $value) {
			array_push($cookie_strings, $key."=".$value);
		}
		$cookie_text = implode ('; ', $cookie_strings);
	}

	if (!empty($response_header_array{"referer"})){
		$referer = $response_header_array{"referer"};
	}

	if (!is_array($response_header_array)) {
		$response_header_array = array();
	}
	else {
		foreach($response_header_array as $key => $value) {
			if ($key != "cookies") {
				unset($response_header_array{$key});
			}
		}
	}

	# insert into request XML vars
	$url_info = parse_url($url);
	$headers = array();
	$_is_xml = 0;
	if (is_array($data)) {
		if (isset($data{"__xml__"})) {
			$_is_xml = 1;
			$data_string = $data{"__xml__"};
		} else {
			$values = array();
			foreach($data as $key=>$value)
				$values[] = "$key=".urlencode($value);
			$data_string = implode("&",$values);
		}
	}
	else {
		$data_string = $data;
	}
	$scheme = strtolower($url_info{"scheme"});

	if(!isset($url_info["port"])) {
		if ($scheme != "https") {
			$url_info["port"]=80;
		} else {
			$url_info["port"]=443;
		}
	}
	$method = strtolower($method);
	$request = "";
	if ($method == "post") {
		$request.="POST ".$url_info["path"].(!empty($url_info{"query"}) ? "?".$url_info{"query"} : "")." HTTP/1.0\r\n";
	}
	else {
		$get_url = $url_info["path"].($url_info{"query"} != "" ? "?".$url_info{"query"}.($data_string != "" ? "&".$data_string : "") : ($data_string != "" ? "?".$data_string :""));
		$request.="GET ".$get_url." HTTP/1.0\r\n";
	}
	$request.="Host: ".$url_info["host"]."\r\n";
	if ($cookie_text != "") {
		$request .= "Cookie: ".$cookie_text."\r\n";
	}
	$request.="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; BTT V3.0) \r\n";
	if ($method == "post") {
		$request.="Content-type: ".($_is_xml == 0 ? "application/x-www-form-urlencoded" : "text/xml")."\r\n";
		$request.="Content-length: ".strlen($data_string)."\r\n";
	}
	$request.="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
	$request.="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1\r\n";
	$request.="Accept-Language: en-us,en;q=0.5\r\n";

	if ($referer != "") {
		$request.="Referer: $referer\r\n";
	}
	if (!empty($HTTP_AUTH_USER)) {
		$request	.="Authorization: Basic ".base64_encode($HTTP_AUTH_USER.":".$HTTP_AUTH_PASS)."\r\n";
	}
	$request.="Connection: close\r\n";
	$request.="Cache-Control: max-age=0\r\n";
	$request.="\r\n";
	if ($method == "post") {
		$request.=$data_string."\r\n";
	}
	$errno = "";
	$errstr = "";

	$count = 0;
	$charge_attempts = 0;
	$response_received = false;
	$null_result = "";
	$post_time = array();
	$is_timeout = false;
	$full_transaction_time = 0;

	while ($count < 1 && !$response_received) {
		$count++;
		$charge_attempts++;
		if (!$fp = fsockopen(($scheme == "https" ? "ssl://" : "").$url_info["host"],$url_info["port"], $errno, $errstr, 10)) {
			break;
		}

		stream_set_timeout($fp, 600);

		fputs($fp, $request);
		while(!feof($fp)) {
			@$buff = @fgets($fp, 4096);
			if ($buff == false) {
				$fp_meta = stream_get_meta_data($fp);
				if ($fp_meta['timed_out'] == true) {
					$is_timeout = true;
					break;
				}
			}
			else {
				@$result .= $buff;
				$response_received = true;
			}
		}
		@fclose($fp);
	}

	if (!$response_received) return 0;

	list($response_headers,$response) = @explode("\r\n\r\n",$result,2);
	$response_header_lines = @explode("\r\n",$response_headers);
	$http_response_line = array_shift($response_header_lines);
	foreach ($response_header_lines as $header_line) {
		list($header,$value) = explode(': ',$header_line,2);
		if (isset($response_header_array[$header])) {
			if (!is_array($response_header_array[$header])) {
				$_re = $response_header_array[$header];
				$response_header_array[$header] = array();
				array_push($response_header_array[$header], $_re);
			}
		}
		if (isset($response_header_array[$header]) && is_array($response_header_array[$header])) {
			array_push($response_header_array[$header], $value);
		} else {
			$response_header_array[$header] = $value;
		}
	}

	// get cookies
	$cookies = array();
	if (isset($response_header_array['Set-Cookie']) && !is_array($response_header_array['Set-Cookie']) && !empty($response_header_array['Set-Cookie'])) {
		$response_header_array['Set-Cookie'] = array($response_header_array['Set-Cookie']);
	}
	if (isset($response_header_array['Set-Cookie']) && is_array($response_header_array['Set-Cookie'])) {
		reset($response_header_array['Set-Cookie']);
		foreach ($response_header_array['Set-Cookie'] as $cookie_line) {
			if (preg_match('/([^\n;]*)(.*expires=([^\n;]*))?/i', $cookie_line, $matches)) {
				list ($variable, $value) =  explode ('=', $matches[1], 2);
				if ($value != "") {
					$cookies{$variable} = $value;
				}
			}
		}
	}
	unset($response_header_array['Set-Cookie']);
	if (count($cookies) > 0) {
		if (!is_array($response_header_array{"cookies"})) {
			$response_header_array{"cookies"} = array();
		}
		foreach ($cookies as $key => $value) {
			$response_header_array{"cookies"}{$key} = $value;
		}
	}

	$line = $response;
	return 1;
}


?>