Subversion Repositories SmartDukaan

Rev

Rev 19798 | Rev 19812 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
15403 manish.sha 1
<?php
2
App::uses('AppController', 'Controller');
3
/**
4
 * Users Controller
5
 *
6
 * @property User $User
7
 */
8
 
9
set_time_limit(0);
10
 
11
class UsersController extends AppController {
12
 
15525 manish.sha 13
	//public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie','Paginator');
14
	public $components = array('RequestHandler','Cookie','Paginator');
15403 manish.sha 15
 
16
    public function beforeFilter() {
17
    	parent::beforeFilter();
18
    	// $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
19
    	$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display','home');
15525 manish.sha 20
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_push','socialauth','oneringcb')); 
15403 manish.sha 21
		$this->Cookie->name = 'profittill';
22
		$this->Cookie->time = 86400*30; 
23
		$this->Cookie->path = '/';
24
		$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#H23s~#^';
25
		$this->Cookie->httpOnly = true;
26
    }
27
 
15525 manish.sha 28
	public function oneringcb() {
15655 anikendra 29
		throw new NotFoundException(__('Unauthorized access'));
15525 manish.sha 30
		$this->log(print_r($_REQUEST,1),'onering');
31
		error_log(print_r($_REQUEST,1),3,TMP.'logs/onering.log');
32
		$this->layout = "ajax";
33
		$this->response->type('json');
34
		$this->set(array(
35
		    'result' => $_REQUEST,
36
		    '_serialize' => array('result')
37
		));
38
		$this->render('/Elements/json');
15403 manish.sha 39
	}
40
 
41
	public function mywallet() {
15655 anikendra 42
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 43
		$userId = $this->request->query('user_id');
44
		$tokenValidated = $this->checkToken();
45
		if(isset($userId) && !empty($userId) && $tokenValidated){	
46
			$next = "/my-wallet";					
47
			$redirectUrl = $this->getAutoLoginUrl($userId,$next);
48
			header('location:'.$redirectUrl);
49
			exit();
50
		}else{
51
			$this->redirect(array('controller'=>'special','action'=>'native','login'));
52
		}
53
	}
54
 
55
	public function socialauth() {
15655 anikendra 56
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 57
		$this->layout = "ajax";
58
		$this->log(print_r($this->request->data,1),'socialauth');
59
	}
60
 
61
	public function mine() {
15655 anikendra 62
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 63
		$this->response->type('json');
64
		$this->layout = 'ajax';
65
		$userId = $this->request->query('user_id');
66
		if(isset($userId) && !empty($userId)){
67
			$this->loadModel('User');
68
			$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',
69
				'city','state','pincode','referrer'),'recursive'=>-1);
70
			$user = $this->User->find('first',$options);
71
			$result = $user['User'];
72
		}
73
		$this->set(array(
74
		    'result' => $result,
75
		    '_serialize' => array('result')
76
		)); 
77
		$this->render('/Elements/json'); 
78
	}
79
 
80
	function registertwitteruser(){
15655 anikendra 81
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 82
		$this->twitterObj->setToken($_GET['oauth_token']);
83
		$token = $this->twitterObj->getAccessToken();
84
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
85
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
86
		$data = array();
87
		$data['twitter_id'] = $twitterInfo->id;		
88
		$this->Session->write('twtusername',$twitterInfo->screen_name);
89
		$data['twitter_token'] = $token->oauth_token;
90
		$data['twitter_secret'] = $token->oauth_token_secret;
91
		$data['twitter_screen_name'] = $twitterInfo->screen_name;					
92
		$data['active'] = 1;
93
 
94
		$id = $this->Auth->user('id');
95
		if(!isset($id) || $id == ''){
96
		//	$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
97
			$user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
98
			//if($count<1){
99
			if(empty($user)){
100
				$this->User->create();
101
				$this->User->save($data);
102
//				$dbuser = $this->User->read(null,$this->User->id);
103
				$this->Auth->login($this->User->data);
104
			}else{
105
		//		$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
106
				$this->Auth->login($user['User']);
107
			}
108
		}else{
109
			//$data['id'] = $this->Auth->user('id');
110
			$user = $this->Auth->user;
111
//			$this->User->save($data);
112
//			$this->Auth->login($data);
113
		}                
114
		$user = $this->User->read(null, $this->Auth->User('id'));
115
		if ($user['User']['group_id'] == 1) {
116
			//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
117
			header('location:users/dashboard?userid='.$this->Auth->user('id'));
118
			exit();
119
		}
120
		elseif ($user['User']['group_id'] == 2) {
121
			$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
122
			exit();
123
		}
124
	}
