Subversion Repositories SmartDukaan

Rev

Rev 12999 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
10582 lgm 1
<?php defined('BASEPATH') OR exit('No direct script access allowed');
2
 
3
/**
4
**/
5
 
6
/**
7
 * CodeIgniter MCurl Class
8
 *
9
 * Work with remote servers via multi-cURL much easier than using the native PHP bindings.
10
 *
11
 * @package			CodeIgniter
12
 * @subpackage		Libraries
13
 * @category		Libraries
14
 * @author			Chad Hutchins
15
 * @link			http://github.com/chadhutchins/codeigniter-mcurl
16
 */
17
 
18
class Mcurl {
19
 
20
	private $_ci;				// CodeIgniter instance
21
	private $calls = array();	// multidimensional array that holds individual calls and data
22
	private $curl_parent;		// the curl multi handle resource
23
 
24
	function __construct()
25
	{
11387 lgm 26
 
10582 lgm 27
		$this->_ci = & get_instance();
28
		log_message('debug', 'Mcurl Class Initialized');
29
		if (!$this->is_enabled())
30
		{
31
			log_message('error', 'Mcurl Class - PHP was not built with cURL enabled. Rebuild PHP with --with-curl to use cURL.');
32
		}
33
		else 
34
		{
35
			$this->curl_parent = curl_multi_init();
36
		}
37
	}
38
 
39
	// check to see if necessary function exists
40
	function is_enabled()
41
	{
42
		return function_exists('curl_multi_init');
43
	}
44
	// method to add curl requests to the multi request queue
45
	function add_call($key=null, $method, $url, $params = array(), $options = array())
46
	{
13061 anikendra 47
		$authorized=$this->_ci->session->userdata('authorized');
48
		if(isset($authorized['isPrivateDealUser']) && !empty($authorized['isPrivateDealUser'])) {
49
			$params['privateDealUser'] = 'true';
50
		}
10582 lgm 51
		if (is_null($key))
52
		{
53
			$key = count($this->calls);
54
		}
55
 
56
		// check to see if the multi handle has been closed
57
		// init the multi handle again
58
		$resource_type = get_resource_type($this->curl_parent);
59
		if(!$resource_type || $resource_type == 'Unknown')
60
		{
61
			$this->calls = array();
62
			$this->curl_parent = curl_multi_init();
63
		}
64
 
65
		$this->calls [$key]= array(
66
			"method" => $method,
67
			"url" => $url,
68
			"params" => $params,
69
			"options" => $options,
70
			"curl" => null,
71
			"response" => null,
72
			"error" => null
73
		);
74
 
75
		$this->calls[$key]["curl"] = curl_init();
76
 
77
		$newdata =$params;
78
		// If its an array (instead of a query string) then format it correctly
79
		if (is_array($params))
80
		{
81
			$params = http_build_query($params, NULL, '&');
82
		}
83
 
84
		$method = strtoupper($method);
85
 
86
		// only supports get/post requests
87
		// set some special curl opts for each type of request
88
		switch ($method)
89
		{			
90
			case "POST":
91
				curl_setopt($this->calls[$key]["curl"], CURLOPT_URL, $url);
92
				curl_setopt($this->calls[$key]["curl"], CURLOPT_POST, TRUE);
93
				curl_setopt($this->calls[$key]["curl"], CURLOPT_POSTFIELDS, $params);
94
				curl_setopt($this->calls[$key]["curl"], CURLOPT_SSL_VERIFYPEER, false);
95
				break;
96
 
97
			case "GET":
98
				if (strpos($url,'?') !== false) {
99
    				curl_setopt($this->calls[$key]["curl"], CURLOPT_URL, $url."&".$params);
100
    			}
101
    			else{
102
    				curl_setopt($this->calls[$key]["curl"], CURLOPT_URL, $url."?".$params);
103
    			}
104
				curl_setopt($this->calls[$key]["curl"], CURLOPT_SSL_VERIFYPEER, false);
105
				break;
106
 
107
			default:
108
				log_message('error', 'Mcurl Class - Provided http method is not supported. Only POST and GET are currently supported.');
109
				break;
110
		}
111
		curl_setopt($this->calls[$key]["curl"], CURLOPT_RETURNTRANSFER, TRUE);
112
		curl_setopt($this->calls[$key]["curl"], CURLOPT_FOLLOWLOCATION, TRUE);
11109 lgm 113
		if(($key == 'tracking') || ($key == 'signup') || ($key == 'orderconfirmation_process')){
114
			$cookiesStringToPass="";
115
			foreach($_COOKIE as $cookie) {
116
				if ($cookiesStringToPass) {
117
	     			$cookiesStringToPass  .= ';';
118
	    		}
119
	    		if(is_object(json_decode($cookie))){
120
	    			$cookieInfo = json_decode($cookie);
121
	    			foreach ($cookieInfo as $info) {
122
	    				$cookiesStringToPass .= $info->name . '=' . addslashes($info->value);
123
	    			}
124
	    		}
125
			}
126
			curl_setopt($this->calls[$key]["curl"], CURLOPT_COOKIE, $cookiesStringToPass);
12999 anikendra 127
			foreach (getallheaders() as $name => $value) {
128
			    if($name == "X-Forwarded-For"){
129
			    	$headers = array('X-Forwarded-For : '.$value);
130
			    	curl_setopt($this->calls[$key]["curl"], CURLOPT_HTTPHEADER, $headers);
131
			    }
132
			}
11109 lgm 133
		}
10582 lgm 134
		curl_setopt_array($this->calls[$key]["curl"], $options);
135
		curl_multi_add_handle($this->curl_parent,$this->calls[$key]["curl"]);		 
136
	}
137
 
138
	// run the calls in the curl requests in $this->calls
139
	function execute()
140
	{
11170 lgm 141
		if (count($this->calls) <= 0)
142
			return False;
10582 lgm 143
		if (count($this->calls))
144
		{
145
			// kick off the requests
146
			do
147
			{
11170 lgm 148
				//print_r($this->calls);
10582 lgm 149
				$multi_exec_handle = curl_multi_exec($this->curl_parent,$active);
150
			} while ($active>0);
151
 
152
			// after all requests finish, set errors and repsonses in $this->calls
153
			foreach ($this->calls as $key => $call)
154
			{
155
				$error = curl_error($this->calls[$key]["curl"]);
156
				if (!empty($error))
157
				{
11387 lgm 158
					if($key != 'tracking' && $key != 'recommended_accessories'){
10582 lgm 159
					$this->calls[$key]["error"] = $error;
11510 lgm 160
					$url = 'http://www.saholic.com/'.uri_string();
11387 lgm 161
					$this->_ci->session->set_userdata('errorurl',$url);
162
					//$errmsg ='<h3>OH SNAP!!!! :</h3><p>Something is not right. <br/><h1>But Relax</h1> <br/>We are working hard on it. </p>';
163
					$msg = '
164
					API for '.$key.' is not working.
165
 
166
					url of API Failed ===> '.$this->calls[$key]['url'].'
11681 lgm 167
					parameters are ===> '.$call['params'].'
168
 
11387 lgm 169
					Access modifier is Public.
170
 
171
					Error is ====> '.$this->calls[$key]["error"].'';
172
					$this->write_log_send_mail('error',$msg);
10739 lgm 173
					//$this->session->set_flashdata('errormsg',$errmsg);
11387 lgm 174
					redirect(base_url().'error_page/index');
175
					exit();
10739 lgm 176
					}
10582 lgm 177
				}
178
				$this->calls[$key]["response"] = curl_multi_getcontent($this->calls[$key]["curl"]);
10800 lgm 179
				$http_status = curl_getinfo($this->calls[$key]["curl"], CURLINFO_HTTP_CODE);
11226 lgm 180
				if($key != 'tracking' && $key != 'recommended_accessories'){
10802 lgm 181
					if($http_status != 200) {
11354 lgm 182
						$url = 'http://www.saholic.com/'.uri_string();
183
						$this->_ci->session->set_userdata('errorurl',$url);
11387 lgm 184
						$msg = '
185
						API for '.$key.' is not working.
186
 
187
						url of API Failed ===> '.$this->calls[$key]['url'].'
11681 lgm 188
						parameters are ===> '.$call['params'].'
11387 lgm 189
 
190
						Access modifier is Public.
191
 
192
						Error is ====> '.$this->calls[$key]["error"].'';
193
						$this->write_log_send_mail('error',$msg);
10802 lgm 194
        				redirect(base_url().'error_page/index');
195
        				exit();
196
					}
10800 lgm 197
				}
10756 lgm 198
				curl_multi_remove_handle($this->curl_parent,$this->calls[$key]["curl"]);
10582 lgm 199
			}
200
 
201
			curl_multi_close($this->curl_parent);
202
		}
11103 lgm 203
		//print_r($this->calls);
10582 lgm 204
		return $this->calls;
205
	}
206
 
207
	function debug()
208
	{
209
		echo "<h2>mcurl debug</h2>";
210
		foreach ($this->calls as $call)
211
		{
212
			echo '<p>url: <b>'.$call["url"].'</b></p>';
213
			if (!is_null($call["error"]))
214
			{
215
				echo '<p style="color:red;">error: <b>'.$call["error"].'</b></p>';
216
			}
217
			echo '<textarea cols="100" rows="10">'.htmlentities($call["response"])."</textarea><hr>";
218
		}
219
	}
220
 
11387 lgm 221
	function write_log_send_mail($level = 'error', $msg, $php_error = FALSE){ 
222
	 	$params = $this->_ci->config->item('email_params'); 
223
		$this->_ci->load->library('email',$params);
224
		$this->_ci->email->set_newline("\r\n");
225
	 	$this->_ci->email->from('mobile@letsgomo.com', 'NO-REPLY');
226
	 	$list = $this->_ci->config->item('email_list');
227
		$this->_ci->email->to($list);
228
		$this->_ci->email->cc('yashmeet@letsgomo.com');		
229
		$this->_ci->email->subject('The API failed on '.date('m/d/Y'));		
230
		$this->_ci->email->message('The API failed at '.date('m/d/Y h:i:s a', time()).' ------> '.$msg);
231
		//send the email 	
232
		$this->_ci->email->send();
233
	}
234
 
10582 lgm 235
}
236
 
237
/* End of file mcurl.php */
12999 anikendra 238
/* Location: ./application/libraries/mcurl.php */