Subversion Repositories SmartDukaan

Rev

Rev 16256 | Rev 16309 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
App::uses('AppController', 'Controller');
3
/**
4
 * Users Controller
5
 *
6
 * @property User $User
7
 */
14408 anikendra 8
 
9
set_time_limit(0);
10
 
13532 anikendra 11
class UsersController extends AppController {
12
 
14395 anikendra 13
	public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie','Paginator');
13532 anikendra 14
 
15
    public function beforeFilter() {
16
    	parent::beforeFilter();
17
    	// $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
18
    	$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display','home');
15511 anikendra 19
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_push','socialauth','oneringcb')); 
13736 anikendra 20
		$this->Cookie->name = 'profittill';
21
		$this->Cookie->time = 86400*30; 
22
		$this->Cookie->path = '/';
23
		$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#H23s~#^';
24
		$this->Cookie->httpOnly = true;
13532 anikendra 25
    }
26
 
15511 anikendra 27
	public function oneringcb() {
28
		$this->log(print_r($_REQUEST,1),'onering');
15523 anikendra 29
		$this->layout = "ajax";
15767 anikendra 30
		$this->response->type('json');
31
		$this->set(array(
32
		    'result' => $result,
33
		    '_serialize' => array('result')
34
		)); 
35
		$this->render('/Elements/json');
13532 anikendra 36
	}
37
 
14019 anikendra 38
	public function mywallet() {
39
		$userId = $this->request->query('user_id');
15380 anikendra 40
		$tokenValidated = $this->checkToken($userId);
15651 anikendra 41
		if(isset($userId) && !empty($userId) && $tokenValidated==1){	
14441 anikendra 42
			$next = "/my-wallet";					
14150 anikendra 43
			$redirectUrl = $this->getAutoLoginUrl($userId,$next);
15380 anikendra 44
			$this->log($redirectUrl,'headers');
15247 anikendra 45
			$this->layout = 'innerpages';
46
			$this->set(compact('redirectUrl'));
14891 anikendra 47
		}else{
15767 anikendra 48
			$this->redirect(array('controller'=>'special','action'=>'native','login'));
16308 anikendra 49
			if($tokenValidated == 0){
15651 anikendra 50
				$this->redirect(array('controller'=>'special','action'=>'native','login'));
51
			}elseif($tokenValidated == -1){
52
				$this->redirect(array('controller'=>'abouts','action'=>'askforupdate'));
16308 anikendra 53
			}
14019 anikendra 54
		}
55
	}
56
 
14825 anikendra 57
	public function socialauth() {
58
		$this->layout = "ajax";
59
		$this->log(print_r($this->request->data,1),'socialauth');
60
	}
61
 
13740 anikendra 62
	public function mine() {
13758 anikendra 63
		$this->response->type('json');
64
		$this->layout = 'ajax';
13740 anikendra 65
		$userId = $this->request->query('user_id');
66
		if(isset($userId) && !empty($userId)){
67
			$this->loadModel('User');
13758 anikendra 68
			$options = array('conditions'=>array('User.id'=>$userId),'fields'=>array('username','email','first_name','profile_pic','mobile_number','mobile_verified','address_line_1','address_line_2',
69
				'city','state','pincode','referrer'),'recursive'=>-1);
13763 anikendra 70
			$user = $this->User->find('first',$options);
71
			$result = $user['User'];
13740 anikendra 72
		}
13758 anikendra 73
		$this->set(array(
74
		    'result' => $result,
75
		    '_serialize' => array('result')
76
		)); 
77
		$this->render('/Elements/json'); 
13740 anikendra 78
	}
79
 
13532 anikendra 80
	function registertwitteruser(){
81
		$this->twitterObj->setToken($_GET['oauth_token']);
82
		$token = $this->twitterObj->getAccessToken();
83
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
84
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
85
		$data = array();
86
		$data['twitter_id'] = $twitterInfo->id;		
87
		$this->Session->write('twtusername',$twitterInfo->screen_name);
88
		$data['twitter_token'] = $token->oauth_token;
89
		$data['twitter_secret'] = $token->oauth_token_secret;
90
		$data['twitter_screen_name'] = $twitterInfo->screen_name;					
91
		$data['active'] = 1;
92
 
93
		$id = $this->Auth->user('id');
94
		if(!isset($id) || $id == ''){
95
		//	$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
96
			$user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
97
			//if($count<1){
98
			if(empty($user)){
99
				$this->User->create();
100
				$this->User->save($data);
101
//				$dbuser = $this->User->read(null,$this->User->id);
102
				$this->Auth->login($this->User->data);
103
			}else{
104
		//		$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
105
				$this->Auth->login($user['User']);
106
			}
107
		}else{
108
			//$data['id'] = $this->Auth->user('id');
109
			$user = $this->Auth->user;
110
//			$this->User->save($data);
111
//			$this->Auth->login($data);
112
		}                
113
		$user = $this->User->read(null, $this->Auth->User('id'));
114
		if ($user['User']['group_id'] == 1) {
115
			//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
116
			header('location:users/dashboard?userid='.$this->Auth->user('id'));
117
			exit();
118
		}
119
		elseif ($user['User']['group_id'] == 2) {
120
			$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
121
			exit();
122
		}
123
	}
124
 
125
    public function checkfbuser($accessToken=null){
126
		$sessionState = $this->Session->read('state');
127
		if($sessionState != $_GET['state']) {
128
			$this->redirect(array('controller'=>'users','action'=>'login'));
129
		}
130
		else {
131
			if(isset($_GET['code'])){
132
				$code = $_GET['code'];
133
				$facebookConfig = Configure::read("Facebook");		
134
				$token_url = "https://graph.facebook.com/oauth/access_token?"
135
			       . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
136
			       . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;
137
 
138
			    $response = file_get_contents($token_url);
139
			    $params = null;
140
			    parse_str($response, $params);
141
			    $accessToken = $params['access_token'];
142
			}else{
143
				$this->redirect(array('controller'=>'users','action'=>'login'));
144
			}
145
		}
146
		$this->User->recursive = -1;
147
		if (!$accessToken) {
148
		    $this->redirect(array('controller'=>'users','action'=>'login'));
149
		    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
150
		}        
151
		if (isset($accessToken) && $accessToken != 'undefined') {			
152
 
153
		    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;
154
 
155
		    $user = json_decode(file_get_contents($graph_url));
156
			$this->log("FB user = ".print_r($user,1),'fb');
157
		    if (!empty($user)) {
158
			if (!$this->isAuthorized()) {
159
			    $id = $this->User->checkFbUser($user,$accessToken);
160
				$dbuser = $this->User->findById($id);
161
			    $this->Session->write('facebook_id',$user->id);
162
				$this->Auth->login($dbuser['User']);
163
				if($this->Auth->login()){
164
					$this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
165
				}
166
			    $next = $this->Session->read('next');
167
				$this->log("next= ".$next."\n",'fb');
168
 
169
			    if (!empty($next)) {
170
					header('Location:' . $next);
171
					exit();
172
			    }else {
173
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
174
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
175
					exit();
176
			            }
177
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
178
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
179
					exit();
180
				} else {                	
181
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
182
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
183
					exit();
184
				}
185
		    }
186
		}
187
    }
188
 
189
	public function uploadavatar(){
190
		$this->log(print_r($_FILES,1),'debug');
191
		$path = "img/avatars/";
192
		$valid_formats = array("jpg", "png", "gif", "bmp");
193
		if ($this->request->is('post')) {
194
			$name = $_FILES['photoimg']['name'];
195
			$size = $_FILES['photoimg']['size'];
196
 
197
			if(strlen($name))
198
				{
199
					list($txt, $ext) = explode(".", $name);
200
					if(in_array($ext,$valid_formats))
201
					{
202
					if($size<(1024*1024))
203
						{
204
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
205
							$tmp = $_FILES['photoimg']['tmp_name'];
206
							if(move_uploaded_file($tmp, $path.$actual_image_name))
207
								{
208
									echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
209
									echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
210
								}
211
							else
212
								echo __('Upload Failed');
213
						}
214
						else
215
						echo __("Maximum allowed image file size is 1 MB");					
216
						}
217
						else
218
						echo __("Invalid file format");	
219
				}
220
			else
221
				echo __("Please select image");
222
			exit;
223
		}
224
	}
225
 
226
    function checkemail() {
227
        $this->User->recursive = -1;
228
        $this->layout = 'ajax';
229
        if (!empty($this->params['url']['data']['User']['email'])) {
230
            $username = $this->params['url']['data']['User']['email'];
231
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
232
            $username = $this->params['url']['data']['Doctor']['email'];
233
        } else {
234
            $result = false;
235
            $this->set('result', $result);
236
        }
237
        if ($this->Auth->user('id') != null) {
238
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
239
        } else {
240
            $conditions = array('User.email' => $username);
241
        }
242
        $count = $this->User->find('count', array('conditions' => $conditions));
243
        if ($count > 0) {
244
            $result = false;
245
        } else {
246
            $result = true;
247
        }
248
        $this->set('result', $result);
249
    }
250
 
251
/**
252
 * view method
253
 *
254
 * @throws NotFoundException
255
 * @param string $id
256
 * @return void
257
 */
258
	public function view($id = null) {
259
		$this->response->type('json');
260
		$this->layout = 'ajax';
261
		$callback = $this->request->query('callback');
262
		$this->User->id = $id;
263
		if (!$this->User->exists()) {
264
			throw new NotFoundException(__('Invalid user'));
265
		}
266
		$user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
267
		$result = array('user'=>$user);
268
		$this->set(array(
269
		    'result' => $result,
270
		    'callback' => $callback,
271
		    '_serialize' => array('result')
272
		));
13736 anikendra 273
		$this->render('/Elements/json');
13532 anikendra 274
	}
275
/**
276
 * edit method
277
 *
278
 * @throws NotFoundException
279
 * @param string $id
280
 * @return void
281
 */
282
 
13736 anikendra 283
    public function edit($id = null) {
14770 anikendra 284
		$this->log(print_r($this->request->data,1),'mydetails');
285
		$this->response->type('json');
286
		$this->layout = 'ajax';
287
		$this->User->recursive = -1;
288
		$updateRequired = true;
13736 anikendra 289
        if (!$this->User->exists($id)) {
14300 anikendra 290
			$result = array('success'=>false,'message'=>'Invalid user');
13736 anikendra 291
		} else {
292
	        if ($this->request->is('post') || $this->request->is('put')) {
14768 anikendra 293
           		if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])) {
294
					$options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
295
					$oldMobile = $this->User->find('first',$options);
296
					if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
14316 anikendra 297
		        		$this->request->data['mobile_verified'] = 0;
14768 anikendra 298
					}
14300 anikendra 299
	        	}