125
 
126
    public function checkfbuser($accessToken=null){
15655 anikendra 127
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 128
		$sessionState = $this->Session->read('state');
129
		if($sessionState != $_GET['state']) {
130
			$this->redirect(array('controller'=>'users','action'=>'login'));
131
		}
132
		else {
133
			if(isset($_GET['code'])){
134
				$code = $_GET['code'];
135
				$facebookConfig = Configure::read("Facebook");		
136
				$token_url = "https://graph.facebook.com/oauth/access_token?"
137
			       . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
138
			       . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;
139
 
140
			    $response = file_get_contents($token_url);
141
			    $params = null;
142
			    parse_str($response, $params);
143
			    $accessToken = $params['access_token'];
144
			}else{
145
				$this->redirect(array('controller'=>'users','action'=>'login'));
146
			}
147
		}
148
		$this->User->recursive = -1;
149
		if (!$accessToken) {
150
		    $this->redirect(array('controller'=>'users','action'=>'login'));
151
		    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
152
		}        
153
		if (isset($accessToken) && $accessToken != 'undefined') {			
154
 
155
		    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;
156
 
157
		    $user = json_decode(file_get_contents($graph_url));
158
			$this->log("FB user = ".print_r($user,1),'fb');
159
		    if (!empty($user)) {
160
			if (!$this->isAuthorized()) {
161
			    $id = $this->User->checkFbUser($user,$accessToken);
162
				$dbuser = $this->User->findById($id);
163
			    $this->Session->write('facebook_id',$user->id);
164
				$this->Auth->login($dbuser['User']);
165
				if($this->Auth->login()){
166
					$this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
167
				}
168
			    $next = $this->Session->read('next');
169
				$this->log("next= ".$next."\n",'fb');
170
 
171
			    if (!empty($next)) {
172
					header('Location:' . $next);
173
					exit();
174
			    }else {
175
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
176
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
177
					exit();
178
			            }
179
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
180
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
181
					exit();
182
				} else {                	
183
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
184
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
185
					exit();
186
				}
187
		    }
188
		}
189
    }
190
 
191
	public function uploadavatar(){
15655 anikendra 192
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 193
		$this->log(print_r($_FILES,1),'debug');
194
		$path = "img/avatars/";
195
		$valid_formats = array("jpg", "png", "gif", "bmp");
196
		if ($this->request->is('post')) {
197
			$name = $_FILES['photoimg']['name'];
198
			$size = $_FILES['photoimg']['size'];
199
 
200
			if(strlen($name))
201
				{
202
					list($txt, $ext) = explode(".", $name);
203
					if(in_array($ext,$valid_formats))
204
					{
205
					if($size<(1024*1024))
206
						{
207
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
208
							$tmp = $_FILES['photoimg']['tmp_name'];
209
							if(move_uploaded_file($tmp, $path.$actual_image_name))
210
								{
211
									echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
212
									echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
213
								}
214
							else
215
								echo __('Upload Failed');
216
						}
217
						else
218
						echo __("Maximum allowed image file size is 1 MB");					
219
						}
220
						else
221
						echo __("Invalid file format");	
222
				}
223
			else
224
				echo __("Please select image");
225
			exit;
226
		}
227
	}
228
 
229
    function checkemail() {
15655 anikendra 230
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 231
        $this->User->recursive = -1;
232
        $this->layout = 'ajax';
233
        if (!empty($this->params['url']['data']['User']['email'])) {
234
            $username = $this->params['url']['data']['User']['email'];
235
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
236
            $username = $this->params['url']['data']['Doctor']['email'];
237
        } else {
238
            $result = false;
239
            $this->set('result', $result);
240
        }
241
        if ($this->Auth->user('id') != null) {
242
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
243
        } else {
244
            $conditions = array('User.email' => $username);
245
        }
246
        $count = $this->User->find('count', array('conditions' => $conditions));
247
        if ($count > 0) {
248
            $result = false;
249
        } else {
250
            $result = true;
251
        }
252
        $this->set('result', $result);
253
    }
254
 
255
/**
256
 * view method
257
 *
258
 * @throws NotFoundException
259
 * @param string $id
260
 * @return void
261
 */
