Subversion Repositories SmartDukaan

Rev

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