14770 anikendra 300
	        	if(!empty($this->request->data['referrer'])) {
14768 anikendra 301
	        		$referrer = $this->request->data['referrer'];
14787 anikendra 302
	        		$this->log(print_r($referrer,1),'activations');
14768 anikendra 303
	        		$this->loadModel('ActivationCode');
14785 anikendra 304
	        		$exists = $this->ActivationCode->findByCode(strtoupper($referrer));
14787 anikendra 305
	        		$this->log(print_r($exists,1),'activations');
14768 anikendra 306
	        		if(empty($exists)){
307
	        			$result = array('success'=>false,'message'=>'Invalid referral code');
15085 anikendra 308
	        			// unset($this->request->data['referrer']);
14770 anikendra 309
	        			$updateRequired = false;
15477 anikendra 310
	        		} else {
311
	        			$this->request->data['activated'] = 1;        		
312
	        		}		        		
14768 anikendra 313
	        	}	        		
14770 anikendra 314
	        	if($updateRequired){
315
		            if ($this->User->save($this->request->data)) {
15475 anikendra 316
		            	if($this->request->data['activated'] == 1) {
317
		            		//Call user activation api
318
		        			$this->markUserActivated($id);
319
		            	}			        		
14770 anikendra 320
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
321
		            } else {
322
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
323
		            }
324
		        }
