Subversion Repositories SmartDukaan

Rev

Rev 14300 | Rev 14394 | 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
 */
8
class UsersController extends AppController {
9
 
10
	public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie');
11
 
12
    public function beforeFilter() {
13
    	parent::beforeFilter();
14
    	// $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
15
    	$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display','home');
14019 anikendra 16
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet')); 
13736 anikendra 17
		$this->Cookie->name = 'profittill';
18
		$this->Cookie->time = 86400*30; 
19
		$this->Cookie->path = '/';
20
		$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#H23s~#^';
21
		$this->Cookie->httpOnly = true;
13532 anikendra 22
    }
23
 
24
	public function bookmarklet() {
13714 anikendra 25
		$this->set('title_for_layout','Profittill Bookmarklet');
13532 anikendra 26
	}
27
 
14019 anikendra 28
	public function mywallet() {
29
		$userId = $this->request->query('user_id');
14150 anikendra 30
		if(isset($userId) && !empty($userId)){	
31
			$next = "&next=/my-wallet";					
32
			$redirectUrl = $this->getAutoLoginUrl($userId,$next);
14019 anikendra 33
			header('location:'.$redirectUrl);
34
			exit();
35
		}
36
	}
37
 
13740 anikendra 38
	public function mine() {
13758 anikendra 39
		$this->response->type('json');
40
		$this->layout = 'ajax';
13740 anikendra 41
		$userId = $this->request->query('user_id');
42
		if(isset($userId) && !empty($userId)){
43
			$this->loadModel('User');
13758 anikendra 44
			$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',
45
				'city','state','pincode','referrer'),'recursive'=>-1);
13763 anikendra 46
			$user = $this->User->find('first',$options);
47
			$result = $user['User'];
13740 anikendra 48
		}
13758 anikendra 49
		$this->set(array(
50
		    'result' => $result,
51
		    '_serialize' => array('result')
52
		)); 
53
		$this->render('/Elements/json'); 
13740 anikendra 54
	}
55
 
13532 anikendra 56
	function registertwitteruser(){
57
		$this->twitterObj->setToken($_GET['oauth_token']);
58
		$token = $this->twitterObj->getAccessToken();
59
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
60
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
61
		$data = array();
62
		$data['twitter_id'] = $twitterInfo->id;		
63
		$this->Session->write('twtusername',$twitterInfo->screen_name);
64
		$data['twitter_token'] = $token->oauth_token;
65
		$data['twitter_secret'] = $token->oauth_token_secret;
66
		$data['twitter_screen_name'] = $twitterInfo->screen_name;					
67
		$data['active'] = 1;
68
 
69
		$id = $this->Auth->user('id');
70
		if(!isset($id) || $id == ''){
71
		//	$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
72
			$user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
73
			//if($count<1){
74
			if(empty($user)){
75
				$this->User->create();
76
				$this->User->save($data);
77
//				$dbuser = $this->User->read(null,$this->User->id);
78
				$this->Auth->login($this->User->data);
79
			}else{
80
		//		$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
81
				$this->Auth->login($user['User']);
82
			}
83
		}else{
84
			//$data['id'] = $this->Auth->user('id');
85
			$user = $this->Auth->user;
86
//			$this->User->save($data);
87
//			$this->Auth->login($data);
88
		}                
89
		$user = $this->User->read(null, $this->Auth->User('id'));
90
		if ($user['User']['group_id'] == 1) {
91
			//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
92
			header('location:users/dashboard?userid='.$this->Auth->user('id'));
93
			exit();
94
		}
95
		elseif ($user['User']['group_id'] == 2) {
96
			$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
97
			exit();
98
		}
99
	}
100
 
