Subversion Repositories SmartDukaan

Rev

Rev 13061 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
**/

/**
 * CodeIgniter MCurl Class
 *
 * Work with remote servers via multi-cURL much easier than using the native PHP bindings.
 *
 * @package                     CodeIgniter
 * @subpackage          Libraries
 * @category            Libraries
 * @author                      Chad Hutchins
 * @link                        http://github.com/chadhutchins/codeigniter-mcurl
 */
 
class Mcurl {

        private $_ci;                           // CodeIgniter instance
        private $calls = array();       // multidimensional array that holds individual calls and data
        private $curl_parent;           // the curl multi handle resource

        function __construct()
        {

                $this->_ci = & get_instance();
                log_message('debug', 'Mcurl Class Initialized');
                if (!$this->is_enabled())
                {
                        log_message('error', 'Mcurl Class - PHP was not built with cURL enabled. Rebuild PHP with --with-curl to use cURL.');
                }
                else 
                {
                        $this->curl_parent = curl_multi_init();
                }
        }

        // check to see if necessary function exists
        function is_enabled()
        {
                return function_exists('curl_multi_init');
        }
        // method to add curl requests to the multi request queue
        function add_call($key=null, $method, $url, $params = array(), $options = array())
        {
                $authorized=$this->_ci->session->userdata('authorized');
                if(isset($authorized['Id']) && !empty($authorized['Id'])){
                        $params['userId'] = $authorized['Id'];
                }
                if(isset($authorized['isPrivateDealUser']) && !empty($authorized['isPrivateDealUser'])) {
                        $params['privateDealUser'] = 'true';
                }
                if (is_null($key))
                {
                        $key = count($this->calls);
                }
                
                // check to see if the multi handle has been closed
                // init the multi handle again
                $resource_type = get_resource_type($this->curl_parent);
                if(!$resource_type || $resource_type == 'Unknown')
                {
                        $this->calls = array();
                        $this->curl_parent = curl_multi_init();
                }

                $this->calls [$key]= array(
                        "method" => $method,
                        "url" => $url,
                        "params" => $params,
                        "options" => $options,
                        "curl" => null,
                        "response" => null,
                        "error" => null
                );

                $this->calls[$key]["curl"] = curl_init();

                $newdata =$params;
                // If its an array (instead of a query string) then format it correctly
                if (is_array($params))
                {
                        $params = http_build_query($params, NULL, '&');
                }

                $method = strtoupper($method);
                
                // only supports get/post requests
                // set some special curl opts for each type of request
                switch ($method)
                {                       
                        case "POST":
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_URL, $url);
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_POST, TRUE);
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_POSTFIELDS, $params);
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_SSL_VERIFYPEER, false);
                                break;

                        case "GET":
                                if (strpos($url,'?') !== false) {
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_URL, $url."&".$params);
                        }
                        else{
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_URL, $url."?".$params);
                        }
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_SSL_VERIFYPEER, false);
                                break;

                        default:
                                log_message('error', 'Mcurl Class - Provided http method is not supported. Only POST and GET are currently supported.');
                                break;
                }
                curl_setopt($this->calls[$key]["curl"], CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($this->calls[$key]["curl"], CURLOPT_FOLLOWLOCATION, TRUE);
                if(($key == 'tracking') || ($key == 'signup') || ($key == 'orderconfirmation_process')){
                        $cookiesStringToPass="";
                        foreach($_COOKIE as $cookie) {
                                if ($cookiesStringToPass) {
                                $cookiesStringToPass  .= ';';
                        }
                        if(is_object(json_decode($cookie))){
                                $cookieInfo = json_decode($cookie);
                                foreach ($cookieInfo as $info) {
                                        $cookiesStringToPass .= $info->name . '=' . addslashes($info->value);
                                }
                        }
                        }
                        curl_setopt($this->calls[$key]["curl"], CURLOPT_COOKIE, $cookiesStringToPass);
                        foreach (getallheaders() as $name => $value) {
                            if($name == "X-Forwarded-For"){
                                $headers = array('X-Forwarded-For : '.$value);
                                curl_setopt($this->calls[$key]["curl"], CURLOPT_HTTPHEADER, $headers);
                            }
                        }
                }
                curl_setopt_array($this->calls[$key]["curl"], $options);
                curl_multi_add_handle($this->curl_parent,$this->calls[$key]["curl"]);            
        }

        // run the calls in the curl requests in $this->calls
        function execute()
        {
                if (count($this->calls) <= 0)
                        return False;
                if (count($this->calls))
                {
                        // kick off the requests
                        do
                        {
                                //print_r($this->calls);
                                $multi_exec_handle = curl_multi_exec($this->curl_parent,$active);
                        } while ($active>0);

                        // after all requests finish, set errors and repsonses in $this->calls
                        foreach ($this->calls as $key => $call)
                        {
                                $error = curl_error($this->calls[$key]["curl"]);
                                if (!empty($error))
                                {
                                        if($key != 'tracking' && $key != 'recommended_accessories'){
                                        $this->calls[$key]["error"] = $error;
                                        $url = 'http://www.saholic.com/'.uri_string();
                                        $this->_ci->session->set_userdata('errorurl',$url);
                                        //$errmsg ='<h3>OH SNAP!!!! :</h3><p>Something is not right. <br/><h1>But Relax</h1> <br/>We are working hard on it. </p>';
                                        $msg = '
                                        API for '.$key.' is not working.
                                        
                                        url of API Failed ===> '.$this->calls[$key]['url'].'
                                        parameters are ===> '.$call['params'].'

                                        Access modifier is Public.
                                        
                                        Error is ====> '.$this->calls[$key]["error"].'';
                                        $this->write_log_send_mail('error',$msg);
                                        //$this->session->set_flashdata('errormsg',$errmsg);
                                        redirect(base_url().'error_page/index');
                                        exit();
                                        }
                                }
                                $this->calls[$key]["response"] = curl_multi_getcontent($this->calls[$key]["curl"]);
                                $http_status = curl_getinfo($this->calls[$key]["curl"], CURLINFO_HTTP_CODE);
                                if($key != 'tracking' && $key != 'recommended_accessories'){
                                        if($http_status != 200) {
                                                $url = 'http://www.saholic.com/'.uri_string();
                                                $this->_ci->session->set_userdata('errorurl',$url);
                                                $msg = '
                                                API for '.$key.' is not working.
                                                
                                                url of API Failed ===> '.$this->calls[$key]['url'].'
                                                parameters are ===> '.$call['params'].'
                                                
                                                Access modifier is Public.
                                                
                                                Error is ====> '.$this->calls[$key]["error"].'';
                                                $this->write_log_send_mail('error',$msg);
                                        redirect(base_url().'error_page/index');
                                        exit();
                                        }
                                }
                                curl_multi_remove_handle($this->curl_parent,$this->calls[$key]["curl"]);
                        }

                        curl_multi_close($this->curl_parent);
                }
                //print_r($this->calls);
                return $this->calls;
        }
        
        function debug()
        {
                echo "<h2>mcurl debug</h2>";
                foreach ($this->calls as $call)
                {
                        echo '<p>url: <b>'.$call["url"].'</b></p>';
                        if (!is_null($call["error"]))
                        {
                                echo '<p style="color:red;">error: <b>'.$call["error"].'</b></p>';
                        }
                        echo '<textarea cols="100" rows="10">'.htmlentities($call["response"])."</textarea><hr>";
                }
        }

        function write_log_send_mail($level = 'error', $msg, $php_error = FALSE){ 
                $params = $this->_ci->config->item('email_params'); 
                $this->_ci->load->library('email',$params);
                $this->_ci->email->set_newline("\r\n");
                $this->_ci->email->from('mobile@letsgomo.com', 'NO-REPLY');
                $list = $this->_ci->config->item('email_list');
                $this->_ci->email->to($list);
                $this->_ci->email->cc('yashmeet@letsgomo.com');         
                $this->_ci->email->subject('The API failed on '.date('m/d/Y'));         
                $this->_ci->email->message('The API failed at '.date('m/d/Y h:i:s a', time()).' ------> '.$msg);
                //send the email        
                $this->_ci->email->send();
        }

}

/* End of file mcurl.php */
/* Location: ./application/libraries/mcurl.php */