13736 anikendra 325
	        }  
326
	    }
327
        $this->set(array(
328
		    'result' => $result,
329
		    '_serialize' => array('result')
330
		)); 
331
		$this->render('/Elements/json');      
13532 anikendra 332
    }
333
 
334
/**
335
 * admin_index method
336
 *
337
 * @return void
338
 */
14408 anikendra 339
 
340
	public function admin_pushnotifications(){
341
		if ($this->request->is('post')) {
342
			$sql = $this->request->data['User']['sql'];
343
			if(!empty($sql)){
344
				$users = $this->User->query($sql);
345
				$this->set(compact('users'));
346
			}
347
		}
348
	}
349
 
14445 anikendra 350
	public function generateAffiliateUrl($url,$user_id,$store){
351
		//Get StoreProduct Info		
14428 anikendra 352
		$storeId = $store['Store']['id'];
353
		$prefix = "SHA".$storeId;
354
		$tag = $prefix.time();
355
		if($storeId == 2){				
356
			$url = str_replace('www','m',$url);
357
		} elseif($storeId == 3) {
358
			$url_parts = parse_url($url);
359
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
360
			if(isset($url_parts['query'])) {
361
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
362
			}else{
363
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
364
			}
365
		} elseif($storeId == 4){
14445 anikendra 366
			$next = str_replace('www','m',$url);	
14428 anikendra 367
			$url = $this->getAutoLoginUrl($userId,$next);
368
			$url .= '?utm_source=profitmandi';
369
		}
370
		if( strpos($url, '?') === false ) {
371
			$firstChar = '?';
372
		} else {
373
			$firstChar = '&';
374
		}
375
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
376
		if(!empty($store['Store']['sub_tag_param'])){
377
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
378
		}
379
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
380
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
381
		$this->loadModel('Click');
382
		$this->Click->create();
383
		$this->Click->save($data);
384
		return $url;
385
	}