101
    public function checkfbuser($accessToken=null){
102
		$sessionState = $this->Session->read('state');
103
		if($sessionState != $_GET['state']) {
104
			$this->redirect(array('controller'=>'users','action'=>'login'));
105
		}
106
		else {
107
			if(isset($_GET['code'])){
108
				$code = $_GET['code'];
109
				$facebookConfig = Configure::read("Facebook");		
110
				$token_url = "https://graph.facebook.com/oauth/access_token?"
111
			       . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
112
			       . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;
113
 
114
			    $response = file_get_contents($token_url);
115
			    $params = null;
116
			    parse_str($response, $params);
117
			    $accessToken = $params['access_token'];
118
			}else{
119
				$this->redirect(array('controller'=>'users','action'=>'login'));
120
			}
121
		}
122
		$this->User->recursive = -1;
123
		if (!$accessToken) {
124
		    $this->redirect(array('controller'=>'users','action'=>'login'));
125
		    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
126
		}        
127
		if (isset($accessToken) && $accessToken != 'undefined') {			
128
 
129
		    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;
130
 
131
		    $user = json_decode(file_get_contents($graph_url));
132
			$this->log("FB user = ".print_r($user,1),'fb');
133
		    if (!empty($user)) {
134
			if (!$this->isAuthorized()) {
135
			    $id = $this->User->checkFbUser($user,$accessToken);
136
				$dbuser = $this->User->findById($id);
137
			    $this->Session->write('facebook_id',$user->id);
138
				$this->Auth->login($dbuser['User']);
139
				if($this->Auth->login()){
140
					$this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
141
				}
142
			    $next = $this->Session->read('next');
143
				$this->log("next= ".$next."\n",'fb');
144
 
145
			    if (!empty($next)) {
146
					header('Location:' . $next);
147
					exit();
148
			    }else {
149
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
150
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
151
					exit();
152
			            }
153
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
154
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
155
					exit();
156
				} else {                	
157
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
158
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
159
					exit();
160
				}
161
		    }
162
		}
163
    }
164
 
165
	public function uploadavatar(){
166
		$this->log(print_r($_FILES,1),'debug');
167
		$path = "img/avatars/";
168
		$valid_formats = array("jpg", "png", "gif", "bmp");
169
		if ($this->request->is('post')) {
170
			$name = $_FILES['photoimg']['name'];
171
			$size = $_FILES['photoimg']['size'];
172
 
173
			if(strlen($name))
174
				{
175
					list($txt, $ext) = explode(".", $name);
176
					if(in_array($ext,$valid_formats))
177
					{
178
					if($size<(1024*1024))
179
						{
180
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
181
							$tmp = $_FILES['photoimg']['tmp_name'];
182
							if(move_uploaded_file($tmp, $path.$actual_image_name))
183
								{
184
									echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
185
									echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
186
								}
187
							else
188
								echo __('Upload Failed');
189
						}
190
						else
191
						echo __("Maximum allowed image file size is 1 MB");					
192
						}
193
						else
194
						echo __("Invalid file format");	
195
				}
196
			else
197
				echo __("Please select image");
198
			exit;
199
		}
200
	}
201
 
202
    function checkemail() {
203
        $this->User->recursive = -1;
204
        $this->layout = 'ajax';
205
        if (!empty($this->params['url']['data']['User']['email'])) {
206
            $username = $this->params['url']['data']['User']['email'];
207
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
208
            $username = $this->params['url']['data']['Doctor']['email'];
209
        } else {
210
            $result = false;
211
            $this->set('result', $result);
212
        }
213
        if ($this->Auth->user('id') != null) {
214
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
215
        } else {
216
            $conditions = array('User.email' => $username);
217
        }
218
        $count = $this->User->find('count', array('conditions' => $conditions));
219
        if ($count > 0) {
220
            $result = false;
221
        } else {
222
            $result = true;
223
        }
224
        $this->set('result', $result);
225
    }
226
 
227
/**
228
 * view method
229
 *
230
 * @throws NotFoundException
231
 * @param string $id
232
 * @return void
233
 */
234
	public function view($id = null) {
235
		$this->response->type('json');
236
		$this->layout = 'ajax';
237
		$callback = $this->request->query('callback');
238
		$this->User->id = $id;
239
		if (!$this->User->exists()) {
240
			throw new NotFoundException(__('Invalid user'));
241
		}
242
		$user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
243
		$result = array('user'=>$user);
244
		$this->set(array(
245
		    'result' => $result,
246
		    'callback' => $callback,
247
		    '_serialize' => array('result')
248
		));
13736 anikendra 249
		$this->render('/Elements/json');
13532 anikendra 250
	}
251
/**
252
 * edit method
253
 *
254
 * @throws NotFoundException
255
 * @param string $id
256
 * @return void
257
 */
258
 
