Subversion Repositories SmartDukaan

Rev

Rev 12694 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
12694 anikendra 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
	{
26
 
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
	{
13062 anikendra 47
		$authorized=$this->_ci->session->userdata('authorized');
48
		if(isset($authorized['isPrivateDealUser']) && !empty($authorized['isPrivateDealUser'])) {
49
			$params['privateDealUser'] = 'true';
50
		}
12694 anikendra 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);
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);
127
		}
128
		curl_setopt_array($this->calls[$key]["curl"], $options);
129
		curl_multi_add_handle($this->curl_parent,$this->calls[$key]["curl"]);		 
130
	}
131
 
132
	// run the calls in the curl requests in $this->calls
133
	function execute()
134
	{
135
		if (count($this->calls) <= 0)
136
			return False;
137
		if (count($this->calls))
138
		{
139
			// kick off the requests
140
			do
141
			{
142
				//print_r($this->calls);
143
				$multi_exec_handle = curl_multi_exec($this->curl_parent,$active);
144
			} while ($active>0);
145
 
146
			// after all requests finish, set errors and repsonses in $this->calls
147
			foreach ($this->calls as $key => $call)
148
			{
149
				$error = curl_error($this->calls[$key]["curl"]);
150
				if (!empty($error))
151
				{
152
					if($key != 'tracking' && $key != 'recommended_accessories'){
153
					$this->calls[$key]["error"] = $error;
154
					$url = 'http://www.saholic.com/'.uri_string();
155
					$this->_ci->session->set_userdata('errorurl',$url);
156
					//$errmsg ='<h3>OH SNAP!!!! :</h3><p>Something is not right. <br/><h1>But Relax</h1> <br/>We are working hard on it. </p>';
157
					$msg = '
158
					API for '.$key.' is not working.
159
 
160
					url of API Failed ===> '.$this->calls[$key]['url'].'
161
					parameters are ===> '.$call['params'].'
162
 
163
					Access modifier is Public.
164
 
165
					Error is ====> '.$this->calls[$key]["error"].'';
166
					$this->write_log_send_mail('error',$msg);
167
					//$this->session->set_flashdata('errormsg',$errmsg);
168
					redirect(base_url().'error_page/index');
169
					exit();
170
					}
171
				}
172
				$this->calls[$key]["response"] = curl_multi_getcontent($this->calls[$key]["curl"]);
173
				$http_status = curl_getinfo($this->calls[$key]["curl"], CURLINFO_HTTP_CODE);
174
				if($key != 'tracking' && $key != 'recommended_accessories'){
175
					if($http_status != 200) {
176
						$url = 'http://www.saholic.com/'.uri_string();
177
						$this->_ci->session->set_userdata('errorurl',$url);
178
						$msg = '
179
						API for '.$key.' is not working.
180
 
181
						url of API Failed ===> '.$this->calls[$key]['url'].'
182
						parameters are ===> '.$call['params'].'
183
 
184
						Access modifier is Public.
185
 
186
						Error is ====> '.$this->calls[$key]["error"].'';
187
						$this->write_log_send_mail('error',$msg);
188
        				redirect(base_url().'error_page/index');
189
        				exit();
190
					}
191
				}
192
				curl_multi_remove_handle($this->curl_parent,$this->calls[$key]["curl"]);
193
			}
194
 
195
			curl_multi_close($this->curl_parent);
196
		}
197
		//print_r($this->calls);
198
		return $this->calls;
199
	}
200
 
201
	function debug()
202
	{
203
		echo "<h2>mcurl debug</h2>";
204
		foreach ($this->calls as $call)
205
		{
206
			echo '<p>url: <b>'.$call["url"].'</b></p>';
207
			if (!is_null($call["error"]))
208
			{
209
				echo '<p style="color:red;">error: <b>'.$call["error"].'</b></p>';
210
			}
211
			echo '<textarea cols="100" rows="10">'.htmlentities($call["response"])."</textarea><hr>";
212
		}
213
	}
214
 
215
	function write_log_send_mail($level = 'error', $msg, $php_error = FALSE){ 
216
	 	$params = $this->_ci->config->item('email_params'); 
217
		$this->_ci->load->library('email',$params);
218
		$this->_ci->email->set_newline("\r\n");
219
	 	$this->_ci->email->from('mobile@letsgomo.com', 'NO-REPLY');
220
	 	$list = $this->_ci->config->item('email_list');
221
		$this->_ci->email->to($list);
222
		$this->_ci->email->cc('yashmeet@letsgomo.com');		
223
		$this->_ci->email->subject('The API failed on '.date('m/d/Y'));		
224
		$this->_ci->email->message('The API failed at '.date('m/d/Y h:i:s a', time()).' ------> '.$msg);
225
		//send the email 	
226
		$this->_ci->email->send();
227
	}
228
 
229
}
230
 
231
/* End of file mcurl.php */
232
/* Location: ./application/libraries/mcurl.php */