386
 
14408 anikendra 387
	public function admin_push(){
388
		if ($this->request->is('post')) {
389
			if(empty($this->request->data['userIds'])){
390
				$this->Session->setFlash(__('Please choose a few users'));
391
				$this->redirect(array('action' => 'admin_pushnotifications'));
392
			}else{
14824 anikendra 393
				$this->log(print_r($this->request->data,1),'pushnotifications');
14445 anikendra 394
				$message = $this->request->data['User'];
14776 anikendra 395
				$this->loadModel('NotificationCampaign');
396
				$this->NotificationCampaign->create();
14781 anikendra 397
				$data = array('name'=>$message['name'],'title'=>$message['title'],'type'=>$message['type'],'message'=>$message['message'],'url'=>$message['url'],'expiresat'=>$message['expiresat']);
14776 anikendra 398
				if($this->NotificationCampaign->save($data)){
399
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
400
				} else{
401
					debug($this->NotificationCampaign->validationErrors);
402
					$message['cid'] = $message['name'];
403
				}
14445 anikendra 404
				if($message['type'] == 'url' && !empty($message['url'])) {
405
					$url = $message['url'];
406
					$this->loadModel('Store');
407
					$store = $this->Store->getByUrl($url);					
408
				}				
14408 anikendra 409
				$this->loadModel('GcmUser');
410
				foreach ($this->request->data['userIds'] as $key => $value) {					
14770 anikendra 411
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
14408 anikendra 412
					$gcmUser = $this->GcmUser->find('first',$options);
413
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
14445 anikendra 414
					// $message = array('message'=>$this->request->data['User']['message']);					
415
					if($message['type'] == 'url' && !empty($message['url'])) {
416
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14428 anikendra 417
					}					
418
					$this->send_push_notification($regIds,$message,$value);
14408 anikendra 419
				}
420
			}
421
		}
422
	}
423
 
15414 manas 424
	/*private function send_push_notification($registatoin_ids, $message, $user_id) {
14409 anikendra 425
		$msg = array(
426
		    'message'       => $message['message'],
14776 anikendra 427
		    'cid'       	=> $message['cid'],
14428 anikendra 428
		    'title'         => $message['title'],
429
		    'type'      	=> $message['type'],
430
		    'url'		    => $message['url'],
14782 anikendra 431
		    // 'expiresat'	    => strtotime($message['expiresat']),
14409 anikendra 432
		    'vibrate'       => 1,
433
		    'sound'         => 1,
434
		    'largeIcon'     => 'large_icon',
435
		    'smallIcon'     => 'small_icon'
436
		);
437
		// Set POST variables
438
		$url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 439
 
14409 anikendra 440
		$fields = array(
441
		    'registration_ids' => $registatoin_ids,
442
		    'data' => $msg,
443
		);
444
		$headers = array(
445
		    'Authorization: key=' . Configure::read('googleapikey'),
446
		    'Content-Type: application/json'
447
		);
448
		//print_r($headers);
449
		// Open connection
450
		$ch = curl_init();
14408 anikendra 451
 
14409 anikendra 452
		// Set the url, number of POST vars, POST data
453
		curl_setopt($ch, CURLOPT_URL, $url);
454
		curl_setopt($ch, CURLOPT_POST, true);
455
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
456
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
14408 anikendra 457
 
14409 anikendra 458
		// Disabling SSL Certificate support temporarly
459
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
14408 anikendra 460
 
14409 anikendra 461
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
14408 anikendra 462
 
14409 anikendra 463
		// Execute post
464
		$result = curl_exec($ch);
465
		if ($result === FALSE) {
466
		    die('Curl failed: ' . curl_error($ch));
467
		}
14776 anikendra 468
		$res = json_decode($result,1);
469
		$this->loadModel('Pushnotification');
470
		$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
471
		$this->Pushnotification->create();
472
		$this->Pushnotification->save($data);
14409 anikendra 473
		// Close connection
474
		curl_close($ch);
15085 anikendra 475
		$this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
15414 manas 476
	}*/
