Subversion Repositories SmartDukaan

Rev

Rev 14770 | Rev 14781 | 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');
14395 anikendra 19
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_index')); 
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
 
27
	public function bookmarklet() {
13714 anikendra 28
		$this->set('title_for_layout','Profittill Bookmarklet');
13532 anikendra 29
	}
30
 
14019 anikendra 31
	public function mywallet() {
32
		$userId = $this->request->query('user_id');
14150 anikendra 33
		if(isset($userId) && !empty($userId)){	
14441 anikendra 34
			$next = "/my-wallet";					
14150 anikendra 35
			$redirectUrl = $this->getAutoLoginUrl($userId,$next);
14019 anikendra 36
			header('location:'.$redirectUrl);
37
			exit();
38
		}
39
	}
40
 
13740 anikendra 41
	public function mine() {
13758 anikendra 42
		$this->response->type('json');
43
		$this->layout = 'ajax';
13740 anikendra 44
		$userId = $this->request->query('user_id');
45
		if(isset($userId) && !empty($userId)){
46
			$this->loadModel('User');
13758 anikendra 47
			$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',
48
				'city','state','pincode','referrer'),'recursive'=>-1);
13763 anikendra 49
			$user = $this->User->find('first',$options);
50
			$result = $user['User'];
13740 anikendra 51
		}
13758 anikendra 52
		$this->set(array(
53
		    'result' => $result,
54
		    '_serialize' => array('result')
55
		)); 
56
		$this->render('/Elements/json'); 
13740 anikendra 57
	}
58
 
13532 anikendra 59
	function registertwitteruser(){
60
		$this->twitterObj->setToken($_GET['oauth_token']);
61
		$token = $this->twitterObj->getAccessToken();
62
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
63
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
64
		$data = array();
65
		$data['twitter_id'] = $twitterInfo->id;		
66
		$this->Session->write('twtusername',$twitterInfo->screen_name);
67
		$data['twitter_token'] = $token->oauth_token;
68
		$data['twitter_secret'] = $token->oauth_token_secret;
69
		$data['twitter_screen_name'] = $twitterInfo->screen_name;					
70
		$data['active'] = 1;
71
 
72
		$id = $this->Auth->user('id');
73
		if(!isset($id) || $id == ''){
74
		//	$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
75
			$user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
76
			//if($count<1){
77
			if(empty($user)){
78
				$this->User->create();
79
				$this->User->save($data);
80
//				$dbuser = $this->User->read(null,$this->User->id);
81
				$this->Auth->login($this->User->data);
82
			}else{
83
		//		$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
84
				$this->Auth->login($user['User']);
85
			}
86
		}else{
87
			//$data['id'] = $this->Auth->user('id');
88
			$user = $this->Auth->user;
89
//			$this->User->save($data);
90
//			$this->Auth->login($data);
91
		}                
92
		$user = $this->User->read(null, $this->Auth->User('id'));
93
		if ($user['User']['group_id'] == 1) {
94
			//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
95
			header('location:users/dashboard?userid='.$this->Auth->user('id'));
96
			exit();
97
		}
98
		elseif ($user['User']['group_id'] == 2) {
99
			$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
100
			exit();
101
		}
102
	}
103
 
104
    public function checkfbuser($accessToken=null){
105
		$sessionState = $this->Session->read('state');
106
		if($sessionState != $_GET['state']) {
107
			$this->redirect(array('controller'=>'users','action'=>'login'));
108
		}
109
		else {
110
			if(isset($_GET['code'])){
111
				$code = $_GET['code'];
112
				$facebookConfig = Configure::read("Facebook");		
113
				$token_url = "https://graph.facebook.com/oauth/access_token?"
114
			       . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
115
			       . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;
116
 
117
			    $response = file_get_contents($token_url);
118
			    $params = null;
119
			    parse_str($response, $params);
120
			    $accessToken = $params['access_token'];
121
			}else{
122
				$this->redirect(array('controller'=>'users','action'=>'login'));
123
			}
124
		}
125
		$this->User->recursive = -1;
126
		if (!$accessToken) {
127
		    $this->redirect(array('controller'=>'users','action'=>'login'));
128
		    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
129
		}        
130
		if (isset($accessToken) && $accessToken != 'undefined') {			
131
 
132
		    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;
133
 
134
		    $user = json_decode(file_get_contents($graph_url));
135
			$this->log("FB user = ".print_r($user,1),'fb');
136
		    if (!empty($user)) {
137
			if (!$this->isAuthorized()) {
138
			    $id = $this->User->checkFbUser($user,$accessToken);
139
				$dbuser = $this->User->findById($id);
140
			    $this->Session->write('facebook_id',$user->id);
141
				$this->Auth->login($dbuser['User']);
142
				if($this->Auth->login()){
143
					$this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
144
				}
145
			    $next = $this->Session->read('next');
146
				$this->log("next= ".$next."\n",'fb');
147
 
148
			    if (!empty($next)) {
149
					header('Location:' . $next);
150
					exit();
151
			    }else {
152
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
153
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
154
					exit();
155
			            }
156
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
157
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
158
					exit();
159
				} else {                	
160
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
161
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
162
					exit();
163
				}
164
		    }
165
		}
166
    }
