Subversion Repositories SmartDukaan

Rev

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