477
	private function send_push_notification($registatoin_ids, $message, $user_id) {
478
                $msg = array(
479
                    'message'       => $message['message'],
480
                    'cid'               => $message['cid'],
481
                    'title'         => $message['title'],
482
                    'type'              => $message['type'],
483
                    'url'                   => $message['url'],
484
                    // 'expiresat'          => strtotime($message['expiresat']),
485
                    'vibrate'       => 1,
486
                    'sound'         => 1,
487
                    'largeIcon'     => 'large_icon',
488
                    'smallIcon'     => 'small_icon'
489
                );
490
                // Set POST variables
491
                $url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 492
 
15414 manas 493
                $fields = array(
494
                    'registration_ids' => $registatoin_ids,
495
                    'data' => $msg,
496
                );
497
                $headers = array(
498
                    'Authorization: key=' . Configure::read('googleapikey'),
499
                    'Content-Type: application/json'
500
                );
501
                //print_r($headers);
502
                // Open connection
503
                $ch = curl_init();
504
 
505
                // Set the url, number of POST vars, POST data
506
                curl_setopt($ch, CURLOPT_URL, $url);
507
                curl_setopt($ch, CURLOPT_POST, true);
508
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
509
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
510
 
511
                // Disabling SSL Certificate support temporarly
512
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
513
 
514
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
515
 
516
                // Execute post
517
                $result = curl_exec($ch);
518
                if ($result === FALSE) {
519
                    die('Curl failed: ' . curl_error($ch));
520
                }
521
                $res = json_decode($result,1);
522
 
523
                $this->loadModel('Pushnotification');
524
                if($res['success']==1){
525
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>'success');
526
				}else if($res['success']==0){
527
					$error_message=$res['results'][0]['error'];
528
					$sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
529
					$resultData=$this->GcmUser->query($sqlQuery);
530
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>$error_message);
531
				}
532
                #$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
533
                $this->Pushnotification->create();
534
                $this->Pushnotification->save($data);
535
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($data,1),'pushnotifications');
536
                // Close connection
537
                curl_close($ch);
538
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
539
        }
540
 
15761 manas 541
	public function admin_index() {
13532 anikendra 542
		$this->User->recursive = 0;
15767 anikendra 543
		$options = array('limit'=>20,'order'=>array('id'=>'desc'));
14395 anikendra 544
		$this->Paginator->settings = $options;
545
		$users = $this->Paginator->paginate();
15761 manas 546
 
13532 anikendra 547
		$groups = $this->User->Group->find('list');
15761 manas 548
 
549
		$postOfficeQuery="select pincode,state from postoffices group by pincode";
550
		$postOfficeResult=$this->User->query($postOfficeQuery);
551
		$postOffice=array();
552
		foreach($postOfficeResult as $value){
553
			$postOffice[$value['postoffices']['pincode']]=$value['postoffices']['state'];
554
		}
555
		foreach ($users as $key => $value) {
556
	$userId=$value['User']['id'];
15815 anikendra 557
	$masterQuery="select u.id,rl.retailer_id,r.state,r.city,r.pin,
15762 manas 558
					ra.state,ra.city,ra.pin,
559
					u.state,u.city,u.pincode,
560
					ua.state,ua.city,ua.pincode 
561
					from retailers r left  join retaileraddresses ra  on r.id=ra.retailer_id  
562
					join retailerlinks rl on r.id=rl.retailer_id 
563
					right join users u on rl.user_id=u.id 
564
					left join useraddresses ua on u.id=ua.user_id 
565
					where u.id=$userId";
566
	$retailerAddress=$this->User->query($masterQuery);
15815 anikendra 567
	$users[$key]['User']['retailer_id']=$retailerAddress[0]['rl']['retailer_id'];	
15762 manas 568
	if($retailerAddress[0]['ra']['city']==null && $retailerAddress[0]['ra']['state']==null && $retailerAddress[0]['ra']['pin']==null){
569
		if($retailerAddress[0]['r']['city']==null && $retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']==null){
570
			if($retailerAddress[0]['ua']['city']==null && $retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']==null){
571
				if($retailerAddress[0]['u']['city']==null && $retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']==null){
572
 
15761 manas 573
				}else{
15762 manas 574
					if($retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']!=null){
575
						$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['u']['pincode']];		
576
					}else{
577
						$users[$key]['User']['state']=$retailerAddress[0]['u']['state'];	
578
						$users[$key]['User']['city']=$retailerAddress[0]['u']['city'];	
15761 manas 579
				}	
15762 manas 580
 
581
				}
15761 manas 582
			}
583
			else{
15762 manas 584
				if($retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']!=null){
585
					$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pincode']];		
15761 manas 586
				}else{
15762 manas 587
					$users[$key]['User']['state']=$retailerAddress[0]['ua']['state'];	
588
					$users[$key]['User']['city']=$retailerAddress[0]['ua']['city'];	
589
				}	
15761 manas 590
			}
591
		}
592
		else{
15762 manas 593
			if($retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']!=null){
594
				$users[$key]['User']['city']=$retailerAddress[0]['r']['city'];	
595
				$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];		
15761 manas 596
			}else{
15762 manas 597
				$users[$key]['User']['state']=$retailerAddress[0]['r']['state'];	
598
				$users[$key]['User']['city']=$retailerAddress[0]['r']['city'];	
599
			}		
15761 manas 600
		}
601
	}else{
15762 manas 602
		if(($retailerAddress[0]['ra']['state']==null || empty($retailerAddress[0]['ra']['state'])) && $retailerAddress[0]['ra']['pin']!=null){
603
			$users[$key]['User']['city']=$retailerAddress[0]['ra']['city'];	
604
			$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];		
15761 manas 605
		}else{
15762 manas 606
			$users[$key]['User']['state']=$retailerAddress[0]['ra']['state'];	
607
			$users[$key]['User']['city']=$retailerAddress[0]['ra']['city'];	
608
		}		
