Subversion Repositories SmartDukaan

Rev

Rev 14150 | Rev 14316 | 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')) {
14300 anikendra 268
	        	if(!empty($this->request->data['mobile_number'])){
269
	        		$this->request->data['mobile_verified'] = 0;
270
	        	}
13736 anikendra 271
	            if ($this->User->save($this->request->data)) {
272
	                $result = array('success'=>true,'message'=>'Your profile has been saved');
273
	            } else {
274
	                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
275
	            }
276
	        }  
277
	    }
278
        $this->set(array(
279
		    'result' => $result,
280
		    '_serialize' => array('result')
281
		)); 
282
		$this->render('/Elements/json');      
13532 anikendra 283
    }
284
 
285
/**
286
 * admin_index method
287
 *
288
 * @return void
289
 */
290
	public function admin_index() {
291
		$this->User->recursive = 0;
292
		$users = $this->paginate();
293
		$groups = $this->User->Group->find('list');
294
		$this->set(compact('groups','users'));
295
	}
296
 
297
/**
298
 * admin_view method
299
 *
300
 * @throws NotFoundException
301
 * @param string $id
302
 * @return void
303
 */
304
	public function admin_view($id = null) {
305
		$this->User->id = $id;
306
		if (!$this->User->exists()) {
307
			throw new NotFoundException(__('Invalid user'));
308
		}
309
		$this->set('user', $this->User->read(null, $id));
310
	}
311
 
312
/**
313
 * admin_add method
314
 *
315
 * @return void
316
 */
317
	public function admin_add() {
318
		if ($this->request->is('post')) {
319
			$this->User->create();
320
			if ($this->User->save($this->request->data)) {
321
				$this->Session->setFlash(__('The user has been saved'));
322
				$this->redirect(array('action' => 'index'));
323
			} else {
324
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
325
			}
326
		}
327
		$groups = $this->User->Group->find('list');
328
		$this->set(compact('groups'));
329
	}
330
 
331
/**
332
 * admin_edit method
333
 *
334
 * @throws NotFoundException
335
 * @param string $id
336
 * @return void
337
 */
338
	public function admin_edit($id = null) {
339
		$this->User->id = $id;
340
		if (!$this->User->exists()) {
341
			throw new NotFoundException(__('Invalid user'));
342
		}
343
		if ($this->request->is('post') || $this->request->is('put')) {
344
			if ($this->User->save($this->request->data)) {
345
				$this->Session->setFlash(__('The user has been saved'));
346
				$this->redirect(array('action' => 'index'));
347
			} else {
348
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
349
			}
350
		} else {
351
			$this->request->data = $this->User->read(null, $id);
352
		}
353
		$groups = $this->User->Group->find('list');
354
		$this->set(compact('groups'));
355
	}
356
 
357
/**
358
 * admin_delete method
359
 *
360
 * @throws MethodNotAllowedException
361
 * @throws NotFoundException
362
 * @param string $id
363
 * @return void
364
 */
365
	public function admin_delete($id = null) {
366
		if (!$this->request->is('post')) {
367
			throw new MethodNotAllowedException();
368
		}
369
		$this->User->id = $id;
370
		if (!$this->User->exists()) {
371
			throw new NotFoundException(__('Invalid user'));
372
		}
373
		if ($this->User->delete()) {
374
			$this->Session->setFlash(__('User deleted'));
375
			$this->redirect(array('action' => 'index'));
376
		}
377
		$this->Session->setFlash(__('User was not deleted'));
378
		$this->redirect(array('action' => 'index'));
379
	}
380
 
381
	public function dashboard() {
382
		App::uses('CakeTime', 'Utility');
383
		$user = $this->User->read(null,$this->Auth->user('id'));
384
		$this->set('user',$user);
385
		$this->set('title_for_layout', "Dashboard");
386
	}
387
 
388
/**
389
* user authentication funtions
390
*/
391
	public function register() {
392
		$referrer = $this->request->query('referrer');
393
		$this->log('referrer = '.$referrer);
394
		$this->Cookie->write('referrer',$referrer);
395
		$this->layout = 'auth';
396
		$this->set('title_for_layout','Register your free letushaggle.com account');
397
		$this->SignMeUp->register();
398
	}
