Subversion Repositories SmartDukaan

Rev

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