Subversion Repositories SmartDukaan

Rev

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