167
 
168
	public function uploadavatar(){
169
		$this->log(print_r($_FILES,1),'debug');
170
		$path = "img/avatars/";
171
		$valid_formats = array("jpg", "png", "gif", "bmp");
172
		if ($this->request->is('post')) {
173
			$name = $_FILES['photoimg']['name'];
174
			$size = $_FILES['photoimg']['size'];
175
 
176
			if(strlen($name))
177
				{
178
					list($txt, $ext) = explode(".", $name);
179
					if(in_array($ext,$valid_formats))
180
					{
181
					if($size<(1024*1024))
182
						{
183
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
184
							$tmp = $_FILES['photoimg']['tmp_name'];
185
							if(move_uploaded_file($tmp, $path.$actual_image_name))
186
								{
187
									echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
188
									echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
189
								}
190
							else
191
								echo __('Upload Failed');
192
						}
193
						else
194
						echo __("Maximum allowed image file size is 1 MB");					
195
						}
196
						else
197
						echo __("Invalid file format");	
198
				}
199
			else
200
				echo __("Please select image");
201
			exit;
202
		}
203
	}
204
 
205
    function checkemail() {
206
        $this->User->recursive = -1;
207
        $this->layout = 'ajax';
208
        if (!empty($this->params['url']['data']['User']['email'])) {
209
            $username = $this->params['url']['data']['User']['email'];
210
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
211
            $username = $this->params['url']['data']['Doctor']['email'];
212
        } else {
213
            $result = false;
214
            $this->set('result', $result);
215
        }
216
        if ($this->Auth->user('id') != null) {
217
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
218
        } else {
219
            $conditions = array('User.email' => $username);
220
        }
221
        $count = $this->User->find('count', array('conditions' => $conditions));
222
        if ($count > 0) {
223
            $result = false;
224
        } else {
225
            $result = true;
226
        }
227
        $this->set('result', $result);
228
    }
229
 
230
/**
231
 * view method
232
 *
233
 * @throws NotFoundException
234
 * @param string $id
235
 * @return void
236
 */
237
	public function view($id = null) {
238
		$this->response->type('json');
239
		$this->layout = 'ajax';
240
		$callback = $this->request->query('callback');
241
		$this->User->id = $id;
242
		if (!$this->User->exists()) {
243
			throw new NotFoundException(__('Invalid user'));
244
		}
245
		$user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
246
		$result = array('user'=>$user);
247
		$this->set(array(
248
		    'result' => $result,
249
		    'callback' => $callback,
250
		    '_serialize' => array('result')
251
		));
13736 anikendra 252
		$this->render('/Elements/json');
13532 anikendra 253
	}
254
/**
255
 * edit method
256
 *
257
 * @throws NotFoundException
258
 * @param string $id
259
 * @return void
260
 */
261
 
13736 anikendra 262
    public function edit($id = null) {
14770 anikendra 263
		$this->log(print_r($this->request->data,1),'mydetails');
264
		$this->response->type('json');
265
		$this->layout = 'ajax';
266
		$this->User->recursive = -1;
267
		$updateRequired = true;
13736 anikendra 268
        if (!$this->User->exists($id)) {
14300 anikendra 269
			$result = array('success'=>false,'message'=>'Invalid user');
13736 anikendra 270
		} else {
271
	        if ($this->request->is('post') || $this->request->is('put')) {
14768 anikendra 272
           		if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])) {
273
					$options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
274
					$oldMobile = $this->User->find('first',$options);
275
					if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
14316 anikendra 276
		        		$this->request->data['mobile_verified'] = 0;
14768 anikendra 277
					}
14300 anikendra 278
	        	}
