Subversion Repositories SmartDukaan

Rev

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