Subversion Repositories SmartDukaan

Rev

Rev 15414 | Rev 15477 | 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;
15475 anikendra 298
	        		}	        		
14768 anikendra 299
	        	}	        		
14770 anikendra 300
	        	if($updateRequired){
301
		            if ($this->User->save($this->request->data)) {
15475 anikendra 302
		            	if($this->request->data['activated'] == 1) {
303
		            		//Call user activation api
304
		        			$this->markUserActivated($id);
305
		            	}			        		
14770 anikendra 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
 
15414 manas 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');
15414 manas 462
	}*/
463
	private function send_push_notification($registatoin_ids, $message, $user_id) {
464
                $msg = array(
465
                    'message'       => $message['message'],
466
                    'cid'               => $message['cid'],
467
                    'title'         => $message['title'],
468
                    'type'              => $message['type'],
469
                    'url'                   => $message['url'],
470
                    // 'expiresat'          => strtotime($message['expiresat']),
471
                    'vibrate'       => 1,
472
                    'sound'         => 1,
473
                    'largeIcon'     => 'large_icon',
474
                    'smallIcon'     => 'small_icon'
475
                );
476
                // Set POST variables
477
                $url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 478
 
15414 manas 479
                $fields = array(
480
                    'registration_ids' => $registatoin_ids,
481
                    'data' => $msg,
482
                );
483
                $headers = array(
484
                    'Authorization: key=' . Configure::read('googleapikey'),
485
                    'Content-Type: application/json'
486
                );
487
                //print_r($headers);
488
                // Open connection
489
                $ch = curl_init();
490
 
491
                // Set the url, number of POST vars, POST data
492
                curl_setopt($ch, CURLOPT_URL, $url);
493
                curl_setopt($ch, CURLOPT_POST, true);
494
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
495
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
496
 
497
                // Disabling SSL Certificate support temporarly
498
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
499
 
500
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
501
 
502
                // Execute post
503
                $result = curl_exec($ch);
504
                if ($result === FALSE) {
505
                    die('Curl failed: ' . curl_error($ch));
506
                }
507
                $res = json_decode($result,1);
508
 
509
                $this->loadModel('Pushnotification');
510
                if($res['success']==1){
511
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>'success');
512
				}else if($res['success']==0){
513
					$error_message=$res['results'][0]['error'];
514
					$sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
515
					$resultData=$this->GcmUser->query($sqlQuery);
516
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>$error_message);
517
				}
518
                #$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
519
                $this->Pushnotification->create();
520
                $this->Pushnotification->save($data);
521
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($data,1),'pushnotifications');
522
                // Close connection
523
                curl_close($ch);
524
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
525
        }
526
 
14408 anikendra 527
	public function admin_index() {		
13532 anikendra 528
		$this->User->recursive = 0;
14395 anikendra 529
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
530
		$this->Paginator->settings = $options;
531
		$users = $this->Paginator->paginate();
13532 anikendra 532
		$groups = $this->User->Group->find('list');
533
		$this->set(compact('groups','users'));
534
	}
535
 
536
/**
537
 * admin_view method
538
 *
539
 * @throws NotFoundException
540
 * @param string $id
541
 * @return void
542
 */
543
	public function admin_view($id = null) {
544
		$this->User->id = $id;
545
		if (!$this->User->exists()) {
546
			throw new NotFoundException(__('Invalid user'));
547
		}
548
		$this->set('user', $this->User->read(null, $id));
549
	}
550
 
551
/**
552
 * admin_add method
553
 *
554
 * @return void
555
 */
556
	public function admin_add() {
557
		if ($this->request->is('post')) {
558
			$this->User->create();
559
			if ($this->User->save($this->request->data)) {
560
				$this->Session->setFlash(__('The user has been saved'));
561
				$this->redirect(array('action' => 'index'));
562
			} else {
563
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
564
			}
565
		}
566
		$groups = $this->User->Group->find('list');
567
		$this->set(compact('groups'));
568
	}
569
 
570
/**
571
 * admin_edit method
572
 *
573
 * @throws NotFoundException
574
 * @param string $id
575
 * @return void
576
 */
577
	public function admin_edit($id = null) {
578
		$this->User->id = $id;
579
		if (!$this->User->exists()) {
580
			throw new NotFoundException(__('Invalid user'));
581
		}
582
		if ($this->request->is('post') || $this->request->is('put')) {
583
			if ($this->User->save($this->request->data)) {
584
				$this->Session->setFlash(__('The user has been saved'));
585
				$this->redirect(array('action' => 'index'));
586
			} else {
587
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
588
			}
589
		} else {
590
			$this->request->data = $this->User->read(null, $id);
591
		}
592
		$groups = $this->User->Group->find('list');
593
		$this->set(compact('groups'));
594
	}
595
 
596
/**
597
 * admin_delete method
598
 *
599
 * @throws MethodNotAllowedException
600
 * @throws NotFoundException
601
 * @param string $id
602
 * @return void
603
 */
15217 anikendra 604
/*
13532 anikendra 605
	public function admin_delete($id = null) {
606
		if (!$this->request->is('post')) {
607
			throw new MethodNotAllowedException();
608
		}
609
		$this->User->id = $id;
610
		if (!$this->User->exists()) {
611
			throw new NotFoundException(__('Invalid user'));
612
		}
613
		if ($this->User->delete()) {
614
			$this->Session->setFlash(__('User deleted'));
615
			$this->redirect(array('action' => 'index'));
616
		}
617
		$this->Session->setFlash(__('User was not deleted'));
618
		$this->redirect(array('action' => 'index'));
619
	}
15217 anikendra 620
*/
13532 anikendra 621
 