399
 
400
	public function activate() {
13714 anikendra 401
		$this->layout = 'auth';
13532 anikendra 402
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 403
		$this->SignMeUp->activate();
13532 anikendra 404
	}
405
 
406
	public function forgotten_password() {
13714 anikendra 407
		$this->layout = 'auth';
13532 anikendra 408
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 409
		$this->SignMeUp->forgottenPassword();
13532 anikendra 410
	}	
411
 
412
	public function login() {
413
		$this->layout = 'auth';
414
		if (!empty($this->data['User']['next'])) {
415
		    $next = $this->data['User']['next'];
416
		    $this->Session->write('next', $next);
417
		} elseif (!empty($this->params['url']['next'])) {
418
		    $next = $this->params['url']['next'];
419
		    $this->Session->write('next', $next);
420
		}
421
		if ($this->Auth->login()) {
422
		    $next = $this->Session->read('next');
423
		    if (!empty($next)) {
424
				header('location:' . $next);
425
				exit();
426
		    }
13736 anikendra 427
		    $user = $this->User->read(null, $this->Auth->User('id'));		 
13532 anikendra 428
		    if ($user['User']['group_id'] == 2) {
429
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
430
				exit();
431
		    }
432
			if ($user['User']['group_id'] == 1) {
13736 anikendra 433
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 434
				exit();
435
			}
436
		} else {
437
		    if (!empty($this->data)) {                
13736 anikendra 438
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 439
		    }
440
		}
441
		$this->set('title_for_layout', "Login to letushaggle.com");
442
	}
443
 
444
	public function logout() {
445
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
446
		$this->redirect($this->Auth->logout());
447
	}
448
 
449
	public function updatetimezone() {
450
		$this->layout = 'ajax';		
451
		$timezone = $_GET['tz'];
452
		Configure::load('constant');
453
		$timeZones = Configure::read("timeZones");
454
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
455
		if($this->User->query($query)){
456
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
457
		}else{
458
			$result = array('success' => false);
459
		}
460
		$this->set('result',$result);
461
	}
462
 
13736 anikendra 463
	public function verifymobile() {
464
		$this->layout = 'innerpages';
465
	}
13532 anikendra 466
 
13736 anikendra 467
	public function getdial2verifynumber() {
468
		$TelNumber=substr($this->request->data("phone_number"),-10);
469
 
470
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
471
	    $API_KEY = Configure::read("dial2verifyapikey");
472
 
473
	  	//Get API Image Response
474
	    $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";
475
	    // $json=file_get_contents($APIUrl);
476
	    $json = json_encode($this->make_request($url,null));
477
	  	$this->response->type('json');
478
		$this->layout = 'ajax';
479
	    echo($json);die;
480
	}
481
 
482
	public function getdial2verifystatus() { 
483
 
484
		$SID=$_REQUEST["SID"];
485
 
486
	    $json = array();
487
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
488
 
489
	   // Make a call to Dial2Verify API & Parse The JSON Response
490
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
491
		$RequestPayload = $this->make_request($VerificationCall,null);
492
		// $RequestPayload = json_decode($response,true);
493
 
494
		$VerifStatus=$RequestPayload["VerificationStatus"];
495
 
496
		$json["VerificationStatus"]=$VerifStatus;
497
 
498
	   	$this->response->type('json');
499
		$this->layout = 'ajax';
500
	    echo(json_encode($json));die;
501
	}
502
 
503
	public function skipmobileverification() {
504
		$this->Session->write('skipmobileverification',1);
13739 anikendra 505
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 506
	}
507
 
508
	public function reauthenticate($userId) {
509
		$user = $this->User->read(null,$userId);
510
		$this->Auth->login($user['User']);
511
		$json = array('success'=>true);
512
		$this->response->type('json');
513
		$this->layout = 'ajax';
14150 anikendra 514
	    echo(json_encode($json));die;
13736 anikendra 515
	}
13739 anikendra 516
}