262
	public function view($id = null) {
15655 anikendra 263
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 264
		$this->response->type('json');
265
		$this->layout = 'ajax';
266
		$callback = $this->request->query('callback');
267
		$this->User->id = $id;
268
		if (!$this->User->exists()) {
269
			throw new NotFoundException(__('Invalid user'));
270
		}
271
		$user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
272
		$result = array('user'=>$user);
273
		$this->set(array(
274
		    'result' => $result,
275
		    'callback' => $callback,
276
		    '_serialize' => array('result')
277
		));
278
		$this->render('/Elements/json');
279
	}
280
/**
281
 * edit method
282
 *
283
 * @throws NotFoundException
284
 * @param string $id
285
 * @return void
286
 */
287
 
288
    public function edit($id = null) {
15655 anikendra 289
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 290
		$this->log(print_r($this->request->data,1),'mydetails');
291
		$this->response->type('json');
292
		$this->layout = 'ajax';
293
		$this->User->recursive = -1;
294
		$updateRequired = true;
295
        if (!$this->User->exists($id)) {
296
			$result = array('success'=>false,'message'=>'Invalid user');
297
		} else {
298
	        if ($this->request->is('post') || $this->request->is('put')) {
299
           		if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])) {
300
					$options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
301
					$oldMobile = $this->User->find('first',$options);
302
					if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
303
		        		$this->request->data['mobile_verified'] = 0;
304
					}
305
	        	}
306
	        	if(!empty($this->request->data['referrer'])) {
307
	        		$referrer = $this->request->data['referrer'];
308
	        		$this->log(print_r($referrer,1),'activations');
309
	        		$this->loadModel('ActivationCode');
310
	        		$exists = $this->ActivationCode->findByCode(strtoupper($referrer));
311
	        		$this->log(print_r($exists,1),'activations');
312
	        		if(empty($exists)){
313
	        			$result = array('success'=>false,'message'=>'Invalid referral code');
314
	        			// unset($this->request->data['referrer']);
315
	        			$updateRequired = false;
316
	        		}
317
	        		$this->request->data['activated'] = 1;
318
	        	}	        		
319
	        	if($updateRequired){
320
		            if ($this->User->save($this->request->data)) {
321
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
322
		            } else {
323
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
324
		            }
325
		        }
326
	        }  
327
	    }
328
        $this->set(array(
329
		    'result' => $result,
330
		    '_serialize' => array('result')
331
		)); 
332
		$this->render('/Elements/json');      
333
    }
334
 
335
/**
336
 * admin_index method
337
 *
338
 * @return void
339
 */
340
 
341
	public function admin_pushnotifications(){
15655 anikendra 342
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 343
		if ($this->request->is('post')) {
344
			$sql = $this->request->data['User']['sql'];
345
			if(!empty($sql)){
346
				$users = $this->User->query($sql);
347
				$this->set(compact('users'));
348
			}
349
		}
350
	}
351
 
352
	public function generateAffiliateUrl($url,$user_id,$store){
15655 anikendra 353
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 354
		//Get StoreProduct Info		
355
		$storeId = $store['Store']['id'];
356
		$prefix = "SHA".$storeId;
357
		$tag = $prefix.time();
358
		if($storeId == 2){				
359
			$url = str_replace('www','m',$url);
360
		} elseif($storeId == 3) {
361
			$url_parts = parse_url($url);
362
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
363
			if(isset($url_parts['query'])) {
364
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
365
			}else{
366
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
367
			}
368
		} elseif($storeId == 4){
369
			$next = str_replace('www','m',$url);	
370
			$url = $this->getAutoLoginUrl($userId,$next);
371
			$url .= '?utm_source=profitmandi';
372
		}
373
		if( strpos($url, '?') === false ) {
374
			$firstChar = '?';
375
		} else {
376
			$firstChar = '&';
377
		}
378
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
379
		if(!empty($store['Store']['sub_tag_param'])){
380
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
381
		}
382
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
383
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
384
		$this->loadModel('Click');
385
		$this->Click->create();
386
		$this->Click->save($data);
387
		return $url;
388
	}
389
 