13532 anikendra 609
	}
15761 manas 610
}
15762 manas 611
 
15761 manas 612
	$this->set(compact('groups','users'));	
613
}
614
 
13532 anikendra 615
/**
616
 * admin_view method
617
 *
618
 * @throws NotFoundException
619
 * @param string $id
620
 * @return void
621
 */
622
	public function admin_view($id = null) {
623
		$this->User->id = $id;
624
		if (!$this->User->exists()) {
625
			throw new NotFoundException(__('Invalid user'));
626
		}
627
		$this->set('user', $this->User->read(null, $id));
628
	}
629
 
630
/**
631
 * admin_add method
632
 *
633
 * @return void
634
 */
635
	public function admin_add() {
636
		if ($this->request->is('post')) {
637
			$this->User->create();
638
			if ($this->User->save($this->request->data)) {
639
				$this->Session->setFlash(__('The user has been saved'));
640
				$this->redirect(array('action' => 'index'));
641
			} else {
642
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
643
			}
644
		}
645
		$groups = $this->User->Group->find('list');
646
		$this->set(compact('groups'));
647
	}
648
 
649
/**
650
 * admin_edit method
651
 *
652
 * @throws NotFoundException
653
 * @param string $id
654
 * @return void
655
 */
656
	public function admin_edit($id = null) {
657
		$this->User->id = $id;
658
		if (!$this->User->exists()) {
659
			throw new NotFoundException(__('Invalid user'));
660
		}
661
		if ($this->request->is('post') || $this->request->is('put')) {
662
			if ($this->User->save($this->request->data)) {
663
				$this->Session->setFlash(__('The user has been saved'));
664
				$this->redirect(array('action' => 'index'));
665
			} else {
666
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
667
			}
668
		} else {
669
			$this->request->data = $this->User->read(null, $id);
670
		}
671
		$groups = $this->User->Group->find('list');
672
		$this->set(compact('groups'));
673
	}
674
 
675
/**
676
 * admin_delete method
677
 *
678
 * @throws MethodNotAllowedException
679
 * @throws NotFoundException
680
 * @param string $id
681
 * @return void
682
 */
15217 anikendra 683
/*
13532 anikendra 684
	public function admin_delete($id = null) {
685
		if (!$this->request->is('post')) {
686
			throw new MethodNotAllowedException();
687
		}
688
		$this->User->id = $id;
689
		if (!$this->User->exists()) {
690
			throw new NotFoundException(__('Invalid user'));
691
		}
692
		if ($this->User->delete()) {
693
			$this->Session->setFlash(__('User deleted'));
694
			$this->redirect(array('action' => 'index'));
695
		}
696
		$this->Session->setFlash(__('User was not deleted'));
697
		$this->redirect(array('action' => 'index'));
698
	}
15217 anikendra 699
*/
13532 anikendra 700
 
