Subversion Repositories SmartDukaan

Rev

Rev 20497 | Rev 20860 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

        public $limit;
        public $apihost;
        public $acls;

        public $components = array(
                'Session','Resize','Cookie',
                'Auth' => array(
                        'loginAction' => array('controller' => 'users', 'action' => 'login')
//                      'allowedActions' => array('index', 'view', 'display')
                )                       
        );

        var $helpers = array('Session', 'Form', 'Html');
        var $keywords = array('instagram followers','instagram button','instagram follow back','instagram tool','instagram automation','free istagram followers','instagram stats','instagram follow button');

        function beforeFilter() {
                $this->Auth->autoRedirect = false;
                if($this->request->is('ajax')){
                        $this->Auth->allow($this->params->params['action']);
                }
                //Set config settings according to domain
                // get host name from URL
                preg_match('@^(?:http://)?([^/]+)@i',$_SERVER['HTTP_HOST'], $matches);
                $host = $matches[1];
                switch($host){                  
                        case 'localdtr':
                                Configure::load('dev');
                                break;
                        case 'staging.profittill.com':
                        case 'www.staging.profittill.com':
                                Configure::load('staging');
                                break;
                        default:
                        case 'www.profittill.com':
                        case 'profittill.com':
                        case 'api.profittill.com':
                                Configure::load('live');
                                break;
                }

                $facebookConfig = Configure::read("Facebook");          
                $categories = Configure::read('Categories');
//              $allowedController = Configure::read('allowcontroller');
                
//              if($this->params->params['controller'] == 'categories' || $this->params->params['controller'] == 'orders' 
//      ||  $this->params->params['controller'] == 'store_products' ||  $this->params->params['controller'] == 'brands')
//              if(in_array($this->params->params['controller'] , $allowedController))          
//              {
                        //Check access for apps tab     

                        $userId = $this->isAuthorized();
                        if(!$userId){
                                $userId = $this->request->query('user_id');
                                if(isset($userId) && !empty($userId)) {
                                        $this->loadModel('User');
                                        $dbuser = $this->User->findById($userId);
                                        $this->Auth->login($dbuser['User']);
                                }else
                                        return;
                        }
                        $cachekey = 'appacls-'.$userId;                 
                        $access = Cache::read($cachekey,'day');
                        if(empty($access)) {
                                $this->loadModel('Appacl');
                                $this->Appacl->recursive = -1;
                                $conditions = array('user_id'=>$userId);
                                $access = $this->Appacl->find('first',array('conditions'=>$conditions));                
                                if(empty($access) || $access['Appacl']['access']==0){
                                        unset($categories[2]);
                                        $this->set('noappcashback',true);
                                }               
                                Cache::write($cachekey,$access,'day');
                        }
//              }
                //Facebook configuration
                $this->set('fbappid', $facebookConfig['fbappid']);
                $this->set('apihost', Configure::read('apihost'));
                $sessionState = $this->Session->read('state');
                if(!isset($sessionState)){
                        $this->Session->write('state' , md5(uniqid(rand(), TRUE))); // CSRF protection
                }
                $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
                   . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/') . "&state="
                   . $this->Session->read('state').'&scope=publish_stream,email,user_birthday,publish_actions,user_location';
                $this->set('dialog_url', $dialog_url);
                $this->set('description','Why spend money when you can get something for free');
                $this->set('categories',$categories);
                if(isset($this->params['admin'])) {
                        $this->layout = 'admin';
                }       
                $this->apihost = Configure::read('pythonapihost');
                $this->limit = Configure::read('dealsperpage'); 
                $staticVersion = Configure::read('staticversion');
                $this->set('staticversion',$staticVersion);
                $this->set('requiremobileverification',Configure::read('requiremobileverification'));                   

                //acl
                $cachekey = 'acls';
                $acls = Cache::read($cachekey,'month');
                if(empty($acls)) {
                        $acls = array();
                        $this->loadModel('Acl');
                        $result = $this->Acl->find('all');
                        foreach ($result as $key => $value) {
                                if($value['Acl']['access']) {
                                        $acls[$value['Acl']['group_id']]['allowed'][] = $value['Acl']['action'];
                                }else{
                                        $acls[$value['Acl']['group_id']]['disallowed'][] = $value['Acl']['action'];
                                }                               
                        }
                        Cache::write($cachekey,$acls,'month');
                }
                $this->acls = $acls;
                $this->set('acls',$acls);
                
                if(isset($_COOKIE['txn_comp']) && $_COOKIE['txn_comp']=='no'){
                        $suserId = base64_decode($_COOKIE['s_id']);
                        $scartId = base64_decode($_COOKIE['s_cart']);
                        $semailId = base64_decode($_COOKIE['s_email']);
                        
                        $pincode = 0;
                        
                        if($pincode==0 && isset($_COOKIE['s_pincode'])){
                                $pincode = base64_decode($_COOKIE['s_pincode']);
                        }
                        $cartItems = array();
                        $postData = array(
                                        'cartItems'     =>      $cartItems
                                        );
                                        
                        $params = array(
                                        'cartMap' => urlencode(json_encode($postData)));
                        
                        $url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
                        if($pincode!='0'){
                                $url = $url.'&pinCode='.$pincode;
                        }
                        $localCartHistory = $this->post_cartinfo_request($url,$params);
                        if(isset($localCartHistory['response']) && $localCartHistory['response']=='error'){
                                setcookie('txn_comp', 'no', -1, '/');
                        }elseif(isset($localCartHistory['cartItems'])&& count($localCartHistory['cartItems'])==0) {
                                setcookie('txn_comp', 'yes', -1, '/');
                        }else{
                                $this->set('localCartHistory',$localCartHistory);
                        }
                        
                }
                if($this->checkToken($userId)==1){
                        ob_start();
                        if(!@include("category.php")) {
                                $this->set('outputcategory','');
                        } else {
                                $this->set('outputcategory', ob_get_clean());
                        }
                }

    }
        
        function checkAcl() {           
        if(!in_array($this->here,$this->acls[$this->Session->read('Auth.User.group_id')]['allowed'])){
                $this->Session->setFlash(__('You are not authorized to access this page.'));
                return $this->redirect(array('controller'=>'administration','action' => 'dashboard','admin'=>false));
        }
    }

    function isAuthorized() {
        return $this->Auth->user('id');
    }

    function isFbAuthorized() {
        return $this->Session->read('facebook_id');
    }

    function afterFilter() {
                $result['ucadcode'] = $this->ucadcode;
    }

    function beforeRender() {   
        $logged_user = $this->Auth->user();
        $this->set('logged_user', $logged_user);        
        $this->set('base_url', 'http://' . $_SERVER['SERVER_NAME'] . Router::url('/'));
    }

    function checkMobileNumber() {
        $logged_user = $this->Auth->user();
        if(empty($logged_user['mobile_verified']) && $this->params['controller'] !='users') {
                        $skipmobileverification = $this->Session->read('skipmobileverification');
                        if(!isset($skipmobileverification) || empty($skipmobileverification)) {
                                $this->redirect('/users/verifymobile');
                        }
                }
    }

    function checkToken($userId = null) {
        $headers =  $this->getallheaders();
        $this->log(print_r($headers,1),'headers');
        $token = $_COOKIE['token'];
        $checkToken = $_COOKIE['walletAuthentication'];
        $this->log("Token : $token",'headers');
        $this->log("CheckToken : $checkToken",'headers');
        if(isset($checkToken) && !empty($checkToken) && isset($token) && !empty($token)) {
                $this->loadModel('SocialProfile');
                $options = array('conditions'=>array('access_token'=>$token),'fields'=>array('user_id'),'recursive'=>-1);
                $user = $this->SocialProfile->find('first',$options);
                $this->log($userId." ".print_r($user['SocialProfile'],1),'headers');
                /*if(!$userId){
                        $userId = $this->request->query('user_id');
                }                */
                if(isset($userId) && !empty($userId)){
                    if($userId == $user['SocialProfile']['user_id']){
                        $this->log("User authenticated",'headers');
                        return 1;//success
                    } else{
                        // token mismatch, so maybe hack attempt
                        $this->log("Mismatch hence user not authenticated",'headers');
                        return 0;//fail
                    }
                } else {
                        // userId is not sent so maybe hack attempt
                        $this->log("Id not sent hence user not authenticated",'headers');
                        return 0;//fail
                }
        } else {    
                $this->log("Old User hence pass",'headers');            
            return -1;//token not set in cookie
        }
    }

    function getallheaders() { 
           $headers = ''; 
       foreach ($_SERVER as $name => $value) 
       { 
           if (substr($name, 0, 5) == 'HTTP_') 
           { 
               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; 
           } 
       } 
       return $headers; 
    } 

    public function getDealsApiUrl($page=1,$userId = null,$categoryId=0,$sort=null,$direction=null,$filter=null,$brands=null,$subcategories=null){
        $this->log('categoryId '.$categoryId,'api');
        $this->log('page '.$page,'api');
        $offset = ($page - 1) * $this->limit;

        if(isset($sort) && !empty($sort) && $sort!=-1){
                $url = $this->apihost.'deals/'.$userId.'?categoryId='.$categoryId.'&sort='.$sort.'&direction='.$direction.'&limit='.$this->limit.'&offset='.$offset;
        }else{
                $url = $this->apihost.'deals/'.$userId.'?categoryId='.$categoryId.'&limit='.$this->limit.'&offset='.$offset;
        }    

        $get_url = "'".$_SERVER['REQUEST_URI']."'";
        $urlArray = explode('=',$_SERVER['REQUEST_URI']);
                $last = $urlArray[sizeof($urlArray)-1];

        if(!isset($filter) && empty($filter)){
                // $get_url = "'".$_SERVER['REQUEST_URI']."'";
                if (strpos($get_url,'filter=brand&brands') !== false)
                {
                        $url .= "&filterData=brandFilter:".$last;
                        // echo $url;
                }
                if (strpos($get_url,'filter=subcategory&subcategories') !== false)
                {
                        $url .= "&filterData=subCategoryFilter:".$last;
                        // echo "url",$url;
                        
                }

        }

        

        if(isset($filter) && !empty($filter)){
                if(isset($brands) && !empty($brands)){
                        $url .= "&filterData=brandFilter:".$brands;
                        if(isset($subcategories) && !empty($subcategories)){
                                $url .= "|subCategoryFilter:".$subcategories;
                        }
                }else{
                        if(isset($subcategories) && !empty($subcategories)){
                                $url .= "&filterData=subCategoryFilter:".$subcategories;
                        }
                }
        }
        // print_r($url);
        return $url;
    }

        function make_request($url,$fields,$format='json'){
                $this->log("[url] $url",'api');
                $this->log("[fields] ".print_r($fields,1),'api');
                $fields_string = '';
                //open connection
                $ch = curl_init();
                //set the url, number of POST vars, POST data
                curl_setopt($ch,CURLOPT_URL, $url);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER , true);
                if(!empty($fields)) {
                        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
                            'Content-Type: application/json',                                                                                
                            // 'Content-Length: ' . sizeof($fields))                                                                       
                            'Content-Length: ' . strlen($fields))                                                                       
                        );   
                }
                //execute post
                $result = curl_exec($ch);
                $this->log("[response] ".print_r($result,1),'api');
                //close connection
                curl_close($ch);
                switch($format){
                        case 'json':
                        $response = json_decode($result,1);
                        break;
                }
                return $response;       
        }
        
        function post_cartinfo_request($url,$fields,$format='json'){
                $this->log("[url] $url",'api');
                //$this->log("[fields] ".print_r($fields,1),'api');
                $fields_string = '';
                //open connection
                $ch = curl_init();
                //execute post
                foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
                rtrim($fields_string, '&');
                //set the url, number of POST vars, POST data
                curl_setopt($ch,CURLOPT_URL, $url);
                curl_setopt($ch,CURLOPT_POST, count($fields));
                curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
                $result = curl_exec($ch);
                //close connection
                curl_close($ch);
                switch($format){
                        case 'json':
                        $response = json_decode($result,1);
                        break;
                }
                return $response;       
        }
        
        function post_request($url,$fields,$format='json'){
                $this->log("[url] $url",'api');
                $this->log("[fields] ".print_r($fields,1),'api');
                $fields_string = '';
                //open connection
                $ch = curl_init();
                //execute post
                foreach($fields as $key=>$value) { $fields_string .= $key.'='.urlencode($value).'&'; }
                rtrim($fields_string, '&');
                //set the url, number of POST vars, POST data
                curl_setopt($ch,CURLOPT_URL, $url);
                curl_setopt($ch,CURLOPT_POST, count($fields));
                curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
                $result = curl_exec($ch);
                $this->log("[response] ".print_r($result,1),'api');
                //close connection
                curl_close($ch);
                switch($format){
                        case 'json':
                        $response = json_decode($result,1);
                        break;
                }
                return $response;       
        }

        public function get_solr_result($q,$page) {
                $dealsperpage = Configure::read('searchresultsperpage');
                $offset = ($page - 1)*$dealsperpage;
                $cond = "$q";
                $sort = "store desc";

                $params = array(
                        'conditions' =>array(
                        'solr_query' => $cond
                ),
                        //'order' => $sort,
                        'offset' => $offset,
                        'limit' => $dealsperpage
                );
                $this->loadModel('Solr');               
                $solroutput = $this->Solr->find('all', $params);
                $result = array();
                if(sizeof($solroutput)<$dealsperpage){
                        $hasMore = false;
                }else{
                        $hasMore = true;
                }
                if(!empty($solroutput['Solr'])) {                       
                        $skuMap = array();
                        foreach ($solroutput['Solr'] as $key => $value) {
                                // if(!$value['in_stock'])continue;
                                $skuMap[$value['id']] = $value;
                                $result[$value['skuBundleId']][$value['id']] = $value['available_price'];
                        }       
                        if(!empty($result)) {
                                foreach ($result as $key => $value) {                                   
                                        asort($value);
                                        $lowestPriceSku = key($value);
                                        $result[$key] = $skuMap[$lowestPriceSku];
                                }
                        }
                }               
                $result['hasMore'] = $hasMore;
                return $result;
        }

        public function admin_update(){
                $this->response->type('json');
                $this->layout = 'ajax';
                $data[$this->request->data['id']] = $this->request->data['value'];
                $data['oid'] = $this->request->data['oid'];
                $id = $this->request->data['id'];
                $multi = $this->request->data['multi'];
                if($this->modelClass == 'Exceptionalskudiscount') {
                        $data['class'] = 'SkuDiscountInfo';     
                }elseif($this->modelClass == 'Skuscheme'){
                        if($id == 'dp' || $id == 'showDp'){
                                $data['class'] = 'SkuDealerPrices';
                        }else{
                                $data['class'] = 'SkuSchemeDetails';
                        }
                }elseif($this->modelClass == 'Exceptionalnlc'){
                        $data['class'] = 'ExceptionalNlc';
                }elseif($this->modelClass == 'ManualDeal' && ($id == 'dealPoints' || $id == 'dealThresholdPrice')){
                        $data['class'] = 'DealPoints';
                }
                else{
                        $data['class'] = $this->modelClass;
                }               
                $data_string = json_encode($data,JSON_NUMERIC_CHECK);           
                $ch = curl_init();
                $url = $this->apihost.'Catalog/updateCollection';
                if(isset($multi) && $multi==1){
                        $url .= "/?multi=1";
                }               
                $this->log("[url] $url",'api');
                $this->log("[fields] ".print_r($data_string,1),'api');
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // note the PUT here

                curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
                curl_setopt($ch, CURLOPT_HEADER, true);

                curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
                    'Content-Type: application/json',                                                                                
                    'Content-Length: ' . strlen($data_string)                                                                       
                ));       

                // execute the request

                $output = curl_exec($ch);
                $result = $this->request->data['value'];
                $this->log("[response] ".print_r($output,1),'api');
                curl_close($ch);
                $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

        public function remove($id,$class){
                $data['oid'] = $id;
                $data['class'] = $class;
                
                $data_string = json_encode($data,JSON_NUMERIC_CHECK);
                $ch = curl_init();
                $url = $this->apihost.'Catalog/deleteDocument';
                $this->log("[url] $url",'api');
                $this->log("[fields] ".print_r($data_string,1),'api');
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // note the PUT here

                curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
                // curl_setopt($ch, CURLOPT_HEADER, true);

                curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
                    'Content-Type: application/json',                                                                                
                    'Content-Length: ' . strlen($data_string)                                                                       
                ));       

                // execute the request

                $output = curl_exec($ch);
                // $result = $this->request->data['value'];
                $this->log("[response] ".print_r($output,1),'api');
                curl_close($ch);
                // $this->set(array(
                    // 'result' => $result,
                    // '_serialize' => array('result')
                // ));
                // $this->render('/Elements/json');
                $result = json_decode($output,1);
                return $result;
        }

        function getAutoLoginUrl($userId,$next) {
                $saholicoffline = Configure::read('saholicoffline');
                if($saholicoffline) {
                        $url = "/abouts/saholicoffline";
                        return $url;
                }
                $this->loadModel('User');
                $this->User->Behaviors->attach('Containable');
                $options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
                $user = $this->User->find('first',$options);
                $this->log("user_accounts ".print_r($user,1),'headers');
                $data = array('email'=>$user['User']['email'],'Id'=>$user['UserAccount'][0]['account_key'],'cartId' => $user['UserAccount'][1]['account_key'],'isPrivateDealUser'=>1,'next'=>$next);
                $data = '?data='.base64_encode(serialize($data));
                $token = '&token='.md5(Configure::read('saholicapikey').'|'.$user['UserAccount'][0]['account_key']);            
                $url = Configure::read('saholicapihost')."login!authorizeProfitMandiUser?userId=".$user['UserAccount'][0]['account_key']."&source=ProfitMandi";
                $result = $this->make_request($url,null);
                $this->log(print_r($result,1),'headers');
                if(!empty($result['tokenString'])){
                        $token = '&token='.$result['tokenString'];
                        return Configure::read('saholicauthurl').$data.$token.'&v=2';
                }
                return Configure::read('saholicauthurl').$data.$token;
        }

        function getBigUtsavAutoLoginUrl($userId,$next) {
                $saholicoffline = Configure::read('saholicoffline');
                if($saholicoffline) {
                        $url = "/abouts/saholicoffline";
                        return $url;
                }
                $this->loadModel('User');
                $this->User->Behaviors->attach('Containable');
                $options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
                $user = $this->User->find('first',$options);
                $this->log("user_accounts ".print_r($user,1),'headers');
                $data = array('email'=>$user['User']['email'],'Id'=>$user['UserAccount'][0]['account_key'],'cartId' => $user['UserAccount'][1]['account_key'],'isPrivateDealUser'=>1,'next'=>$next);
                $data = '?data='.base64_encode(serialize($data));
                $token = '&token='.md5(Configure::read('saholicapikey').'|'.$user['UserAccount'][0]['account_key']);            
                $url = Configure::read('saholicapihost')."login!authorizeProfitMandiUser?userId=".$user['UserAccount'][0]['account_key']."&source=ProfitMandi";
                $result = $this->make_request($url,null);
                $this->log(print_r($result,1),'headers');
                if(!empty($result['tokenString'])){
                        $token = '&token='.$result['tokenString'];
                        return Configure::read('bigutsavauthurl').$data.$token.'&v=2';
                }
                return Configure::read('bigutsavauthurl').$data.$token;
        }

        function createUploadDirectory($modelClass) {
        //Create directory
        if (!is_dir(WWW_ROOT.'uploads'.DS.$modelClass)) {            
            $this->log("making directory for $modelClass". WWW_ROOT.DS.'uploads'.DS.$modelClass);
            mkdir(WWW_ROOT.'uploads'.DS.$modelClass,0777);
        }
        if (!is_dir(WWW_ROOT.'uploads'.DS.$modelClass)) {
            $this->log("failed to create directory for $modelClass");
            return false; 
        } else {
            return true;
        }
    }

    public function upload() {
        $result['status'] = 0; 
        $result['success'] = false;
        $result['message'] = __('Unable to upload');

        App::import('Vendor','qqFileUploader',array('file' =>'qqFileUploader.php'));

        $uploader = new qqFileUploader();

        // Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
        $uploader->allowedExtensions = array('jpeg','png','jpg','gif','bmp');

        // Specify max file size in bytes.
        $uploader->sizeLimit = 10 * 1024 * 1024;

        // Specify the input name set in the javascript.
        $uploader->inputName = 'qqfile';

        // If you want to use resume feature for uploader, specify the folder to save parts.
        $uploader->chunksFolder = 'chunks';

        // $min_width = isset($this->request->data['minwidth']) ? $this->request->data['minwidth'] : 0; 
        // $min_height = isset($this->request->data['minheight']) ? $this->request->data['minheight'] : 0; 
        $modelClass = $this->modelClass; 

        $this->log($this->request);
        $folderName = Inflector::pluralize(strtolower($modelClass));

        if (!$this->createUploadDirectory($folderName)) {
            $result['message'] = 'Failed to create directory :'.$modelClass.
            '.  Sorry we are having trouble.  Please try again, or email help@profittill.com';
        } else {
            // To save the upload with a specified name, set the second parameter
            $result = $uploader->handleUpload('uploads'.DS.$folderName.DS, $uploader->getName());
            if($result){
                //Resize and create thumbnail
                $inFile = WWW_ROOT.'uploads'.DS.$folderName.DS. $uploader->getName();

                $largeOutFile = WWW_ROOT.'uploads'.DS.$folderName.DS.'large-'.basename($inFile);
                $this->resizeImage($inFile,$largeOutFile,800,800);
                
                $outFile = WWW_ROOT.'uploads'.DS.$folderName.DS.'small-'.basename($inFile);
                $this->resizeImage($inFile,$outFile,200,200);

                $newUrl = '/uploads/'.$folderName.'/'.basename($inFile);
                // To return a name used for uploaded file you can use the following line.
                $result['uploadName'] = $newUrl;
                
                $result['status'] = 1;
                $result['success'] = true;
                // $result['filesize'] = $filesize;
                $result['message'] = __('Uploaded');
            }
        }
        $this->log($result);
        return new CakeResponse(array('body' => json_encode($result)));
    }

    function cropImage ($url, $height, $width, $x1, $x2, $y1, $y2) {
        ini_set('memory_limit', '2G');
        $result['status'] = 0; 
        $result['message'] = __('Unable to crop');

        $image_type = substr($url, strrpos($url, '.', -1)); 
        $filepath = WWW_ROOT.substr($url, strlen(FULL_BASE_URL)+1);
        $croppedfile = substr($filepath, 0, strrpos($filepath, '/', -1)).
            '/C_'.substr($filepath, strrpos($filepath, '/', -1)+1);
        
        // Create image instances
        $dest = imagecreatetruecolor($x2,$y2);

        switch ($image_type) {
            case '.jpg':
            case '.jpeg':
            case '.JPEG':
            case '.JPG':
                $src = imagecreatefromjpeg($filepath);
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
                imagejpeg($dest, $croppedfile);
                $ext = '.jpg';
                break;
            case '.gif':
                $src = imagecreatefromgif($filepath);
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
                imagegif($dest, $croppedfile);
                $ext = '.gif';
                break;
            case '.png':
                $src = imagecreatefrompng($filepath);
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
                imagepng($dest, $croppedfile);
                $ext = '.png';
                break;
            default: 
                $result['message'] = __('Unsupported image format.');   
                return $result;
        }
        $result['status'] = 1; 
        $result['message'] = __('Cropped');
        $result['data'] = substr($url, 0, strrpos($url, '/', -1)).'/C_'.substr($url, strrpos($url, '/', -1)+1);
        return $result;
    }

    function resizeImage ($inFile, $outFile, $w, $h) {
        $image = $this->Resize;
        $image->load($inFile);                       
        $image->crop($w,$h);
        $image->save($outFile);
    }

    public function crop() {
        $url = $this->request->data['file_url'];
        $height = $this->request->data['h']; 
        $width = $this->request->data['w']; 
        $x1 = $this->request->data['x'];
        $x2 = $this->request->data['x2'];
        $y1 = $this->request->data['y'];
        $y2 = $this->request->data['y2'];

        $result = $this->cropImage($url, $height, $width, $x1, $x2, $y1, $y2);

        $this->set('result', $result);
        $this->set('_serialize', array('result'));
    }

    public function generateMultiUrl($url,&$data){
        if(!empty($data['multi']) && $data['multi']==1){
                $url .= '/?multi=1';                    
        }
        unset($data['multi']);
        return $url;
    }

    public function markUserActivated($id){
        $url = Configure::read('pythonapihost').'retailerActivated/'.$id;
        $this->make_request($url,null);
        $this->loadModel('User');
        $sql = "UPDATE users SET activation_time = NOW() WHERE id = $id AND activation_time IS NULL";
        $this->User->query($sql);
        $this->loadModel('Appacl');
        $data = array('user_id'=>$id,'access'=>1);
                $count = $this->Appacl->find('count',array('conditions'=> $data));
                if($count==0){
                        $this->Appacl->create();
                        $this->Appacl->save($data);
                }       
    }
    
        function post_request_dont_use($url,$fields,$format='json'){
                $this->log("[url] $url",'api');
                $this->log("[fields] ".print_r($fields,1),'api');
                $fields_string = '';
                //open connection
                $ch = curl_init();
                //execute post
                foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
                rtrim($fields_string, '&');
                //set the url, number of POST vars, POST data
                curl_setopt($ch,CURLOPT_URL, $url);
                curl_setopt($ch,CURLOPT_POST, count($fields));
                curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
                curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: multpipart/form-data'));
                $result = curl_exec($ch);
                $this->log("[response] ".print_r($result,1),'api');
                //close connection
                curl_close($ch);
                switch($format){
                        case 'json':
                        $response = json_decode($result,1);
                        break;
                }
                return $response;       
        }
        
        public function getuseroffer(){
                //check for offer start
                $user_id = $this->Auth->user('id');
                $cachekey = 'target-'.$user_id;
                $getoffer = Cache::read($cachekey,'target');
                $current_time = time();
                $offerresponse = "";
                if(empty($getoffer) || $getoffer === false){
                        $offerurl = $this->apihost."getOfferForUser/?user_id=".$user_id;
                        $offerresponse = $this->make_request($offerurl,null);
                        Cache::write($cachekey , $offerresponse ,'target');
                        if(!empty($offerresponse)){
                                        
                                if($offerresponse['startDate']/1000 <= $current_time && $offerresponse['endDate']/1000 >= $current_time ){
                                                
                                }
                                else{
                                        $offerresponse = "";
                                }
                        }
                        else{
                                $offerresponse = "";
                        }
                }else{
                        if(!empty($getoffer)){
                                $offerresponse = $getoffer;
                                if($offerresponse['startDate']/1000 <= $current_time && $offerresponse['endDate']/1000 >= $current_time ){
                
                                }
                                else{
                                        $offerresponse = "";
                                }
                        }
                
                }
                return $offerresponse;  
                //check for offer end
        }
        
        public function getpin(){
                $getpin = $this->Auth->user('pincode');
                if(!isset($getpin)){
                        $userId = $this->Auth->user('id');
                        $pinquery = "select pincode from all_user_addresses where user_id = '".$userId."' and pincode is not Null limit 1";
                        $pinres = $this->Category->query($pinquery);
                        if(!empty($pinres)){
                                $getpin =  $pinres[0]['all_user_addresses']['pincode'];
                        }
                }
                if(!isset($getpin) && empty($getpin)){
                        $getpin = '';
                }
                return $getpin;
        }
        
}