390
	public function admin_push(){
15655 anikendra 391
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 392
		if ($this->request->is('post')) {
393
			if(empty($this->request->data['userIds'])){
394
				$this->Session->setFlash(__('Please choose a few users'));
395
				$this->redirect(array('action' => 'admin_pushnotifications'));
396
			}else{
397
				$this->log(print_r($this->request->data,1),'pushnotifications');
398
				$message = $this->request->data['User'];
399
				$this->loadModel('NotificationCampaign');
400
				$this->NotificationCampaign->create();
401
				$data = array('name'=>$message['name'],'title'=>$message['title'],'type'=>$message['type'],'message'=>$message['message'],'url'=>$message['url'],'expiresat'=>$message['expiresat']);
402
				if($this->NotificationCampaign->save($data)){
403
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
404
				} else{
405
					debug($this->NotificationCampaign->validationErrors);
406
					$message['cid'] = $message['name'];
407
				}
408
				if($message['type'] == 'url' && !empty($message['url'])) {
409
					$url = $message['url'];
410
					$this->loadModel('Store');
411
					$store = $this->Store->getByUrl($url);					
412
				}				
413
				$this->loadModel('GcmUser');
414
				foreach ($this->request->data['userIds'] as $key => $value) {					
415
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
416
					$gcmUser = $this->GcmUser->find('first',$options);
417
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
418
					// $message = array('message'=>$this->request->data['User']['message']);					
419
					if($message['type'] == 'url' && !empty($message['url'])) {
420
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
421
					}					
422
					$this->send_push_notification($regIds,$message,$value);
423
				}
424
			}
425
		}
426
	}
427
 
428
	private function send_push_notification($registatoin_ids, $message, $user_id) {
15655 anikendra 429
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 430
		$msg = array(
431
		    'message'       => $message['message'],
432
		    'cid'       	=> $message['cid'],
433
		    'title'         => $message['title'],
434
		    'type'      	=> $message['type'],
435
		    'url'		    => $message['url'],
436
		    // 'expiresat'	    => strtotime($message['expiresat']),
437
		    'vibrate'       => 1,
438
		    'sound'         => 1,
439
		    'largeIcon'     => 'large_icon',
440
		    'smallIcon'     => 'small_icon'
441
		);
442
		// Set POST variables
443
		$url = 'https://android.googleapis.com/gcm/send';
444
 
445
		$fields = array(
446
		    'registration_ids' => $registatoin_ids,
447
		    'data' => $msg,
448
		);
449
		$headers = array(
450
		    'Authorization: key=' . Configure::read('googleapikey'),
451
		    'Content-Type: application/json'
452
		);
453
		//print_r($headers);
454
		// Open connection
455
		$ch = curl_init();
456
 
457
		// Set the url, number of POST vars, POST data
458
		curl_setopt($ch, CURLOPT_URL, $url);
459
		curl_setopt($ch, CURLOPT_POST, true);
460
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
461
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
462
 
463
		// Disabling SSL Certificate support temporarly
464
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
465
 
466
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
467
 
468
		// Execute post
469
		$result = curl_exec($ch);
470
		if ($result === FALSE) {
471
		    die('Curl failed: ' . curl_error($ch));
472
		}
473
		$res = json_decode($result,1);
474
		$this->loadModel('Pushnotification');
475
		$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
476
		$this->Pushnotification->create();
477
		$this->Pushnotification->save($data);
478
		// Close connection
479
		curl_close($ch);
480
		$this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
481
	}
482
 
483
	public function admin_index() {		
15655 anikendra 484
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 485
		$this->User->recursive = 0;
486
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
487
		$this->Paginator->settings = $options;
488
		$users = $this->Paginator->paginate();
489
		$groups = $this->User->Group->find('list');
490
		$this->set(compact('groups','users'));
491
	}
492
 
493
/**
494
 * admin_view method
495
 *
496
 * @throws NotFoundException
497
 * @param string $id
498
 * @return void
499
 */
500
	public function admin_view($id = null) {
501
		$this->User->id = $id;
502
		if (!$this->User->exists()) {
503
			throw new NotFoundException(__('Invalid user'));
504
		}
505
		$this->set('user', $this->User->read(null, $id));
506
	}
507
 
508
/**
509
 * admin_add method
510
 *
511
 * @return void
512
 */
513
	public function admin_add() {
15655 anikendra 514
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 515
		if ($this->request->is('post')) {
516
			$this->User->create();
517
			if ($this->User->save($this->request->data)) {
518
				$this->Session->setFlash(__('The user has been saved'));
519
				$this->redirect(array('action' => 'index'));
520
			} else {
521
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
522
			}
523
		}
524
		$groups = $this->User->Group->find('list');
525
		$this->set(compact('groups'));
526
	}
527
 
528
/**
529
 * admin_edit method
530
 *
531
 * @throws NotFoundException
532
 * @param string $id
533
 * @return void
534
 */
