Subversion Repositories SmartDukaan

Rev

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

<?php
class PushnotificationShell extends AppShell {
    public $uses = array('Pushnotification','GcmUser','Store','User','Click');

    public function main() {
                $this->Pushnotification->Behaviors->attach('Containable');
                $options = array('conditions'=>array('Pushnotification.type'=>'pending'),'contain'=>array('NotificationCampaign'));
                $data = $this->Pushnotification->find('all',$options);
                if(!empty($data)) {
                        if($data[0]['NotificationCampaign']['type'] == 'url' && !empty($data[0]['NotificationCampaign']['url'])) {
                                $url = $data[0]['NotificationCampaign']['url'];
                                $store = $this->Store->getByUrl($url);                                  
                        }
                        foreach($data AS $user) {
                                // $this->out(print_r($user,1));                                
                                $options = array('conditions'=>array('user_id'=>$user['Pushnotification']['user_id']),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
                                $gcmUser = $this->GcmUser->find('first',$options);
                                $regIds = array($gcmUser['GcmUser']['gcm_regid']);
                                $message = $user['NotificationCampaign'];                                       
                                if($user['NotificationCampaign']['type'] == 'url' && !empty($user['NotificationCampaign']['url'])) {
                                        $message['url'] = $this->generateAffiliateUrl($user['NotificationCampaign']['url'],$user['Pushnotification']['user_id'],$store);
                                }       
                                $result = $this->send_push_notification($regIds,$message,$user['Pushnotification']['user_id'],$user['Pushnotification']['id']);
                        }
                }
    }

    private function send_push_notification($registatoin_ids, $message, $user_id,$cid) {
        Configure::load('live');
                $msg = array(
                    'message'       => $message['message'],
                    'cid'               => $message['id'],
                    'title'         => $message['title'],
                    'type'              => $message['type'],
                    'url'                   => $message['url'],
                    'vibrate'       => 1,
                    'sound'         => 1,
                    'largeIcon'     => 'large_icon',
                    'smallIcon'     => 'small_icon'
                );
                // Set POST variables
                $url = 'https://android.googleapis.com/gcm/send';

                $fields = array(
                    'registration_ids' => $registatoin_ids,
                    'data' => $msg,
                );
                $headers = array(
                    'Authorization: key=' . Configure::read('googleapikey'),
                    'Content-Type: application/json'
                );
                $this->log(print_r($msg,1),'pushnotifications');
                // Open connection
                $ch = curl_init();

                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                // Disabling SSL Certificate support temporarly
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

                // Execute post
                $result = curl_exec($ch);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($ch));
                }
                $res = json_decode($result,1);
                // $data = array('notification_campaign_id'=>$message['id'],'user_id'=>$user_id,'status'=>$res['success']);
                // $this->Pushnotification->create();
                // $this->Pushnotification->save($data);
                // Close connection
                curl_close($ch);
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
                if($res['success']==1){
                        $data = array('id'=>$cid,'type'=>'sent','status'=>$res['success'],'message'=>'success');
                        $this->Pushnotification->save($data);
                }else if($res['success']==0){
                        $this->loadModel(GcmUser);
                        $message=$res['results'][0]['error'];
                        $data = array('id'=>$cid,'type'=>'sent','status'=>$res['success'],'message'=>$message);
                        
                        $sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
                        $resultData=$this->GcmUser->query($sqlQuery);
                        $this->Pushnotification->save($data);
                }
                return $res['success'];
        }

        private function generateAffiliateUrl($url,$user_id,$store){
                //Get StoreProduct Info         
                $storeId = $store['Store']['id'];
                $prefix = "SHA".$storeId;
                $tag = $prefix.time();
                if($storeId == 2){                              
                        $url = str_replace('www','m',$url);
                } elseif($storeId == 3) {
                        $url_parts = parse_url($url);
                        $url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
                        if(isset($url_parts['query'])) {
                                $url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
                        }else{
                                $url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
                        }
                } elseif($storeId == 4){
                        $next = str_replace('www','m',$url);            
                        $url = $this->getAutoLoginUrl($userId,$next);
                        $url .= '?utm_source=profitmandi';
                } else {
                        $url .= "?user_id=$user_id";
                }
                if( strpos($url, '?') === false ) {
                        $firstChar = '?';
                } else {
                        $firstChar = '&';
                }
                $url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
                if(!empty($store['Store']['sub_tag_param'])){
                        $url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
                }
                $extras = array('store'=>$store['Store']['name'],'source'=>'notification');
                $data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
                // $this->loadModel('Click');
                $this->Click->create();
                $this->Click->save($data);
                return $url;
        }

        private function getAutoLoginUrl($userId,$next) {
                $saholicoffline = Configure::read('saholicoffline');
                if($saholicoffline) {
                        $url = "/abouts/saholicoffline";
                        return $url;
                }               
                $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);
                $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;
        }
}