Subversion Repositories SmartDukaan

Rev

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