535
	public function admin_edit($id = null) {
15655 anikendra 536
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 537
		$this->User->id = $id;
538
		if (!$this->User->exists()) {
539
			throw new NotFoundException(__('Invalid user'));
540
		}
541
		if ($this->request->is('post') || $this->request->is('put')) {
542
			if ($this->User->save($this->request->data)) {
543
				$this->Session->setFlash(__('The user has been saved'));
544
				$this->redirect(array('action' => 'index'));
545
			} else {
546
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
547
			}
548
		} else {
549
			$this->request->data = $this->User->read(null, $id);
550
		}
551
		$groups = $this->User->Group->find('list');
552
		$this->set(compact('groups'));
553
	}
554
 
555
/**
556
 * admin_delete method
557
 *
558
 * @throws MethodNotAllowedException
559
 * @throws NotFoundException
560
 * @param string $id
561
 * @return void
562
 */
563
	public function admin_delete($id = null) {
15655 anikendra 564
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 565
		if (!$this->request->is('post')) {
566
			throw new MethodNotAllowedException();
567
		}
568
		$this->User->id = $id;
569
		if (!$this->User->exists()) {
570
			throw new NotFoundException(__('Invalid user'));
571
		}
572
		if ($this->User->delete()) {
573
			$this->Session->setFlash(__('User deleted'));
574
			$this->redirect(array('action' => 'index'));
575
		}
576
		$this->Session->setFlash(__('User was not deleted'));
577
		$this->redirect(array('action' => 'index'));
578
	}
579
 
580
	public function dashboard() {
581
		App::uses('CakeTime', 'Utility');
582
		$user = $this->User->read(null,$this->Auth->user('id'));
583
		$this->set('user',$user);
584
		$this->set('title_for_layout', "Dashboard");
585
	}
586
 
587
/**
588
* user authentication funtions
589
*/
590
	public function register() {
15655 anikendra 591
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 592
		$referrer = $this->request->query('referrer');
593
		$this->log('referrer = '.$referrer);
594
		$this->Cookie->write('referrer',$referrer);
595
		$this->layout = 'auth';
596
		$this->set('title_for_layout','Register your free letushaggle.com account');
597
		$this->SignMeUp->register();
598
	}
599
 
600
	public function activate() {
15655 anikendra 601
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 602
		$this->layout = 'auth';
603
		$this->set('title_for_layout','Activate your copublish.in account');
604
		$this->SignMeUp->activate();
605
	}
606
 
607
	public function forgotten_password() {
15655 anikendra 608
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 609
		$this->layout = 'auth';
610
		$this->set('title_for_layout','Reset your copublish.in password');
611
		$this->SignMeUp->forgottenPassword();
612
	}	
613
 
614
	public function login() {
615
		$this->layout = 'auth';
616
		if (!empty($this->data['User']['next'])) {
617
		    $next = $this->data['User']['next'];
618
		    $this->Session->write('next', $next);
619
		} elseif (!empty($this->params['url']['next'])) {
620
		    $next = $this->params['url']['next'];
621
		    $this->Session->write('next', $next);
622
		}
623
		if ($this->Auth->login()) {
624
		    $next = $this->Session->read('next');
625
		    if (!empty($next)) {
626
				header('location:' . $next);
627
				exit();
628
		    }
629
		    $user = $this->User->read(null, $this->Auth->User('id'));		 
19804 naman 630
		    if ($user['User']['group_id'] == 2 || $user['User']['group_id'] == 6 || $user['User']['group_id'] == 99) {
15403 manish.sha 631
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
632
				exit();
633
		    }
634
			if ($user['User']['group_id'] == 1) {
635
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
636
				exit();
637
			}
638
		} else {
639
		    if (!empty($this->data)) {                
640
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
641
		    }
642
		}
643
		$this->set('title_for_layout', "Login to letushaggle.com");
644
	}
645
 
646
	public function logout() {
647
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
648
		$this->redirect($this->Auth->logout());
649
	}
650
 
651
	public function updatetimezone() {
15655 anikendra 652
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 653
		$this->layout = 'ajax';		
654
		$timezone = $_GET['tz'];
655
		Configure::load('constant');
656
		$timeZones = Configure::read("timeZones");
657
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
658
		if($this->User->query($query)){
659
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
660
		}else{
661
			$result = array('success' => false);
662
		}
663
		$this->set('result',$result);
664
	}
665
 
666
	public function verifymobile() {
15655 anikendra 667
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 668
		$this->layout = 'innerpages';
669
	}
670
 