13736 anikendra 259
    public function edit($id = null) {
13900 anikendra 260
	$this->log(print_r($this->request->data,1),'mydetails');
14300 anikendra 261
	$this->response->type('json');
13900 anikendra 262
	$this->layout = 'ajax';
263
	$this->User->recursive = -1;
13736 anikendra 264
        if (!$this->User->exists($id)) {
14300 anikendra 265
			$result = array('success'=>false,'message'=>'Invalid user');
13736 anikendra 266
		} else {
267
	        if ($this->request->is('post') || $this->request->is('put')) {
14316 anikendra 268
               		if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])){
269
				$options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
270
				$oldMobile = $this->User->find('first',$options);
271
				if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
272
		        		$this->request->data['mobile_verified'] = 0;
273
				}
14300 anikendra 274
	        	}
13736 anikendra 275
	            if ($this->User->save($this->request->data)) {
276
	                $result = array('success'=>true,'message'=>'Your profile has been saved');
277
	            } else {
278
	                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
279
	            }
280
	        }  
281
	    }
282
        $this->set(array(
283
		    'result' => $result,
284
		    '_serialize' => array('result')
285
		)); 
286
		$this->render('/Elements/json');      
13532 anikendra 287
    }
288
 
289
/**
290
 * admin_index method
291
 *
292
 * @return void
293
 */
294
	public function admin_index() {
295
		$this->User->recursive = 0;
296
		$users = $this->paginate();
297
		$groups = $this->User->Group->find('list');
298
		$this->set(compact('groups','users'));
299
	}
300
 
301
/**
302
 * admin_view method
303
 *
304
 * @throws NotFoundException
305
 * @param string $id
306
 * @return void
307
 */
308
	public function admin_view($id = null) {
309
		$this->User->id = $id;
310
		if (!$this->User->exists()) {
311
			throw new NotFoundException(__('Invalid user'));
312
		}
313
		$this->set('user', $this->User->read(null, $id));
314
	}
315
 
316
/**
317
 * admin_add method
318
 *
319
 * @return void
320
 */
321
	public function admin_add() {
322
		if ($this->request->is('post')) {
323
			$this->User->create();
324
			if ($this->User->save($this->request->data)) {
325
				$this->Session->setFlash(__('The user has been saved'));
326
				$this->redirect(array('action' => 'index'));
327
			} else {
328
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
329
			}
330
		}
331
		$groups = $this->User->Group->find('list');
332
		$this->set(compact('groups'));
333
	}
334
 
335
/**
336
 * admin_edit method
337
 *
338
 * @throws NotFoundException
339
 * @param string $id
340
 * @return void
341
 */
342
	public function admin_edit($id = null) {
343
		$this->User->id = $id;
344
		if (!$this->User->exists()) {
345
			throw new NotFoundException(__('Invalid user'));
346
		}
347
		if ($this->request->is('post') || $this->request->is('put')) {
348
			if ($this->User->save($this->request->data)) {
349
				$this->Session->setFlash(__('The user has been saved'));
350
				$this->redirect(array('action' => 'index'));
351
			} else {
352
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
353
			}
354
		} else {
355
			$this->request->data = $this->User->read(null, $id);
356
		}
357
		$groups = $this->User->Group->find('list');
358
		$this->set(compact('groups'));
359
	}
360
 
361
/**
362
 * admin_delete method
363
 *
364
 * @throws MethodNotAllowedException
365
 * @throws NotFoundException
366
 * @param string $id
367
 * @return void
368
 */
369
	public function admin_delete($id = null) {
370
		if (!$this->request->is('post')) {
371
			throw new MethodNotAllowedException();
372
		}
373
		$this->User->id = $id;
374
		if (!$this->User->exists()) {
375
			throw new NotFoundException(__('Invalid user'));
376
		}
377
		if ($this->User->delete()) {
378
			$this->Session->setFlash(__('User deleted'));
379
			$this->redirect(array('action' => 'index'));
380
		}
381
		$this->Session->setFlash(__('User was not deleted'));
382
		$this->redirect(array('action' => 'index'));
383
	}
384
 
385
	public function dashboard() {
386
		App::uses('CakeTime', 'Utility');
387
		$user = $this->User->read(null,$this->Auth->user('id'));
388
		$this->set('user',$user);
389
		$this->set('title_for_layout', "Dashboard");
390
	}
391
 
