<?php
/**
 * @package Sami's cURL class
 * @version $Id: samis_curl.class.php v.1.0 2014-01-27 18:04:00 $
 * @author Samuil Banti
 * @copyright (C) 2015 - Samuil Banti
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
class samis_curl
{

	/**
	* Send data to given URL via POST method and get the output
	* Useful for automatic submit
	* @param string $url - The url to post the data to.
	* @param array $variables - The array of varables. The keys are the names of the variables.
	* @return string $server_output - The server response
	*/
	public function curl_post_get_output($url, $variables = array(), $files = array())
	{
        foreach($files as $fileName => $filePath) {
            $variables[$fileName] = curl_file_create($filePath);
        }
	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($variables));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$server_output = curl_exec ($ch);
		curl_close ($ch);
		return $server_output;
	}

	/**
	* Send data to given URL via POST method and get the cookies
	* Useful for automatic login
	* @param string $url - The url to post the data to.
	* @param array $variables - The array of varables. The keys are the names of the variables.
	* @return string $cookies - The cookies
	*/
	public function curl_post_get_cookies($url, $variables = array())
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($variables));
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$cookies = curl_exec ($ch);
		curl_close ($ch);
		return $cookies;
	}

	/**
	* Send data to given URL via POST method using cookie and get the output
	* Useful for crolling web pages that require login
	* @param string $url - The url to post the data to.
	* @param string $cookie_file - The path to the file that contains the cookie information
	* @param array $variables - The array of varables. The keys are the names of the variables.
	* @return string $server_output - The server response
	*/
	public function curl_post_using_cookie($url, $cookie_file, $variables = array())
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($variables));
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
		curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$server_output = curl_exec ($ch);
		curl_close ($ch);
		return $server_output;
	}

	/**
	* Parse session ID drom cookie string
	* @param string $cookie_string - The cookie
	* @return array $cookies - Array with the session IDs
	*/
	public function parse_set_cookie($cookie_string)
	{
		preg_match('/^Set-Cookie:\s*([^;]*)/mi', $cookie_string, $m);
		parse_str($m[1], $cookies);
		return $cookies;
	}
}