15217 anikendra 701
	public function admin_search() {
702
		$type = $this->request->query('type');
703
		$search = $this->request->query('search');
704
		$this->User->recursive = -1;
705
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
15232 anikendra 706
		if($type == 'unactivated'){
707
			$options['conditions'] = array('activated' =>0);
708
		}
709
		else if(!empty($type) && !empty($search)){
710
			$options['conditions'] = array($type.' LIKE '=>"%$search%");			
711
		}else{
712
			$options['conditions'] = array('date(created)'=>date('Y-m-d',time()));			
15217 anikendra 713
		}		
15232 anikendra 714
		$this->Paginator->settings = $options;
715
		$users = $this->Paginator->paginate();		
16256 manas 716
		foreach ($users as $key => $value) {
717
			$userId = $value['User']['id'];
718
			$quer= "select r.retailer_id,a.name from retailerlinks r join agents a on r.agent_id=a.id where user_id=$userId";
719
			$res = $this->User->query($quer);
720
			if(empty($res)){
721
				$users[$key]['User']['retailer_id']="";	
722
				$users[$key]['User']['agent_name']="";	
723
			}else{
724
				$users[$key]['User']['retailer_id']=$res[0]['r']['retailer_id'];	
725
				$users[$key]['User']['agent_name']=$res[0]['a']['name'];	
726
			}
727
 
728
		}
729
 
15380 anikendra 730
		$this->set(compact('users'));	
15217 anikendra 731
	}
732
 
13532 anikendra 733
	public function dashboard() {
734
		App::uses('CakeTime', 'Utility');
735
		$user = $this->User->read(null,$this->Auth->user('id'));
736
		$this->set('user',$user);
737
		$this->set('title_for_layout', "Dashboard");
738
	}
739
 
740
/**
741
* user authentication funtions
742
*/
743
	public function register() {
744
		$referrer = $this->request->query('referrer');
745
		$this->log('referrer = '.$referrer);
746
		$this->Cookie->write('referrer',$referrer);
747
		$this->layout = 'auth';
748
		$this->set('title_for_layout','Register your free letushaggle.com account');
749
		$this->SignMeUp->register();
750
	}
751
 
752
	public function activate() {
13714 anikendra 753
		$this->layout = 'auth';
13532 anikendra 754
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 755
		$this->SignMeUp->activate();
13532 anikendra 756
	}
757
 
758
	public function forgotten_password() {
13714 anikendra 759
		$this->layout = 'auth';
13532 anikendra 760
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 761
		$this->SignMeUp->forgottenPassword();
13532 anikendra 762
	}	
763
 
764
	public function login() {
765
		$this->layout = 'auth';
766
		if (!empty($this->data['User']['next'])) {
767
		    $next = $this->data['User']['next'];
768
		    $this->Session->write('next', $next);
769
		} elseif (!empty($this->params['url']['next'])) {
770
		    $next = $this->params['url']['next'];
771
		    $this->Session->write('next', $next);
772
		}
773
		if ($this->Auth->login()) {
774
		    $next = $this->Session->read('next');
775
		    if (!empty($next)) {
776
				header('location:' . $next);
777
				exit();
778
		    }
15188 anikendra 779
		    $user = $this->User->read(null, $this->Auth->User('id'));		 		    
13532 anikendra 780
			if ($user['User']['group_id'] == 1) {
13736 anikendra 781
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 782
				exit();
783
			}
15188 anikendra 784
			else if ($user['User']['group_id'] >= 2) {
785
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
786
				exit();
787
		    }
13532 anikendra 788
		} else {
789
		    if (!empty($this->data)) {                
13736 anikendra 790
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 791
		    }
792
		}
793
		$this->set('title_for_layout', "Login to letushaggle.com");
794
	}
795
 
796
	public function logout() {
797
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
798
		$this->redirect($this->Auth->logout());
799
	}
800
 
801
	public function updatetimezone() {
802
		$this->layout = 'ajax';		
803
		$timezone = $_GET['tz'];
804
		Configure::load('constant');
805
		$timeZones = Configure::read("timeZones");
806
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
807
		if($this->User->query($query)){
808
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
809
		}else{
810
			$result = array('success' => false);
811
		}
812
		$this->set('result',$result);
813
	}
814
 
13736 anikendra 815
	public function verifymobile() {
816
		$this->layout = 'innerpages';
817
	}
13532 anikendra 818
 
13736 anikendra 819
	public function getdial2verifynumber() {
820
		$TelNumber=substr($this->request->data("phone_number"),-10);
821
 
822
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
823
	    $API_KEY = Configure::read("dial2verifyapikey");
824
 
825
	  	//Get API Image Response
826
	    $url ="http://engine.dial2verify.in/Integ/API.dvf?mobile=$TelNumber&passkey=$API_KEY&notify=http://engine.dial2verify.in/Integ/CatchAll.dvf&e-notify=support@dial2verify.in&out=JSON&cn=IN";
827
	    // $json=file_get_contents($APIUrl);
828
	    $json = json_encode($this->make_request($url,null));
829
	  	$this->response->type('json');
830
		$this->layout = 'ajax';
831
	    echo($json);die;
832
	}
