Subversion Repositories SmartDukaan

Rev

Rev 14426 | Rev 14441 | 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',
                '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 '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');
                //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'));
    }
        
    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 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){
        $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;
        }       
        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'];
                // $data['class'] = $this->request->data['class'];
                if($this->modelClass == 'Exceptionalskudiscount') {
                        $data['class'] = 'SkuDiscountInfo';     
                }elseif($this->modelClass == 'Skuscheme'){
                        $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';
                $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');
        }

        function getAutoLoginUrl($userId,$next) {
                $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);
                $data = '?data='.base64_encode(serialize($data));
                $token = '&token='.md5(Configure::read('saholicapikey').'|'.$user['UserAccount'][0]['account_key']);            
                return Configure::read('saholicauthurl').$data.$token.$next;
        }
}