Subversion Repositories SmartDukaan

Rev

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