833
 
834
	public function getdial2verifystatus() { 
835
 
836
		$SID=$_REQUEST["SID"];
837
 
838
	    $json = array();
839
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
840
 
841
	   // Make a call to Dial2Verify API & Parse The JSON Response
842
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
843
		$RequestPayload = $this->make_request($VerificationCall,null);
844
		// $RequestPayload = json_decode($response,true);
845
 
846
		$VerifStatus=$RequestPayload["VerificationStatus"];
847
 
848
		$json["VerificationStatus"]=$VerifStatus;
849
 
850
	   	$this->response->type('json');
851
		$this->layout = 'ajax';
852
	    echo(json_encode($json));die;
853
	}
854
 
855
	public function skipmobileverification() {
856
		$this->Session->write('skipmobileverification',1);
13739 anikendra 857
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 858
	}
859
 
860
	public function reauthenticate($userId) {
861
		$user = $this->User->read(null,$userId);
862
		$this->Auth->login($user['User']);
863
		$json = array('success'=>true);
864
		$this->response->type('json');
865
		$this->layout = 'ajax';
14150 anikendra 866
	    echo(json_encode($json));die;
13736 anikendra 867
	}
16013 anikendra 868
 
869
	public function getlinks($userId) {		
16082 anikendra 870
		$cachekey = 'userlinks-'.$userId;
871
		$links = Cache::read($cachekey,'day');
872
		if(empty($links)) {
873
			$links[3] = $this->getCatergoryLinks($userId,3);
874
			$links[5] = $this->getCatergoryLinks($userId,5);
875
			Cache::write($cachekey,$links,'day');
876
		}
16013 anikendra 877
	 	if ($this->request->is('requested')) {
878
            return $links;
879
        }
880
        $this->set('links', $links);
881
	}
882
 
883
	public function getCatergoryLinks($userId,$categoryId) {
884
		$temp = $links = $fixed = $random = array();		
885
		//populate fixed brands array
886
		if($categoryId == 3){
887
			$sql = "SELECT id,name FROM brands WHERE lower(name) IN('samsung','micromax','apple','intex','lava','spice','htc','lenovo','nokia','microsoft','xiaomi') AND category_id = $categoryId";
888
		} else {
889
			$sql = "SELECT id,name FROM brands WHERE lower(name) IN('lenovo','dell','hp','iball','digiflip','samsung','datavent','apple','micromax','asus') AND category_id = $categoryId";
890
		}
891
		$brandnames = $this->User->query($sql);
892
		if(!empty($brandnames)){
893
			foreach ($brandnames as $key => $value) {
894
				if($categoryId == 3){
895
					if($value['brands']['name'] == 'Samsung' || $value['brands']['name'] == 'Micromax'){
896
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
897
					} else {
898
						$temp[] = $value['brands'];
899
					}							
900
				}else{
901
					if($value['brands']['name'] == 'Dell' || $value['brands']['name'] == 'Lenovo'){
902
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
903
					} else {
904
						$temp[] = $value['brands'];
905
					}							
906
				}			
907
			}		
908
		}
909
		$rand_keys = array_rand(array_keys($temp), 3);
910
		$sql = "select p.brand,count(p.brand) count,b.id from pushnotificationusergroups p left join brands b on p.brand = b.name where p.userids = $userId and p.category_id = $categoryId group by p.brand order by count desc limit 5";
911
		$brands = $this->User->query($sql);
912
		if(!empty($brands)){
913
			foreach ($brands as $key => $brand) {
914
				if($key>2 && !empty($temp))continue;
915
				$links[$categoryId][$brand['p']['brand']] = "?filter=brand&brands=".$brand['b']['id'];
916
			}	
917
			if(!empty($temp)){
918
				for($i=0;$i<2;$i++) {
919
					$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];
920
				}
921
			}
922
		} else {
923
			if(!empty($fixed) && !empty($temp)){
924
				foreach ($fixed as $key => $value) {
925
					$links[$categoryId][$key] = $value;
926
				}			
927
				for($i=0;$i<3;$i++){
928
					$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];	
929
				}
930
			}
931
		}		
932
		return $links[$categoryId];		
933
	}
934
}