Subversion Repositories SmartDukaan

Rev

Rev 15247 | Rev 15380 | 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;
15378 anikendra 301
	        		//Call user activation api
302
        			$this->markUserActivated($id);	        		
14768 anikendra 303
	        	}	        		
14770 anikendra 304
	        	if($updateRequired){
305
		            if ($this->User->save($this->request->data)) {
306
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
307
		            } else {
308
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
309
		            }
310
		        }
13736 anikendra 311
	        }  
312
	    }
313
        $this->set(array(
314
		    'result' => $result,
315
		    '_serialize' => array('result')
316
		)); 
317
		$this->render('/Elements/json');      
13532 anikendra 318
    }
319
 
320
/**
321
 * admin_index method
322
 *
323
 * @return void
324
 */
14408 anikendra 325
 
326
	public function admin_pushnotifications(){
327
		if ($this->request->is('post')) {
328
			$sql = $this->request->data['User']['sql'];
329
			if(!empty($sql)){
330
				$users = $this->User->query($sql);
331
				$this->set(compact('users'));
332
			}
333
		}
334
	}
335
 
14445 anikendra 336
	public function generateAffiliateUrl($url,$user_id,$store){
337
		//Get StoreProduct Info		
14428 anikendra 338
		$storeId = $store['Store']['id'];
339
		$prefix = "SHA".$storeId;
340
		$tag = $prefix.time();
341
		if($storeId == 2){				
342
			$url = str_replace('www','m',$url);
343
		} elseif($storeId == 3) {
344
			$url_parts = parse_url($url);
345
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
346
			if(isset($url_parts['query'])) {
347
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
348
			}else{
349
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
350
			}
351
		} elseif($storeId == 4){
14445 anikendra 352
			$next = str_replace('www','m',$url);	
14428 anikendra 353
			$url = $this->getAutoLoginUrl($userId,$next);
354
			$url .= '?utm_source=profitmandi';
355
		}
356
		if( strpos($url, '?') === false ) {
357
			$firstChar = '?';
358
		} else {
359
			$firstChar = '&';
360
		}
361
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
362
		if(!empty($store['Store']['sub_tag_param'])){
363
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
364
		}
365
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
366
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
367
		$this->loadModel('Click');
368
		$this->Click->create();
369
		$this->Click->save($data);
370
		return $url;
371
	}
372
 
14408 anikendra 373
	public function admin_push(){
374
		if ($this->request->is('post')) {
375
			if(empty($this->request->data['userIds'])){
376
				$this->Session->setFlash(__('Please choose a few users'));
377
				$this->redirect(array('action' => 'admin_pushnotifications'));
378
			}else{
14824 anikendra 379
				$this->log(print_r($this->request->data,1),'pushnotifications');
14445 anikendra 380
				$message = $this->request->data['User'];
14776 anikendra 381
				$this->loadModel('NotificationCampaign');
382
				$this->NotificationCampaign->create();
14781 anikendra 383
				$data = array('name'=>$message['name'],'title'=>$message['title'],'type'=>$message['type'],'message'=>$message['message'],'url'=>$message['url'],'expiresat'=>$message['expiresat']);
14776 anikendra 384
				if($this->NotificationCampaign->save($data)){
385
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
386
				} else{
387
					debug($this->NotificationCampaign->validationErrors);
388
					$message['cid'] = $message['name'];
389
				}
14445 anikendra 390
				if($message['type'] == 'url' && !empty($message['url'])) {
391
					$url = $message['url'];
392
					$this->loadModel('Store');
393
					$store = $this->Store->getByUrl($url);					
394
				}				
14408 anikendra 395
				$this->loadModel('GcmUser');
396
				foreach ($this->request->data['userIds'] as $key => $value) {					
14770 anikendra 397
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
14408 anikendra 398
					$gcmUser = $this->GcmUser->find('first',$options);
399
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
14445 anikendra 400
					// $message = array('message'=>$this->request->data['User']['message']);					
401
					if($message['type'] == 'url' && !empty($message['url'])) {
402
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14428 anikendra 403
					}					
404
					$this->send_push_notification($regIds,$message,$value);
14408 anikendra 405
				}
406
			}
407
		}
408
	}
409
 