671
	public function getdial2verifynumber() {
15655 anikendra 672
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 673
		$TelNumber=substr($this->request->data("phone_number"),-10);
674
 
675
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
676
	    $API_KEY = Configure::read("dial2verifyapikey");
677
 
678
	  	//Get API Image Response
679
	    $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";
680
	    // $json=file_get_contents($APIUrl);
681
	    $json = json_encode($this->make_request($url,null));
682
	  	$this->response->type('json');
683
		$this->layout = 'ajax';
684
	    echo($json);die;
685
	}
686
 
687
	public function getdial2verifystatus() { 
15655 anikendra 688
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 689
		$SID=$_REQUEST["SID"];
690
 
691
	    $json = array();
692
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
693
 
694
	   // Make a call to Dial2Verify API & Parse The JSON Response
695
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
696
		$RequestPayload = $this->make_request($VerificationCall,null);
697
		// $RequestPayload = json_decode($response,true);
698
 
699
		$VerifStatus=$RequestPayload["VerificationStatus"];
700
 
701
		$json["VerificationStatus"]=$VerifStatus;
702
 
703
	   	$this->response->type('json');
704
		$this->layout = 'ajax';
705
	    echo(json_encode($json));die;
706
	}
707
 
708
	public function skipmobileverification() {
15655 anikendra 709
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 710
		$this->Session->write('skipmobileverification',1);
711
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
712
	}
713
 
714
	public function reauthenticate($userId) {
15655 anikendra 715
		throw new NotFoundException(__('Unauthorized access'));
15403 manish.sha 716
		$user = $this->User->read(null,$userId);
717
		$this->Auth->login($user['User']);
718
		$json = array('success'=>true);
719
		$this->response->type('json');
720
		$this->layout = 'ajax';
721
	    echo(json_encode($json));die;
722
	}
17380 naman 723
 
724
	public function admin_search() {
725
		$type = $this->request->query('type');
726
		$search = $this->request->query('search');
17386 naman 727
 
17380 naman 728
		$this->User->recursive = -1;
729
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
730
		if($type == 'unactivated'){
731
			$options['conditions'] = array('activated' =>0);
732
		}
733
		else if(!empty($type) && !empty($search)){
734
			if($type=='id'){
735
				$options['conditions'] = array($type =>$search);			
736
			}else{
737
				$options['conditions'] = array($type.' LIKE '=>"%$search%");			
738
			}
739
		}else{
17386 naman 740
 
741
			$options['conditions'] = array('date(User.created)'=>'');			
17380 naman 742
		}	
743
 
744
		$sql = "SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ";
745
		$last_act = $this->User->query($sql);
746
		// debug($last_act);
747
		$last_act_user_id = array();
748
		$last_activated = array();
749
		foreach ($last_act as $key => $row) {
750
			// echo $key;
751
			foreach ($row as $key => $value) {
752
				$last_activated['visited'] = $value['visited'];
753
				$last_act_user_id[$value['user_id']] = $last_activated['visited'];
754
			}
755
		}
756
		// debug($last_act_user_id);
757
		$this->set(compact('last_act_user_id'));
758
		$options['fields'] = array('id','email','first_name','referrer','utm_source','utm_medium','utm_term','utm_campaign','mobile_number','activated','User.created','Appacl.access');
759
		$options['joins'] = array(
760
		    array('table' => 'appacls',
761
		        'alias' => 'Appacl',
762
		        'type' => 'LEFT',
763
		        'conditions' => array(
764
		            'Appacl.user_id = User.id',
765
		        )
766
		    )
767
	    );
768
		$this->Paginator->settings = $options;
769
		$users = $this->Paginator->paginate();		
770
 
771
 
772
		$this->set(compact('users'));	
773
	}
774
 
775
	public function getDateInstallsBy($date, $user_id){
776
 
777
		$this->autoRender = false;	
778
		$this->request->onlyAllow('ajax');
779
		$url = $this->apihost.'appUserBatchDateDrillDown/'.$user_id.'/'.$date;
780
		$getApp = $this->make_request($url,null);
781
		return json_encode($getApp);	
782
	}
19698 naman 783
 
784
    public function admin_backlog()
785
    {
786
 
787
    }
788
 