14770 anikendra 279
	        	if(!empty($this->request->data['referrer'])) {
14768 anikendra 280
	        		$referrer = $this->request->data['referrer'];
281
	        		$this->loadModel('ActivationCode');
282
	        		$exists = $this->ActivationCode->findByCode($referrer);
283
	        		if(empty($exists)){
284
	        			$result = array('success'=>false,'message'=>'Invalid referral code');
285
	        			unset($this->request->data['referrer']);
14770 anikendra 286
	        			$updateRequired = false;
14768 anikendra 287
	        		}
288
	        	}	        		
14770 anikendra 289
	        	if($updateRequired){
290
		            if ($this->User->save($this->request->data)) {
291
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
292
		            } else {
293
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
294
		            }
295
		        }
13736 anikendra 296
	        }  
297
	    }
298
        $this->set(array(
299
		    'result' => $result,
300
		    '_serialize' => array('result')
301
		)); 
302
		$this->render('/Elements/json');      
13532 anikendra 303
    }
304
 
305
/**
306
 * admin_index method
307
 *
308
 * @return void
309
 */
14408 anikendra 310
 
311
	public function admin_pushnotifications(){
312
		if ($this->request->is('post')) {
313
			$sql = $this->request->data['User']['sql'];
314
			if(!empty($sql)){
315
				$users = $this->User->query($sql);
316
				$this->set(compact('users'));
317
			}
318
		}
319
	}
320
 
14445 anikendra 321
	public function generateAffiliateUrl($url,$user_id,$store){
322
		//Get StoreProduct Info		
14428 anikendra 323
		$storeId = $store['Store']['id'];
324
		$prefix = "SHA".$storeId;
325
		$tag = $prefix.time();
326
		if($storeId == 2){				
327
			$url = str_replace('www','m',$url);
328
		} elseif($storeId == 3) {
329
			$url_parts = parse_url($url);
330
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
331
			if(isset($url_parts['query'])) {
332
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
333
			}else{
334
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
335
			}
336
		} elseif($storeId == 4){
14445 anikendra 337
			$next = str_replace('www','m',$url);	
14428 anikendra 338
			$url = $this->getAutoLoginUrl($userId,$next);
339
			$url .= '?utm_source=profitmandi';
340
		}
341
		if( strpos($url, '?') === false ) {
342
			$firstChar = '?';
343
		} else {
344
			$firstChar = '&';
345
		}
346
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
347
		if(!empty($store['Store']['sub_tag_param'])){
348
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
349
		}
350
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
351
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
352
		$this->loadModel('Click');
353
		$this->Click->create();
354
		$this->Click->save($data);
355
		return $url;
356
	}
357
 
14408 anikendra 358
	public function admin_push(){
359
		if ($this->request->is('post')) {
360
			if(empty($this->request->data['userIds'])){
361
				$this->Session->setFlash(__('Please choose a few users'));
362
				$this->redirect(array('action' => 'admin_pushnotifications'));
363
			}else{
14445 anikendra 364
				$message = $this->request->data['User'];
14776 anikendra 365
				$this->loadModel('NotificationCampaign');
366
				$this->NotificationCampaign->create();
367
				$data = array('name'=>$message['name'],'title'=>$message['title'],'type'=>$message['type'],'message'=>$message['message'],'url'=>$message['url']);
368
				if($this->NotificationCampaign->save($data)){
369
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
370
				} else{
371
					debug($this->NotificationCampaign->validationErrors);
372
					$message['cid'] = $message['name'];
373
				}
14445 anikendra 374
				if($message['type'] == 'url' && !empty($message['url'])) {
375
					$url = $message['url'];
376
					$this->loadModel('Store');
377
					$store = $this->Store->getByUrl($url);					
378
				}				
14408 anikendra 379
				$this->loadModel('GcmUser');
380
				foreach ($this->request->data['userIds'] as $key => $value) {					
14770 anikendra 381
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
14408 anikendra 382
					$gcmUser = $this->GcmUser->find('first',$options);
383
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
14445 anikendra 384
					// $message = array('message'=>$this->request->data['User']['message']);					
385
					if($message['type'] == 'url' && !empty($message['url'])) {
386
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14428 anikendra 387
					}					
388
					$this->send_push_notification($regIds,$message,$value);
14408 anikendra 389
				}
390
			}
391
		}
392
	}
393
 