15217 anikendra 622
	public function admin_search() {
623
		$type = $this->request->query('type');
624
		$search = $this->request->query('search');
625
		$this->User->recursive = -1;
626
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
15232 anikendra 627
		if($type == 'unactivated'){
628
			$options['conditions'] = array('activated' =>0);
629
		}
630
		else if(!empty($type) && !empty($search)){
631
			$options['conditions'] = array($type.' LIKE '=>"%$search%");			
632
		}else{
633
			$options['conditions'] = array('date(created)'=>date('Y-m-d',time()));			
15217 anikendra 634
		}		
15232 anikendra 635
		$this->Paginator->settings = $options;
636
		$users = $this->Paginator->paginate();		
15380 anikendra 637
 
638
		$this->set(compact('users'));	
15217 anikendra 639
	}
640
 
13532 anikendra 641
	public function dashboard() {
642
		App::uses('CakeTime', 'Utility');
643
		$user = $this->User->read(null,$this->Auth->user('id'));
644
		$this->set('user',$user);
645
		$this->set('title_for_layout', "Dashboard");
646
	}
647
 
648
/**
649
* user authentication funtions
650
*/
651
	public function register() {
652
		$referrer = $this->request->query('referrer');
653
		$this->log('referrer = '.$referrer);
654
		$this->Cookie->write('referrer',$referrer);
655
		$this->layout = 'auth';
656
		$this->set('title_for_layout','Register your free letushaggle.com account');
657
		$this->SignMeUp->register();
658
	}
659
 
660
	public function activate() {
13714 anikendra 661
		$this->layout = 'auth';
13532 anikendra 662
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 663
		$this->SignMeUp->activate();
13532 anikendra 664
	}
665
 
666
	public function forgotten_password() {
13714 anikendra 667
		$this->layout = 'auth';
13532 anikendra 668
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 669
		$this->SignMeUp->forgottenPassword();
13532 anikendra 670
	}	
671
 
672
	public function login() {
673
		$this->layout = 'auth';
674
		if (!empty($this->data['User']['next'])) {
675
		    $next = $this->data['User']['next'];
676
		    $this->Session->write('next', $next);
677
		} elseif (!empty($this->params['url']['next'])) {
678
		    $next = $this->params['url']['next'];
679
		    $this->Session->write('next', $next);
680
		}
681
		if ($this->Auth->login()) {
682
		    $next = $this->Session->read('next');
683
		    if (!empty($next)) {
684
				header('location:' . $next);
685
				exit();
686
		    }
15188 anikendra 687
		    $user = $this->User->read(null, $this->Auth->User('id'));		 		    
13532 anikendra 688
			if ($user['User']['group_id'] == 1) {
13736 anikendra 689
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 690
				exit();
691
			}
15188 anikendra 692
			else if ($user['User']['group_id'] >= 2) {
693
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
694
				exit();
695
		    }
13532 anikendra 696
		} else {
697
		    if (!empty($this->data)) {                
13736 anikendra 698
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 699
		    }
700
		}
701
		$this->set('title_for_layout', "Login to letushaggle.com");
702
	}
703
 
704
	public function logout() {
705
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
706
		$this->redirect($this->Auth->logout());
707
	}
708
 
709
	public function updatetimezone() {
710
		$this->layout = 'ajax';		
711
		$timezone = $_GET['tz'];
712
		Configure::load('constant');
713
		$timeZones = Configure::read("timeZones");
714
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
715
		if($this->User->query($query)){
716
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
717
		}else{
718
			$result = array('success' => false);
719
		}
720
		$this->set('result',$result);
721
	}
722
 
13736 anikendra 723
	public function verifymobile() {
724
		$this->layout = 'innerpages';
725
	}
13532 anikendra 726
 
13736 anikendra 727
	public function getdial2verifynumber() {
728
		$TelNumber=substr($this->request->data("phone_number"),-10);
729
 
730
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
731
	    $API_KEY = Configure::read("dial2verifyapikey");
732
 
733
	  	//Get API Image Response
734
	    $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";
735
	    // $json=file_get_contents($APIUrl);
736
	    $json = json_encode($this->make_request($url,null));
737
	  	$this->response->type('json');
738
		$this->layout = 'ajax';
739
	    echo($json);die;
740
	}
741
 
742
	public function getdial2verifystatus() { 
743
 
744
		$SID=$_REQUEST["SID"];
745
 
746
	    $json = array();
747
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
748
 
749
	   // Make a call to Dial2Verify API & Parse The JSON Response
750
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
751
		$RequestPayload = $this->make_request($VerificationCall,null);
752
		// $RequestPayload = json_decode($response,true);
753
 
754
		$VerifStatus=$RequestPayload["VerificationStatus"];
755
 
756
		$json["VerificationStatus"]=$VerifStatus;
757
 
758
	   	$this->response->type('json');
759
		$this->layout = 'ajax';
760
	    echo(json_encode($json));die;
761
	}
762
 
763
	public function skipmobileverification() {
764
		$this->Session->write('skipmobileverification',1);
13739 anikendra 765
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 766
	}
767
 
768
	public function reauthenticate($userId) {
769
		$user = $this->User->read(null,$userId);
770
		$this->Auth->login($user['User']);
771
		$json = array('success'=>true);
772
		$this->response->type('json');
773
		$this->layout = 'ajax';
14150 anikendra 774
	    echo(json_encode($json));die;
13736 anikendra 775
	}
13739 anikendra 776
}