789
    public function admin_by($userId = null) {
790
 
791
    	$this->loadModel('UserAddress');
792
    	$postOfficeQuery="select pincode,state from postoffices group by pincode";
793
    	$postOfficeResult=$this->UserAddress->query($postOfficeQuery);
794
    	$postOffice=array();
795
    	foreach($postOfficeResult as $value){
796
    		$postOffice[$value['postoffices']['pincode']]=$value['postoffices']['state'];
797
    	}
798
 
799
    	$retailerAddress="SELECT r.title,r.address, r.city,r.state,r.pin from retaileraddresses r join retailerlinks rl on r.retailer_id=rl.retailer_id where rl.user_id=$userId";
800
    	$new_address=$this->UserAddress->query($retailerAddress);
801
 
802
    	$retailerAddress="SELECT title,address,city,state,pin from retailers r join retailerlinks rl on r.id=rl.retailer_id where rl.user_id=$userId";
803
    	$retailer_address=$this->UserAddress->query($retailerAddress);
804
 
805
    	$retailerAddress="SELECT ua.store_name,ua.address,ua.city,ua.state,ua.pincode from user_addresses ua join users u on ua.user_id=u.id where ua.user_id=$userId";
806
    	$user_update_address=$this->UserAddress->query($retailerAddress);
807
 
808
    	$retailerAddress="SELECT concat(' ', address_line_1,address_line_2) as address,city,state,pincode from users where id=$userId";
809
    	$user_address=$this->UserAddress->query($retailerAddress);
810
    	if($user_address[0]['users']['state']==null){
811
    		if($user_address[0]['users']['pincode']==null){
812
 
813
    		}else{
814
    			$user_address[0]['users']['state']=$postOffice[$user_address[0]['users']['pincode']];
815
    		}
816
    	}
817
 
818
    	if(empty($new_address)){
819
 
820
    	}else{
821
    		if(empty($new_address[0]['r']['state'])){
822
    			$new_address[0]['r']['state']=$postOffice[$new_address[0]['r']['pin']];
823
    		}
824
    	}
825
    	if(empty($retailer_address)){
826
 
827
    	}else{
828
    		if(empty($retailer_address[0]['r']['state'])){
829
    			$retailer_address[0]['r']['state']=$postOffice[$retailer_address[0]['r']['pin']];
830
    		}
831
    	}
832
    	if(empty($user_update_address)){
833
 
834
    	}else{
835
    		if(empty($user_update_address[0]['ua']['state'])){
836
    			$user_update_address[0]['ua']['state']=$postOffice[$user_update_address[0]['ua']['pincode']];
837
    		}
838
    	}
839
    	$this->set('newaddress', $new_address);
840
    	$this->set('retaileraddress', $retailer_address);
841
    	$this->set('userupdateaddress', $user_update_address);
842
    	$this->set('useraddress', $user_address);
843
    }
844
 
845
    public function admin_target($userId=null){
846
    	$this->layout = "innerpages";
847
    	$user_id = $userId;
848
    	$cachekey = 'target-'.$user_id;
849
    	$getoffer = Cache::read($cachekey,'target');
850
    	$current_time = time();
851
    	$response = "";
19701 naman 852
	    if($getoffer === false){
853
				$offerurl = $this->apihost."getOfferForUser/?user_id=".$user_id;
854
				$response = $this->make_request($offerurl,null);
855
				Cache::write($cachekey , $response ,'target');
856
				if(empty($response)){
857
						$response = "";
858
					}
859
 
860
			}else{
861
				if(!empty($getoffer)){
862
						$response = $getoffer;
863
					}
864
			}
19698 naman 865
 
866
    	$maxpercentage = 0;
867
 
868
    	if(isset($response['target2_cash_back_percetage']) && !empty($response['target2_cash_back_percetage'])){
869
    		$maxpercentage = $response['target2_cash_back_percetage'];
870
    	}
871
    	else{
872
    		if(isset($response['target1_cash_back_percetage']) && !empty($response['target1_cash_back_percetage'])){
873
    			$maxpercentage = $response['target1_cash_back_percetage'];
874
    		}
875
    	}
876
 
877
 
878
    	$this->loadModel('User');
879
    	$user_email = "";
880
    	if($user_id != null || $user_id != ''){
881
    		$opt = array('conditions'=>array('id'=>$user_id),'recursive'=>-1,'fields'=>'email');
882
    		$usId = $this->User->find('first',$opt);
883
    		$user_email = $usId['User']['email'];
884
    	}
885
    	$this->set(compact('response','maxpercentage','user_email'));
886
    }
19798 naman 887
 
888
 
889
    public function admin_userretailer()
890
    {}
891
 
892
    public function admin_searchuserretailer()