392
/**
393
* user authentication funtions
394
*/
395
	public function register() {
396
		$referrer = $this->request->query('referrer');
397
		$this->log('referrer = '.$referrer);
398
		$this->Cookie->write('referrer',$referrer);
399
		$this->layout = 'auth';
400
		$this->set('title_for_layout','Register your free letushaggle.com account');
401
		$this->SignMeUp->register();
402
	}
403
 
404
	public function activate() {
13714 anikendra 405
		$this->layout = 'auth';
13532 anikendra 406
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 407
		$this->SignMeUp->activate();
13532 anikendra 408
	}
409
 
410
	public function forgotten_password() {
13714 anikendra 411
		$this->layout = 'auth';
13532 anikendra 412
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 413
		$this->SignMeUp->forgottenPassword();
13532 anikendra 414
	}	
415
 
416
	public function login() {
417
		$this->layout = 'auth';
418
		if (!empty($this->data['User']['next'])) {
419
		    $next = $this->data['User']['next'];
420
		    $this->Session->write('next', $next);
421
		} elseif (!empty($this->params['url']['next'])) {
422
		    $next = $this->params['url']['next'];
423
		    $this->Session->write('next', $next);
424
		}
425
		if ($this->Auth->login()) {
426
		    $next = $this->Session->read('next');
427
		    if (!empty($next)) {
428
				header('location:' . $next);
429
				exit();
430
		    }
13736 anikendra 431
		    $user = $this->User->read(null, $this->Auth->User('id'));		 
13532 anikendra 432
		    if ($user['User']['group_id'] == 2) {
433
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
434
				exit();
435
		    }
436
			if ($user['User']['group_id'] == 1) {
13736 anikendra 437
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 438
				exit();
439
			}
440
		} else {
441
		    if (!empty($this->data)) {                
13736 anikendra 442
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 443
		    }
444
		}
445
		$this->set('title_for_layout', "Login to letushaggle.com");
446
	}
447
 
448
	public function logout() {
449
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
450
		$this->redirect($this->Auth->logout());
451
	}
452
 
453
	public function updatetimezone() {
454
		$this->layout = 'ajax';		
455
		$timezone = $_GET['tz'];
456
		Configure::load('constant');
457
		$timeZones = Configure::read("timeZones");
458
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
459
		if($this->User->query($query)){
460
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
461
		}else{
462
			$result = array('success' => false);
463
		}
464
		$this->set('result',$result);
465
	}
466
 
13736 anikendra 467
	public function verifymobile() {
468
		$this->layout = 'innerpages';
469
	}
13532 anikendra 470
 
13736 anikendra 471
	public function getdial2verifynumber() {
472
		$TelNumber=substr($this->request->data("phone_number"),-10);
473
 
474
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
475
	    $API_KEY = Configure::read("dial2verifyapikey");
476
 
477
	  	//Get API Image Response
478
	    $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";
479
	    // $json=file_get_contents($APIUrl);
480
	    $json = json_encode($this->make_request($url,null));
481
	  	$this->response->type('json');
482
		$this->layout = 'ajax';
483
	    echo($json);die;
484
	}
485
 
486
	public function getdial2verifystatus() { 
487
 
488
		$SID=$_REQUEST["SID"];
489
 
490
	    $json = array();
491
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
492
 
493
	   // Make a call to Dial2Verify API & Parse The JSON Response
494
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
495
		$RequestPayload = $this->make_request($VerificationCall,null);
496
		// $RequestPayload = json_decode($response,true);
497
 
498
		$VerifStatus=$RequestPayload["VerificationStatus"];
499
 
500
		$json["VerificationStatus"]=$VerifStatus;
501
 
502
	   	$this->response->type('json');
503
		$this->layout = 'ajax';
504
	    echo(json_encode($json));die;
505
	}
506
 
507
	public function skipmobileverification() {
508
		$this->Session->write('skipmobileverification',1);
13739 anikendra 509
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 510
	}
511
 
512
	public function reauthenticate($userId) {
513
		$user = $this->User->read(null,$userId);
514
		$this->Auth->login($user['User']);
515
		$json = array('success'=>true);
516
		$this->response->type('json');
517
		$this->layout = 'ajax';
14150 anikendra 518
	    echo(json_encode($json));die;
13736 anikendra 519
	}
13739 anikendra 520
}