14428 anikendra 394
	private function send_push_notification($registatoin_ids, $message, $user_id) {
14409 anikendra 395
		$msg = array(
396
		    'message'       => $message['message'],
14776 anikendra 397
		    'cid'       	=> $message['cid'],
14428 anikendra 398
		    'title'         => $message['title'],
399
		    'type'      	=> $message['type'],
400
		    'url'		    => $message['url'],
14409 anikendra 401
		    'vibrate'       => 1,
402
		    'sound'         => 1,
403
		    'largeIcon'     => 'large_icon',
404
		    'smallIcon'     => 'small_icon'
405
		);
406
		// Set POST variables
407
		$url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 408
 
14409 anikendra 409
		$fields = array(
410
		    'registration_ids' => $registatoin_ids,
411
		    'data' => $msg,
412
		);
413
		$headers = array(
414
		    'Authorization: key=' . Configure::read('googleapikey'),
415
		    'Content-Type: application/json'
416
		);
417
		//print_r($headers);
418
		// Open connection
419
		$ch = curl_init();
14408 anikendra 420
 
14409 anikendra 421
		// Set the url, number of POST vars, POST data
422
		curl_setopt($ch, CURLOPT_URL, $url);
423
		curl_setopt($ch, CURLOPT_POST, true);
424
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
425
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
14408 anikendra 426
 
14409 anikendra 427
		// Disabling SSL Certificate support temporarly
428
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
14408 anikendra 429
 
14409 anikendra 430
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
14408 anikendra 431
 
14409 anikendra 432
		// Execute post
433
		$result = curl_exec($ch);
434
		if ($result === FALSE) {
435
		    die('Curl failed: ' . curl_error($ch));
436
		}
14776 anikendra 437
		$res = json_decode($result,1);
438
		$this->loadModel('Pushnotification');
439
		$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
440
		$this->Pushnotification->create();
441
		$this->Pushnotification->save($data);
14409 anikendra 442
		// Close connection
443
		curl_close($ch);
14770 anikendra 444
		$this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'notifiactions');
14409 anikendra 445
	}
14408 anikendra 446
 
447
	public function admin_index() {		
13532 anikendra 448
		$this->User->recursive = 0;
14395 anikendra 449
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
450
		$this->Paginator->settings = $options;
451
		$users = $this->Paginator->paginate();
13532 anikendra 452
		$groups = $this->User->Group->find('list');
453
		$this->set(compact('groups','users'));
454
	}
455
 
456
/**
457
 * admin_view method
458
 *
459
 * @throws NotFoundException
460
 * @param string $id
461
 * @return void
462
 */
463
	public function admin_view($id = null) {
464
		$this->User->id = $id;
465
		if (!$this->User->exists()) {
466
			throw new NotFoundException(__('Invalid user'));
467
		}
468
		$this->set('user', $this->User->read(null, $id));
469
	}
470
 
471
/**
472
 * admin_add method
473
 *
474
 * @return void
475
 */
476
	public function admin_add() {
477
		if ($this->request->is('post')) {
478
			$this->User->create();
479
			if ($this->User->save($this->request->data)) {
480
				$this->Session->setFlash(__('The user has been saved'));
481
				$this->redirect(array('action' => 'index'));
482
			} else {
483
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
484
			}
485
		}
486
		$groups = $this->User->Group->find('list');
487
		$this->set(compact('groups'));
488
	}
489
 
490
/**
491
 * admin_edit method
492
 *
493
 * @throws NotFoundException
494
 * @param string $id
495
 * @return void
496
 */
497
	public function admin_edit($id = null) {
498
		$this->User->id = $id;
499
		if (!$this->User->exists()) {
500
			throw new NotFoundException(__('Invalid user'));
501
		}
502
		if ($this->request->is('post') || $this->request->is('put')) {
503
			if ($this->User->save($this->request->data)) {
504
				$this->Session->setFlash(__('The user has been saved'));
505
				$this->redirect(array('action' => 'index'));
506
			} else {
507
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
508
			}
509
		} else {
510
			$this->request->data = $this->User->read(null, $id);
511
		}
512
		$groups = $this->User->Group->find('list');
513
		$this->set(compact('groups'));
514
	}
515
 
516
/**
517
 * admin_delete method
518
 *
519
 * @throws MethodNotAllowedException
520
 * @throws NotFoundException
521
 * @param string $id
522
 * @return void
523
 */
524
	public function admin_delete($id = null) {
525
		if (!$this->request->is('post')) {
526
			throw new MethodNotAllowedException();
527
		}
528
		$this->User->id = $id;
529
		if (!$this->User->exists()) {
530
			throw new NotFoundException(__('Invalid user'));
531
		}
532
		if ($this->User->delete()) {
533
			$this->Session->setFlash(__('User deleted'));
534
			$this->redirect(array('action' => 'index'));
535
		}
536
		$this->Session->setFlash(__('User was not deleted'));
537
		$this->redirect(array('action' => 'index'));
538
	}
539
 
