Subversion Repositories SmartDukaan

Rev

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 $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;              
        
                //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 'localmobiledtr':
                                Configure::load('dev');
                                break;
                        case 'staging.mobilehotindia.com':
                        case 'www.staging.mobilehotindia.com':
                                Configure::load('staging');
                                break;
                        default:
                        case 'www.mobilehotindia.com':
                        case 'mobilehotindia.com':
                        case 'api.mobilehotindia.com':
                                Configure::load('live');
                                break;
                }
                $facebookConfig = Configure::read("Facebook");          
                $categories = Configure::read('Categories');
                //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'));                   
                $debugusers = Configure::read('debugusers');
                if($id = $this->isAuthorized()){
                        if(in_array($id, $debugusers)){
                                $this->Cookie->write('debuguser',1);
                        }else{
                                $this->Cookie->delete('debuguser');
                        }
                }
    }
        
    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() {
                $headers =  $this->getallheaders();
        $this->log(print_r($headers,1),'headers');
        $token = $_COOKIE['token'];
        $this->log("Token : $token",'headers');
        // if(isset($headers['Token']) && !empty($headers['Token'])) {
        if(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);
                $userId = $this->request->query('user_id');
                        if(isset($userId) && !empty($userId)){
                                if($userId == $user['SocialProfile']['user_id']){
                                        return true;
                                }
                        }
        } else {
                return true;
        }
        return false;
    }

    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){
        $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.'getStaticdeals/?categoryId='.$categoryId.'&sort='.$sort.'&direction='.$direction.'&limit='.$this->limit.'&offset='.$offset;
        }else{
                $url = $this->apihost.'getStaticdeals/?categoryId='.$categoryId.'&limit='.$this->limit.'&offset='.$offset;
        }       
        if(isset($filter) && !empty($filter)){
                $url .= "&filterData=brandFilter:".$brands;
        }
        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_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);
                $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('dealsperpage');
                $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'){
                                $data['class'] = 'SkuDealerPrices';
                        }else{
                                $data['class'] = 'SkuSchemeDetails';
                        }
                }elseif($this->modelClass == 'Exceptionalnlc'){
                        $data['class'] = 'ExceptionalNlc';
                }
                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');
                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));
                $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']);            
                return Configure::read('saholicauthurl').$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;
    }
}