<?php
/*
* Curl functions
*
* 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');

function wtg_is_curl_preferred() {
	if (defined('CURL_PREFERRED') && CURL_PREFERRED && extension_loaded('curl')) {
		return true;
	}
	return false;
}

function wtg_fetch_url_curl( $url, &$returned_headers, &$last_url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
	curl_setopt($ch, CURLOPT_TIMEOUT, 120);
	if (CURL_PREFERRED == 1) {
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  //use curl_redir_exec when open_basedir is set
	}
	curl_setopt($ch, CURLOPT_MAXREDIRS,10);
	curl_setopt($ch, CURLOPT_USERAGENT, BROWSER);
	curl_setopt($ch, CURLOPT_HTTPGET, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	if (isset($GLOBALS['referer'])) {
		curl_setopt($ch, CURLOPT_REFERER, $GLOBALS['referer']);
	}
	if (!empty($GLOBALS['config']['header'])) {
		$httpheader = array();
		foreach ($GLOBALS['config']['header'] as $k => $v) {
			$httpheader[] = trim($k) . ': ' . $v;
		}
		//curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
	}
	//	add_user_cookie($ch);

	curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIEJAR);
	curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIEJAR);
	if (CURL_PREFERRED == 1) {
		$txt = curl_exec($ch);
	}
	else {
		$txt = wtg_curl_redir_exec($ch);
	}

	$GLOBALS['referer'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
	$last_url = $GLOBALS['referer'];

	curl_close($ch);

	wtg_dump_url_to_file($url, $txt);
	return $txt;
}

function wtg_submit_url_curl( $url, $postvars, &$returned_headers, &$last_url ) {
	global $logger, $indent;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
	curl_setopt($ch, CURLOPT_TIMEOUT, 120);
	if (CURL_PREFERRED == 1) {
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  //use curl_redir_exec when open_basedir is set
	}

	curl_setopt($ch, CURLOPT_MAXREDIRS,10);
	curl_setopt($ch, CURLOPT_USERAGENT, BROWSER);
	curl_setopt($ch, CURLOPT_HTTPGET, 0);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_POSTFIELDS, wtg_parse_post_array($postvars));

	if (isset($GLOBALS['referer'])) {
		curl_setopt($ch, CURLOPT_REFERER, $GLOBALS['referer']);
	}
	if (!empty($GLOBALS['config']['header'])) {
		$httpheader = array();
		foreach ($GLOBALS['config']['header'] as $k => $v) {
			$httpheader[] = trim($k) . ': ' . $v;
		}
		//curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
	}
	//	add_user_cookie($ch);

	curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIEJAR);
	curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIEJAR);

	$logger->buf(str_repeat(' ', $indent) . 'Submitting to url ' . $url);
	if (CURL_PREFERRED == 1) {
		$txt = curl_exec($ch);
	}
	else {
		$txt = wtg_curl_redir_exec($ch);
	}
	$logger->info(empty($txt)?' FAIL':' SUCCESS', 0, false);

	$GLOBALS['referer'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
	$last_url = $GLOBALS['referer'];

	curl_close($ch);
	wtg_dump_url_to_file($url, $txt);
	return $txt;
}

function wtg_add_user_cookie($ch) {
	$cookie = '';
	if (!empty($GLOBALS['config']['usercookie'])) {
		foreach ($GLOBALS['config']['usercookie'] as $k => $v) {
			$cookie .= ($k . '='. $v . ';');
		}
	}
	curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}

//use this function when open_basedir is set/not redirected automatically
function wtg_curl_redir_exec($ch) {
	static $curl_loops = 0;
	static $curl_max_loops = 20;
		
	if ($curl_loops++>= $curl_max_loops)
	{
		$curl_loops = 0;
		return FALSE;
	}
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$data = curl_exec($ch);
	list($header, $data) = explode("\n\n", $data, 2);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	if ($http_code == 301 || $http_code == 302)
	{
		$matches = array();
		preg_match('/Location:(.*?)\n/', $header, $matches);
		$url = @parse_url(trim(array_pop($matches)));
		if (!$url)
		{
			//couldn't process the url to redirect to
			$curl_loops = 0;
			return $data;
		}
		$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
		if (!$url['scheme'])
		$url['scheme'] = $last_url['scheme'];
		if (!$url['host'])
			$url['host'] = $last_url['host'];
		if (!$url['path'])
			$url['path'] = $last_url['path'];
		$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
		curl_setopt($ch, CURLOPT_URL, $new_url);
		return wtg_curl_redir_exec($ch);
	} else {
		$curl_loops=0;
		return $data;
	}
}

function wtg_dump_url_to_file($url, $txt) {
	if ( DEBUG ) {
		$file = DUMP_DIR .'/' . wtg_get_filename_from_url($url);
		$ctr = '';
		while ( file_exists($file.$ctr) ) $ctr++;
		@file_put_contents( $file.$ctr, $txt );
	}
}

function wtg_get_filename_from_url( $url ) {
	$f = @parse_url($url);
	return wtg_sanitize_name( isset($f['path']) ? $f['path'] : basename($url) );
}

function wtg_sanitize_name( $url ) {
	$retval = '';
	$url = str_replace('/', '__', $url);
	$url = str_replace('\\', '__', $url);
	for ( $i = 0; $i < strlen($url); $i++ ) {
		if ( strpos('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ ', $url{$i}) !== false )
		$retval .= $url{$i};
	}
	return $retval. '_' . time() . '_';
}

function wtg_parse_post_array($post_data) {
	$o="";
	foreach ($post_data as $k=>$v) {
		if($v[0] == '' && isset($v[1])) {
			$v[0]=$v[1];
		}
		$o.= "$k=".urlencode(utf8_encode($v[0]))."&";
	}
	return substr($o,0,-1);
}

function wtg_get_captcha_img ($image) {
	if (isset($image))
	{
		$time=time();
		$filename=dirname(__FILE__) . '/captcha/'.$time.'.jpg';
		
		// $data = file_get_contents($image);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $image);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
		curl_setopt($ch, CURLOPT_TIMEOUT, 120);
		if (CURL_PREFERRED == 1) {
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  //use curl_redir_exec when open_basedir is set
		}
		curl_setopt($ch, CURLOPT_MAXREDIRS,10);
		curl_setopt($ch, CURLOPT_USERAGENT, BROWSER);
		curl_setopt($ch, CURLOPT_HTTPGET, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		if (!empty($GLOBALS['config']['header'])) {
			$httpheader = array();
			foreach ($GLOBALS['config']['header'] as $k => $v) {
				$httpheader[] = trim($k) . ': ' . $v;
			}
			//curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
		}
		$post='';
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		curl_setopt($ch, CURLOPT_POSTFIELDSIZE, strlen($image)); 
		curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIEJAR);
		curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIEJAR);
		$data = curl_exec($ch);
		curl_close($ch);
		if($data) {
			$file = fopen($filename, "w+");
			fputs($file, $data);
			fclose($file); 
			return $filename;
		}
	}
	return false;
}

// $data is an array
function wtg_post_data($url, $data)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}

// split fields
function wtg_split_fields ($data)
{
	$ret = array();
	$lines = explode("\n", $data);
	if($lines)
	{
		foreach($lines as $line)
		{
			$x = trim($line);
			if(strlen($x) == 0) continue;

			$value = strstr($x, " ");
			$name = "";
			if($value === FALSE)
			{
				$name = $x;
				$value = "";
			}
			else
			{
				$name = substr($x, 0, strlen($x) - strlen($value));
				$value = trim($value);
			}
			$ret[$name] = $value;
		}
	}
	return $ret;
}

// return NULL if decode failed
function wtg_submit_captcha($key, $img_file_name)
{
	global $bc_task_id;
	$bc_task_id = -1;
	
	// read image data of image
	$fp = fopen($img_file_name, "rb");
	if(!$fp) return NULL;
	$file_size = filesize($img_file_name);
	if($file_size <= 0) return NULL;
	$data = fread($fp, $file_size);
	fclose($fp);

	// use base64 encoding to encode it
	$enc_data = base64_encode($data);

	// submit it to server
	if(strlen($key) != 40 && strlen($key) != 32) return NULL;
	$data = wtg_post_data("http://bypasscaptcha.com/upload.php",
			array( "key" => $key, "file" => $enc_data, "submit" => "Submit",
						"gen_task_id" => 1, "base64_code" => 1));

	// dict
	$dict = wtg_split_fields($data);
	if(array_key_exists("TaskId", $dict) && array_key_exists("Value", $dict))
	{
		$bc_task_id = $dict["TaskId"];
		return $dict["Value"];
	}
	return NULL;
}

function wtg_get_poster_decaptcher ($user, $pwd, $image) {
	$postData['pict']= "@$image";
	$postData['function']= "picture2";
	// username and password can be different for different users.
	$postData['username']= $user;
	$postData['password']= $pwd;
	$postData['pict_to']= "0";
	$postData['pict_type']= "0";
	$postData['submit']= 'Send';
	$url = 'http://72.233.78.211'; // http://72.233.78.211 or http://poster.decaptcher.com/
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
	curl_setopt($ch, CURLOPT_TIMEOUT, 120);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  //use curl_redir_exec when open_basedir is set
	curl_setopt($ch, CURLOPT_MAXREDIRS,10);
	curl_setopt($ch, CURLOPT_USERAGENT, BROWSER);
	curl_setopt($ch, CURLOPT_HTTPGET, 0);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
	$response = curl_exec( $ch );
	curl_close($ch );
	$results=split("\|", $response);
	return $results[5];
}

function wtg_get_captcha_result_by_deathbycaptcha ($user, $pwd, $image) {
	$client = new DeathByCaptcha_Client();
	// Put our username & password here
	if ($client->login($user, $pwd)) {
		// Put our CAPTCHA image file name and optional timeout (in seconds) here,
		// we'll receive CAPTCHA (id, text) tuple on success
		$result = $client->decode($image);
		if ($result) {
			list($id, $text) = $result;
			return $text;
			// Report if the CAPTCHA was solved incorrectly
		   // $client->report($id);
		}
	}
	return false;
}

function wtg_get_version($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}