540
	public function dashboard() {
541
		App::uses('CakeTime', 'Utility');
542
		$user = $this->User->read(null,$this->Auth->user('id'));
543
		$this->set('user',$user);
544
		$this->set('title_for_layout', "Dashboard");
545
	}
546
 
547
/**
548
* user authentication funtions
549
*/
550
	public function register() {
551
		$referrer = $this->request->query('referrer');
552
		$this->log('referrer = '.$referrer);
553
		$this->Cookie->write('referrer',$referrer);
554
		$this->layout = 'auth';
555
		$this->set('title_for_layout','Register your free letushaggle.com account');
556
		$this->SignMeUp->register();
557
	}
558
 
559
	public function activate() {
13714 anikendra 560
		$this->layout = 'auth';
13532 anikendra 561
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 562
		$this->SignMeUp->activate();
13532 anikendra 563
	}
564
 
565
	public function forgotten_password() {
13714 anikendra 566
		$this->layout = 'auth';
13532 anikendra 567
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 568
		$this->SignMeUp->forgottenPassword();
13532 anikendra 569
	}	
570
 
571
	public function login() {
572
		$this->layout = 'auth';
573
		if (!empty($this->data['User']['next'])) {
574
		    $next = $this->data['User']['next'];
575
		    $this->Session->write('next', $next);
576
		} elseif (!empty($this->params['url']['next'])) {
577
		    $next = $this->params['url']['next'];
578
		    $this->Session->write('next', $next);
579
		}
580
		if ($this->Auth->login()) {
581
		    $next = $this->Session->read('next');
582
		    if (!empty($next)) {
583
				header('location:' . $next);
584
				exit();
585
		    }
13736 anikendra 586
		    $user = $this->User->read(null, $this->Auth->User('id'));		 
13532 anikendra 587
		    if ($user['User']['group_id'] == 2) {
588
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
589
				exit();
590
		    }
591
			if ($user['User']['group_id'] == 1) {
13736 anikendra 592
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 593
				exit();
594
			}
595
		} else {
596
		    if (!empty($this->data)) {                
13736 anikendra 597
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 598
		    }
599
		}
600
		$this->set('title_for_layout', "Login to letushaggle.com");
601
	}
602
 
603
	public function logout() {
604
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
605
		$this->redirect($this->Auth->logout());
606
	}
607
 
608
	public function updatetimezone() {
609
		$this->layout = 'ajax';		
610
		$timezone = $_GET['tz'];
611
		Configure::load('constant');
612
		$timeZones = Configure::read("timeZones");
613
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
614
		if($this->User->query($query)){
615
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
616
		}else{
617
			$result = array('success' => false);
618
		}
619
		$this->set('result',$result);
620
	}
621
 
13736 anikendra 622
	public function verifymobile() {
623
		$this->layout = 'innerpages';
624
	}
13532 anikendra 625
 
13736 anikendra 626
	public function getdial2verifynumber() {
627
		$TelNumber=substr($this->request->data("phone_number"),-10);
628
 
629
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
630
	    $API_KEY = Configure::read("dial2verifyapikey");
631
 
632
	  	//Get API Image Response
633
	    $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";
634
	    // $json=file_get_contents($APIUrl);
635
	    $json = json_encode($this->make_request($url,null));
636
	  	$this->response->type('json');
637
		$this->layout = 'ajax';
638
	    echo($json);die;
639
	}
640
 
641
	public function getdial2verifystatus() { 
642
 
643
		$SID=$_REQUEST["SID"];
644
 
645
	    $json = array();
646
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
647
 
648
	   // Make a call to Dial2Verify API & Parse The JSON Response
649
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
650
		$RequestPayload = $this->make_request($VerificationCall,null);
651
		// $RequestPayload = json_decode($response,true);
652
 
653
		$VerifStatus=$RequestPayload["VerificationStatus"];
654
 
655
		$json["VerificationStatus"]=$VerifStatus;
656
 
657
	   	$this->response->type('json');
658
		$this->layout = 'ajax';
659
	    echo(json_encode($json));die;
660
	}
661
 
662
	public function skipmobileverification() {
663
		$this->Session->write('skipmobileverification',1);
13739 anikendra 664
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 665
	}
666
 
667
	public function reauthenticate($userId) {
668
		$user = $this->User->read(null,$userId);
669
		$this->Auth->login($user['User']);
670
		$json = array('success'=>true);
671
		$this->response->type('json');
672
		$this->layout = 'ajax';
14150 anikendra 673
	    echo(json_encode($json));die;
13736 anikendra 674
	}
13739 anikendra 675
}