893
    {
894
    	$this->autoRender = false;
895
    	$this->request->onlyAllow ( 'ajax' );
896
    	$type = $this->request->query('type');
897
    	$search = $this->request->query('search');
898
    	$searchfor = $this->request->query('searchfor');
899
    	$this->User->recursive = -1;
900
//     	$options = array('limit'=>100,'order'=>array('id'=>'desc'));
901
 
902
    	$response = "";
903
    	if(!empty($type) && !empty($search)){
904
    		if($searchfor == "usertype"){
905
    			$options['conditions'] = array($type.' LIKE '=>"%$search%");
906
    			$users = $this->User->find('all',$options);
907
    			$response = $users;
908
    		}elseif($searchfor == "retailertype"){
909
    			$this->loadModel('Retailer');
910
    			if($type=='contact'){
911
    				$options['conditions'] =array('OR'=>array('contact1 LIKE '=>"%$search%",'contact2 LIKE '=>"%$search%"));
912
    			}else{
913
    				$options['conditions'] = array($type.' LIKE '=>"%$search%");
914
    			}
915
 
916
    			$users = $this->Retailer->find('all',$options);
917
 
918
    			$response = $users;
919
 
920
    		}
921
 
922
    	}
923
    	return json_encode($response);
924
    }
925
 
926
    public function admin_addretailer(){
927
 
928
 
929
    	if ($this->request->is('post')) {
930
    		$agentid = Configure::read('agentid');
931
    		$cur_date = date('Y-m-d H:i:s', time());
932
    		$data = $this->request->data['Retailer'];
933
    		$retailer['Retailer']['identifier'] = NULL;
934
    		$retailer['Retailer']['title'] = $data['storeName'];
935
    		$retailer['Retailer']['address'] = $data['completeAddress'];
936
    		$retailer['Retailer']['contact1'] = $data['mobileNumber'];
937
    		$retailer['Retailer']['status'] = "pending_verification";
938
    		$retailer['Retailer']['is_elavated'] = 1;
939
    		$retailer['Retailer']['pin'] = $data['pin'];
940
    		$retailer['Retailer']['city'] = $data['city'];
941
    		$retailer['Retailer']['state'] = $data['state'];
942
    		$retailer['Retailer']['retry_count'] = 0;
943
    		$retailer['Retailer']['invalid_retry_count'] = 0;
944
    		$retailer['Retailer']['call_priority'] = NULL;
945
    		$retailer['Retailer']['next_call_time'] = 0;
946
    		$retailer['Retailer']['is_std'] = 0;
947
    		$retailer['Retailer']['is_or'] = 0;
948
    		$retailer['Retailer']['disposition'] = "inbound_call";
949
    		$retailer['Retailer']['source'] = "inbound";
950
    		$retailer['Retailer']['created'] = $cur_date;
951
    		$retailer['Retailer']['modified'] = $cur_date;
952
    		$retailer['Retailer']['tinnumber'] = $data['tinNumber'];
953
    		$retailer['Retailer']['next_call_time'] = NULL;
954
    		$retailer['Retailer']['isvalidated'] = 0;
955
 
956
 
957
    		$this->loadModel('Retailer');
958
    		$this->Retailer->create();
959
    		if ($retdata = $this->Retailer->save($retailer)) {
960
    			$this->Session->setFlash(__('The user has been saved'));
961
    			$callhistoryquery = "insert into callhistory (retailer_id,agent_id,mobile_number,call_type,sms_verified,call_time,duration_sec,last_fetch_time,call_disposition,disposition_description,disposition_comments,created) values (".$retdata['Retailer']['id'].",".$agentid.",'".$retailer['Retailer']['contact1']."','inbound',1,'".$cur_date."',0,'".$cur_date."','verified_link_sent','autosms of code will be sent','autosms of code will be sent','".$cur_date."')";
962
    			$contactquery = "insert into retailercontacts (retailer_id,agent_id,mobile_number,contact_type,call_type,created) values (".$retdata['Retailer']['id'].",".$agentid.",'".$retailer['Retailer']['contact1']."','sms','inbound','".date('Y-m-d h:i:s', time())."')";
963
    			$this->User->query($contactquery);
964
    			$this->User->query($callhistoryquery);
965
    			$this->redirect('userretailer');
966
    		} else {
967
    			$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
968
    		}
969
    	}
970
    }
971
 
972
    public function getcode($id){
973
    	$agentid = Configure::read('agentid'); 
974
    	$this->autoRender = false;
975
    	$this->request->onlyAllow('ajax');
976
    	$url = $this->apihost."getDtrLink/".$agentid."/fresh/".$id;
977
    	$response = $this->make_request($url,null);
978
 
979
    	return json_encode($response['result']);
980
 
981
    }
15403 manish.sha 982
}