14428 anikendra 410
	private function send_push_notification($registatoin_ids, $message, $user_id) {
14409 anikendra 411
		$msg = array(
412
		    'message'       => $message['message'],
14776 anikendra 413
		    'cid'       	=> $message['cid'],
14428 anikendra 414
		    'title'         => $message['title'],
415
		    'type'      	=> $message['type'],
416
		    'url'		    => $message['url'],
14782 anikendra 417
		    // 'expiresat'	    => strtotime($message['expiresat']),
14409 anikendra 418
		    'vibrate'       => 1,
419
		    'sound'         => 1,
420
		    'largeIcon'     => 'large_icon',
421
		    'smallIcon'     => 'small_icon'
422
		);
423
		// Set POST variables
424
		$url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 425
 
14409 anikendra 426
		$fields = array(
427
		    'registration_ids' => $registatoin_ids,
428
		    'data' => $msg,
429
		);
430
		$headers = array(
431
		    'Authorization: key=' . Configure::read('googleapikey'),
432
		    'Content-Type: application/json'
433
		);
434
		//print_r($headers);
435
		// Open connection
436
		$ch = curl_init();
14408 anikendra 437
 
14409 anikendra 438
		// Set the url, number of POST vars, POST data
439
		curl_setopt($ch, CURLOPT_URL, $url);
440
		curl_setopt($ch, CURLOPT_POST, true);
441
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
442
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
14408 anikendra 443
 
14409 anikendra 444
		// Disabling SSL Certificate support temporarly
445
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
14408 anikendra 446
 
14409 anikendra 447
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
14408 anikendra 448
 
14409 anikendra 449
		// Execute post
450
		$result = curl_exec($ch);
451
		if ($result === FALSE) {
452
		    die('Curl failed: ' . curl_error($ch));
453
		}
14776 anikendra 454
		$res = json_decode($result,1);
455
		$this->loadModel('Pushnotification');
456
		$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
457
		$this->Pushnotification->create();
458
		$this->Pushnotification->save($data);
14409 anikendra 459
		// Close connection
460
		curl_close($ch);
15085 anikendra 461
		$this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
14409 anikendra 462
	}
14408 anikendra 463
 
464
	public function admin_index() {		
13532 anikendra 465
		$this->User->recursive = 0;
14395 anikendra 466
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
467
		$this->Paginator->settings = $options;
468
		$users = $this->Paginator->paginate();
13532 anikendra 469
		$groups = $this->User->Group->find('list');
470
		$this->set(compact('groups','users'));
471
	}
472
 
473
/**
474
 * admin_view method
475
 *
476
 * @throws NotFoundException
477
 * @param string $id
478
 * @return void
479
 */
480
	public function admin_view($id = null) {
481
		$this->User->id = $id;
482
		if (!$this->User->exists()) {
483
			throw new NotFoundException(__('Invalid user'));
484
		}
485
		$this->set('user', $this->User->read(null, $id));
486
	}
487
 
488
/**
489
 * admin_add method
490
 *
491
 * @return void
492
 */
493
	public function admin_add() {
494
		if ($this->request->is('post')) {
495
			$this->User->create();
496
			if ($this->User->save($this->request->data)) {
497
				$this->Session->setFlash(__('The user has been saved'));
498
				$this->redirect(array('action' => 'index'));
499
			} else {
500
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
501
			}
502
		}
503
		$groups = $this->User->Group->find('list');
504
		$this->set(compact('groups'));
505
	}
506
 
507
/**
508
 * admin_edit method
509
 *
510
 * @throws NotFoundException
511
 * @param string $id
512
 * @return void
513
 */
514
	public function admin_edit($id = null) {
515
		$this->User->id = $id;
516
		if (!$this->User->exists()) {
517
			throw new NotFoundException(__('Invalid user'));
518
		}
519
		if ($this->request->is('post') || $this->request->is('put')) {
520
			if ($this->User->save($this->request->data)) {
521
				$this->Session->setFlash(__('The user has been saved'));
522
				$this->redirect(array('action' => 'index'));
523
			} else {
524
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
525
			}
526
		} else {
527
			$this->request->data = $this->User->read(null, $id);
528
		}
529
		$groups = $this->User->Group->find('list');
530
		$this->set(compact('groups'));
531
	}
532
 
533
/**
534
 * admin_delete method
535
 *
536
 * @throws MethodNotAllowedException
537
 * @throws NotFoundException
538
 * @param string $id
539
 * @return void
540
 */
15217 anikendra 541
/*
13532 anikendra 542
	public function admin_delete($id = null) {
543
		if (!$this->request->is('post')) {
544
			throw new MethodNotAllowedException();
545
		}
546
		$this->User->id = $id;
547
		if (!$this->User->exists()) {
548
			throw new NotFoundException(__('Invalid user'));
549
		}
550
		if ($this->User->delete()) {
551
			$this->Session->setFlash(__('User deleted'));
552
			$this->redirect(array('action' => 'index'));
553
		}
554
		$this->Session->setFlash(__('User was not deleted'));
555
		$this->redirect(array('action' => 'index'));
556
	}
15217 anikendra 557
*/
13532 anikendra 558
 
15217 anikendra 559
	public function admin_search() {
560
		$type = $this->request->query('type');
561
		$search = $this->request->query('search');
562
		$this->User->recursive = -1;
563
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
15232 anikendra 564
		if($type == 'unactivated'){
565
			$options['conditions'] = array('activated' =>0);
566
		}
567
		else if(!empty($type) && !empty($search)){
568
			$options['conditions'] = array($type.' LIKE '=>"%$search%");			
569
		}else{
570
			$options['conditions'] = array('date(created)'=>date('Y-m-d',time()));			
15217 anikendra 571
		}		
15232 anikendra 572
		$this->Paginator->settings = $options;
573
		$users = $this->Paginator->paginate();		
15378 anikendra 574
		$sql = "SELECT DATE( created ) , referrer, COUNT( id ) FROM users WHERE DATEDIFF( NOW( ) , created ) =1 AND referrer IS NOT NULL GROUP BY DATE( created ) , referrer";
575
		$lastdayactivations = $this->User->query($sql);
576
		$this->set(compact('users','lastdayactivations'));	
15217 anikendra 577
	}
