Subversion Repositories SmartDukaan

Rev

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