<?php

/*

*

* Web Traffic Genius Pro v3.5.4

* Copyright (c) 2008-2010

* Success on the Internet Pty Ltd

* PO Box 25

* Salisbury SA 5108

* Australia

* Phone: +61 422 512 549

* Fax: +61 8 8425 9657

* Web: http://www.webtrafficgenius.com

* Support: http://www.marketing-assassins.com

*

*/



require_once(dirname(__FILE__) . '/config.php');

require_once(dirname(__FILE__) . '/php5_functions.php');

require_once(dirname(__FILE__) . '/curl_functions.php');

require_once(dirname(__FILE__) . '/form_parser.php');

require_once(dirname(__FILE__) . '/rss_log.php');



function wtg_submit_url($url, $postvars, &$returned_headers, &$last_url,$method="POST") {

	global $logger, $indent;



	if (wtg_is_curl_preferred()) {

		//		$logger->log('(curl)', 0, false);

		return wtg_submit_url_curl($url, $postvars, $returned_headers, $last_url);

	} else {

		//		$logger->log('(build-in socket)', 0, false);

		return wtg_request_url_php($url, $method, $postvars, $returned_headers, $last_url);

	}

}





function wtg_fetch_url($url, &$returned_headers, &$last_url) {

	global $logger, $indent;



	if (wtg_is_curl_preferred()) {

		$logger->buf('(curl)', 0, false);

		return wtg_fetch_url_curl($url, $returned_headers, $last_url);

	} else {

		$logger->buf('(build-in socket)', 0, false);

		return wtg_request_url_php($url, 'GET', array(), $returned_headers, $last_url);

	}

}





function wtg_request_url_php($url, $method, $post_vars, &$returned_headers, &$last_url, $max_redirect = 10){

	$redirect = 0;



	global $logger, $indent;

	

	

	if ($method == 'POST') $logger->buf(str_repeat(' ', $indent) . 'Submitting to url ' . $url);



	do {

		$returned_headers = array();

		$last_url = '';

		$need_redirect = false; // akb & rrb



		$u = @parse_url($url);

		if ($u == false) return false;  // not a valid url

		if (empty($u['port'])) $u['port'] = 80;



		$fp = fsockopen($u['host'], $u['port']);

		if (!$fp) return false; // connection fail

		

		$uri = (empty($u['path'])?'/':$u['path']) . (empty($u['query'])?'': '?' . $u['query']);



		$request = "";

		$request .= strtoupper($method) . " $uri HTTP/1.1\r\n";

		$request .= 'Host: ' . $u['host'] . ':' . $u['port'] . "\r\n";



		// add cookies header from cookie file

		$cookies = wtg_parse_cookie_file_to_cookies();

		$cook_str = 'Cookie: ';

		foreach ($cookies as $k => $v) {

			$cook_str .= "{$k}={$v};";

		}



		// add user cookies

		if (!empty($GLOBALS['config']['usercookie'])) {

			foreach ($GLOBALS['config']['usercookie'] as $k => $v) {

				$cook_str .= "{$k}={$v};";

			}

		}



		$request .= "{$cook_str}\r\n";



		// add other header

		$request .= "User-Agent: " . BROWSER . "\r\n";

		if (!empty($GLOBALS['config']['header'])) {

			foreach ($GLOBALS['config']['header'] as $k => $v) {

				$canonicalName = implode('-', array_map('ucfirst', explode('-', $k)));

				$request .= trim($canonicalName) . ': ' . $v . "\r\n";  // very much top1

			}

		}



		// add referer header

		if (!empty($GLOBALS['referer'])) {

			$request .= "Referer: {$GLOBALS['referer']}\r\n";

		}



		// method is post

		if (strtoupper($method) == 'POST')	{

			$request .= "Content-Type: application/x-www-form-urlencoded\r\n";

			$postdata = wtg_parse_post_array($post_vars);

			$request .= 'Content-Length: ' . strlen($postdata) . "\r\n";

		}



		$request .= "\r\n";  // header end



		// body content

		if (strtoupper($method) == 'POST')	{

			$request .= $postdata;

		}



		// send the request

		if (fwrite($fp, $request) === false) { // error while send the request

			fclose($fp);

			return false;

		}



		// read response

		$rsp = '';

		while(!feof($fp)) {

			$rsp .= fread($fp,4096);

		}

		fclose($fp);

		wtg_dump_url_to_file($url, $rsp);

		// process the response

		$hunks = explode("\r\n\r\n",trim($rsp));

		$body    = trim($hunks[1]);

		$headers = explode("\n", $hunks[0]);



		// get response code

		if (!preg_match('!^(HTTP/\d\.\d) (\d{3})(?: (.+))?!', $headers[0], $s)) {

			return false;

		} else {

			$response_code = intval($s[2]);

			array_shift($headers);

		}

		if (preg_match('|Transfer-encoding\s*:\s*chunked|im', $hunks[0])) { // unchunk body

			$body = trim(wtg_unchunkHttpResponse($body));

		}



		// deal with cookies

		$cookie_header = wtg_parse_cookie_file_to_cookies();

		foreach( $headers as $response ) {

			$head = explode(':', $response, 2);

			$head = array_map('trim', $head);



			// Check for cookies

			if ( strtolower($head[0]) == 'set-cookie' ) {

				$cookies = explode(';', $head[1]);

				foreach( $cookies as $cookie ) {

					$cook = explode( '=', trim($cookie), 2 );

					if ( isset($cook[0]) ) {

						switch( trim(strtolower($cook[0])) ) {

							case 'expires':

							case 'path':

								break;

							default:

								$cookie_header[ $cook[0] ] = $cook[1];

								break;

						}

					}

				}

			} else {

				if ( count($head) == 2 ) {

					if ( !array_key_exists($head[0], $returned_headers) )

					$returned_headers[ ucfirst($head[0]) ] = array();

					$returned_headers[ ucfirst($head[0]) ][] = ltrim($head[1]);

				}

			}

		}



		// write cookies to cookie file

		file_put_contents( COOKIEJAR, serialize($cookie_header) );



		$last_url = $url;

		$GLOBALS['referer'] = $url;



		// if response code is a redirect

		if ($response_code > 300 && $response_code < 399 && ++$redirect < $max_redirect && !empty($returned_headers['Location'])) { //redirect

			$need_redirect = true;

			$url = wtg_get_url_relative($url, $returned_headers['Location'][0]);

			$method = 'GET';

			$post_vars = array();

		}



	} while ($need_redirect);

	

	if ($response_code >= 200 && $response_code < 300) {

		$logger->info(' SUCCESS', 0, false);

		return $body;

	} else {

		$logger->error(' FAIL', 0, false);

		return false;

	}

}



function wtg_unchunkHttpResponse($str=null) {

	if (!is_string($str) or strlen($str) < 1) { return false; }

	$eol = "\r\n";

	$add = strlen($eol);

	$tmp = $str;

	$str = '';



	do {

		$tmp = ltrim($tmp);

		$pos = strpos($tmp, $eol);

		if ($pos === false) { return false; }

		$len = hexdec(substr($tmp, 0, $pos));

		if (!is_numeric($len) or $len < 0) { return false; }

		$str .= substr($tmp, ($pos + $add), $len);

		$tmp  = substr($tmp, ($len + $pos + $add));

		$check = trim($tmp);

	} while(!empty($check));



	unset($tmp);

	return $str;

}



function wtg_parse_cookie_file_to_cookies(){

	if ( file_exists(COOKIEJAR) ) {

		$cookies = unserialize(file_get_contents(COOKIEJAR));

	}

	return empty($cookies)?array():$cookies;

}