578
 
13532 anikendra 579
	public function dashboard() {
580
		App::uses('CakeTime', 'Utility');
581
		$user = $this->User->read(null,$this->Auth->user('id'));
582
		$this->set('user',$user);
583
		$this->set('title_for_layout', "Dashboard");
584
	}
585
 
586
/**
587
* user authentication funtions
588
*/
589
	public function register() {
590
		$referrer = $this->request->query('referrer');
591
		$this->log('referrer = '.$referrer);
592
		$this->Cookie->write('referrer',$referrer);
593
		$this->layout = 'auth';
594
		$this->set('title_for_layout','Register your free letushaggle.com account');
595
		$this->SignMeUp->register();
596
	}
597
 
598
	public function activate() {
13714 anikendra 599
		$this->layout = 'auth';
13532 anikendra 600
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 601
		$this->SignMeUp->activate();
13532 anikendra 602
	}
603
 
604
	public function forgotten_password() {
13714 anikendra 605
		$this->layout = 'auth';
13532 anikendra 606
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 607
		$this->SignMeUp->forgottenPassword();
13532 anikendra 608
	}	
609
 
610
	public function login() {
611
		$this->layout = 'auth';
612
		if (!empty($this->data['User']['next'])) {
613
		    $next = $this->data['User']['next'];
614
		    $this->Session->write('next', $next);
615
		} elseif (!empty($this->params['url']['next'])) {
616
		    $next = $this->params['url']['next'];
617
		    $this->Session->write('next', $next);
618
		}
619
		if ($this->Auth->login()) {
620
		    $next = $this->Session->read('next');
621
		    if (!empty($next)) {
622
				header('location:' . $next);
623
				exit();
624
		    }
15188 anikendra 625
		    $user = $this->User->read(null, $this->Auth->User('id'));		 		    
13532 anikendra 626
			if ($user['User']['group_id'] == 1) {
13736 anikendra 627
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 628
				exit();
629
			}
15188 anikendra 630
			else if ($user['User']['group_id'] >= 2) {
631
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
632
				exit();
633
		    }
13532 anikendra 634
		} else {
635
		    if (!empty($this->data)) {                
13736 anikendra 636
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 637
		    }
638
		}
639
		$this->set('title_for_layout', "Login to letushaggle.com");
640
	}
641
 
642
	public function logout() {
643
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
644
		$this->redirect($this->Auth->logout());
645
	}
646
 
647
	public function updatetimezone() {
648
		$this->layout = 'ajax';		
649
		$timezone = $_GET['tz'];
650
		Configure::load('constant');
651
		$timeZones = Configure::read("timeZones");
652
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
653
		if($this->User->query($query)){
654
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
655
		}else{
656
			$result = array('success' => false);
657
		}
658
		$this->set('result',$result);
659
	}
660
 
13736 anikendra 661
	public function verifymobile() {
662
		$this->layout = 'innerpages';
663
	}
13532 anikendra 664
 
13736 anikendra 665
	public function getdial2verifynumber() {
666
		$TelNumber=substr($this->request->data("phone_number"),-10);
667
 
668
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
669
	    $API_KEY = Configure::read("dial2verifyapikey");
670
 
671
	  	//Get API Image Response
672
	    $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";
673
	    // $json=file_get_contents($APIUrl);
674
	    $json = json_encode($this->make_request($url,null));
675
	  	$this->response->type('json');
676
		$this->layout = 'ajax';
677
	    echo($json);die;
678
	}
679
 
680
	public function getdial2verifystatus() { 
681
 
682
		$SID=$_REQUEST["SID"];
683
 
684
	    $json = array();
685
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
686
 
687
	   // Make a call to Dial2Verify API & Parse The JSON Response
688
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
689
		$RequestPayload = $this->make_request($VerificationCall,null);
690
		// $RequestPayload = json_decode($response,true);
691
 
692
		$VerifStatus=$RequestPayload["VerificationStatus"];
693
 
694
		$json["VerificationStatus"]=$VerifStatus;
695
 
696
	   	$this->response->type('json');
697
		$this->layout = 'ajax';
698
	    echo(json_encode($json));die;
699
	}
700
 
701
	public function skipmobileverification() {
702
		$this->Session->write('skipmobileverification',1);
13739 anikendra 703
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 704
	}
705
 
706
	public function reauthenticate($userId) {
707
		$user = $this->User->read(null,$userId);
708
		$this->Auth->login($user['User']);
709
		$json = array('success'=>true);
710
		$this->response->type('json');
711
		$this->layout = 'ajax';
14150 anikendra 712
	    echo(json_encode($json));die;
13736 anikendra 713
	}
13739 anikendra 714
}