Subversion Repositories SmartDukaan

Rev

Rev 15511 | Rev 15651 | 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
 */
14408 anikendra 8
 
9
set_time_limit(0);
10
 
13532 anikendra 11
class UsersController extends AppController {
12
 
14395 anikendra 13
	public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie','Paginator');
13532 anikendra 14
 
15
    public function beforeFilter() {
16
    	parent::beforeFilter();
17
    	// $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
18
    	$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display','home');
15511 anikendra 19
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_push','socialauth','oneringcb')); 
13736 anikendra 20
		$this->Cookie->name = 'profittill';
21
		$this->Cookie->time = 86400*30; 
22
		$this->Cookie->path = '/';
23
		$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#H23s~#^';
24
		$this->Cookie->httpOnly = true;
13532 anikendra 25
    }
26
 
15511 anikendra 27
	public function oneringcb() {
28
		$this->log(print_r($_REQUEST,1),'onering');
15523 anikendra 29
		$this->layout = "ajax";
30
        $this->response->type('json');
31
        $this->set(array(
32
            'result' => $result,
33
            '_serialize' => array('result')
34
        ));
35
        $this->render('/Elements/json');
13532 anikendra 36
	}
37
 
14019 anikendra 38
	public function mywallet() {
39
		$userId = $this->request->query('user_id');
15380 anikendra 40
		$tokenValidated = $this->checkToken($userId);
14891 anikendra 41
		if(isset($userId) && !empty($userId) && $tokenValidated){	
14441 anikendra 42
			$next = "/my-wallet";					
14150 anikendra 43
			$redirectUrl = $this->getAutoLoginUrl($userId,$next);
15380 anikendra 44
			$this->log($redirectUrl,'headers');
15247 anikendra 45
			$this->layout = 'innerpages';
46
			$this->set(compact('redirectUrl'));
14891 anikendra 47
		}else{
48
			$this->redirect(array('controller'=>'special','action'=>'native','login'));
14019 anikendra 49
		}
50
	}
51
 
14825 anikendra 52
	public function socialauth() {
53
		$this->layout = "ajax";
54
		$this->log(print_r($this->request->data,1),'socialauth');
55
	}
56
 
13740 anikendra 57
	public function mine() {
13758 anikendra 58
		$this->response->type('json');
59
		$this->layout = 'ajax';
13740 anikendra 60
		$userId = $this->request->query('user_id');
61
		if(isset($userId) && !empty($userId)){
62
			$this->loadModel('User');
13758 anikendra 63
			$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',
64
				'city','state','pincode','referrer'),'recursive'=>-1);
13763 anikendra 65
			$user = $this->User->find('first',$options);
66
			$result = $user['User'];
13740 anikendra 67
		}
13758 anikendra 68
		$this->set(array(
69
		    'result' => $result,
70
		    '_serialize' => array('result')
71
		)); 
72
		$this->render('/Elements/json'); 
13740 anikendra 73
	}
74
 
13532 anikendra 75
	function registertwitteruser(){
76
		$this->twitterObj->setToken($_GET['oauth_token']);
77
		$token = $this->twitterObj->getAccessToken();
78
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
79
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
80
		$data = array();
81
		$data['twitter_id'] = $twitterInfo->id;		
82
		$this->Session->write('twtusername',$twitterInfo->screen_name);
83
		$data['twitter_token'] = $token->oauth_token;
84
		$data['twitter_secret'] = $token->oauth_token_secret;
85
		$data['twitter_screen_name'] = $twitterInfo->screen_name;					
86
		$data['active'] = 1;
87
 
88
		$id = $this->Auth->user('id');
89
		if(!isset($id) || $id == ''){
90
		//	$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
91
			$user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
92
			//if($count<1){
93
			if(empty($user)){
94
				$this->User->create();
95
				$this->User->save($data);
96
//				$dbuser = $this->User->read(null,$this->User->id);
97
				$this->Auth->login($this->User->data);
98
			}else{
99
		//		$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
100
				$this->Auth->login($user['User']);
101
			}
102
		}else{
103
			//$data['id'] = $this->Auth->user('id');
104
			$user = $this->Auth->user;
105
//			$this->User->save($data);
106
//			$this->Auth->login($data);
107
		}                
108
		$user = $this->User->read(null, $this->Auth->User('id'));
109
		if ($user['User']['group_id'] == 1) {
110
			//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
111
			header('location:users/dashboard?userid='.$this->Auth->user('id'));
112
			exit();
113
		}
114
		elseif ($user['User']['group_id'] == 2) {
115
			$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
116
			exit();
117
		}
118
	}
119
 
120
    public function checkfbuser($accessToken=null){
121
		$sessionState = $this->Session->read('state');
122
		if($sessionState != $_GET['state']) {
123
			$this->redirect(array('controller'=>'users','action'=>'login'));
124
		}
125
		else {
126
			if(isset($_GET['code'])){
127
				$code = $_GET['code'];
128
				$facebookConfig = Configure::read("Facebook");		
129
				$token_url = "https://graph.facebook.com/oauth/access_token?"
130
			       . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
131
			       . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;
132
 
133
			    $response = file_get_contents($token_url);
134
			    $params = null;
135
			    parse_str($response, $params);
136
			    $accessToken = $params['access_token'];
137
			}else{
138
				$this->redirect(array('controller'=>'users','action'=>'login'));
139
			}
140
		}
141
		$this->User->recursive = -1;
142
		if (!$accessToken) {
143
		    $this->redirect(array('controller'=>'users','action'=>'login'));
144
		    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
145
		}        
146
		if (isset($accessToken) && $accessToken != 'undefined') {			
147
 
148
		    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;
149
 
150
		    $user = json_decode(file_get_contents($graph_url));
151
			$this->log("FB user = ".print_r($user,1),'fb');
152
		    if (!empty($user)) {
153
			if (!$this->isAuthorized()) {
154
			    $id = $this->User->checkFbUser($user,$accessToken);
155
				$dbuser = $this->User->findById($id);
156
			    $this->Session->write('facebook_id',$user->id);
157
				$this->Auth->login($dbuser['User']);
158
				if($this->Auth->login()){
159
					$this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
160
				}
161
			    $next = $this->Session->read('next');
162
				$this->log("next= ".$next."\n",'fb');
163
 
164
			    if (!empty($next)) {
165
					header('Location:' . $next);
166
					exit();
167
			    }else {
168
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
169
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
170
					exit();
171
			            }
172
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
173
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
174
					exit();
175
				} else {                	
176
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
177
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
178
					exit();
179
				}
180
		    }
181
		}
182
    }
183
 
184
	public function uploadavatar(){
185
		$this->log(print_r($_FILES,1),'debug');
186
		$path = "img/avatars/";
187
		$valid_formats = array("jpg", "png", "gif", "bmp");
188
		if ($this->request->is('post')) {
189
			$name = $_FILES['photoimg']['name'];
190
			$size = $_FILES['photoimg']['size'];
191
 
192
			if(strlen($name))
193
				{
194
					list($txt, $ext) = explode(".", $name);
195
					if(in_array($ext,$valid_formats))
196
					{
197
					if($size<(1024*1024))
198
						{
199
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
200
							$tmp = $_FILES['photoimg']['tmp_name'];
201
							if(move_uploaded_file($tmp, $path.$actual_image_name))
202
								{
203
									echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
204
									echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
205
								}
206
							else
207
								echo __('Upload Failed');
208
						}
209
						else
210
						echo __("Maximum allowed image file size is 1 MB");					
211
						}
212
						else
213
						echo __("Invalid file format");	
214
				}
215
			else
216
				echo __("Please select image");
217
			exit;
218
		}
219
	}
220
 
221
    function checkemail() {
222
        $this->User->recursive = -1;
223
        $this->layout = 'ajax';
224
        if (!empty($this->params['url']['data']['User']['email'])) {
225
            $username = $this->params['url']['data']['User']['email'];
226
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
227
            $username = $this->params['url']['data']['Doctor']['email'];
228
        } else {
229
            $result = false;
230
            $this->set('result', $result);
231
        }
232
        if ($this->Auth->user('id') != null) {
233
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
234
        } else {
235
            $conditions = array('User.email' => $username);
236
        }
237
        $count = $this->User->find('count', array('conditions' => $conditions));
238
        if ($count > 0) {
239
            $result = false;
240
        } else {
241
            $result = true;
242
        }
243
        $this->set('result', $result);
244
    }
245
 
246
/**
247
 * view method
248
 *
249
 * @throws NotFoundException
250
 * @param string $id
251
 * @return void
252
 */
253
	public function view($id = null) {
254
		$this->response->type('json');
255
		$this->layout = 'ajax';
256
		$callback = $this->request->query('callback');
257
		$this->User->id = $id;
258
		if (!$this->User->exists()) {
259
			throw new NotFoundException(__('Invalid user'));
260
		}
261
		$user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
262
		$result = array('user'=>$user);
263
		$this->set(array(
264
		    'result' => $result,
265
		    'callback' => $callback,
266
		    '_serialize' => array('result')
267
		));
13736 anikendra 268
		$this->render('/Elements/json');
13532 anikendra 269
	}
270
/**
271
 * edit method
272
 *
273
 * @throws NotFoundException
274
 * @param string $id
275
 * @return void
276
 */
277
 
13736 anikendra 278
    public function edit($id = null) {
14770 anikendra 279
		$this->log(print_r($this->request->data,1),'mydetails');
280
		$this->response->type('json');
281
		$this->layout = 'ajax';
282
		$this->User->recursive = -1;
283
		$updateRequired = true;
13736 anikendra 284
        if (!$this->User->exists($id)) {
14300 anikendra 285
			$result = array('success'=>false,'message'=>'Invalid user');
13736 anikendra 286
		} else {
287
	        if ($this->request->is('post') || $this->request->is('put')) {
14768 anikendra 288
           		if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])) {
289
					$options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
290
					$oldMobile = $this->User->find('first',$options);
291
					if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
14316 anikendra 292
		        		$this->request->data['mobile_verified'] = 0;
14768 anikendra 293
					}
14300 anikendra 294
	        	}
14770 anikendra 295
	        	if(!empty($this->request->data['referrer'])) {
14768 anikendra 296
	        		$referrer = $this->request->data['referrer'];
14787 anikendra 297
	        		$this->log(print_r($referrer,1),'activations');
14768 anikendra 298
	        		$this->loadModel('ActivationCode');
14785 anikendra 299
	        		$exists = $this->ActivationCode->findByCode(strtoupper($referrer));
14787 anikendra 300
	        		$this->log(print_r($exists,1),'activations');
14768 anikendra 301
	        		if(empty($exists)){
302
	        			$result = array('success'=>false,'message'=>'Invalid referral code');
15085 anikendra 303
	        			// unset($this->request->data['referrer']);
14770 anikendra 304
	        			$updateRequired = false;
15477 anikendra 305
	        		} else {
306
	        			$this->request->data['activated'] = 1;        		
307
	        		}		        		
14768 anikendra 308
	        	}	        		
14770 anikendra 309
	        	if($updateRequired){
310
		            if ($this->User->save($this->request->data)) {
15475 anikendra 311
		            	if($this->request->data['activated'] == 1) {
312
		            		//Call user activation api
313
		        			$this->markUserActivated($id);
314
		            	}			        		
14770 anikendra 315
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
316
		            } else {
317
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
318
		            }
319
		        }
13736 anikendra 320
	        }  
321
	    }
322
        $this->set(array(
323
		    'result' => $result,
324
		    '_serialize' => array('result')
325
		)); 
326
		$this->render('/Elements/json');      
13532 anikendra 327
    }
328
 
329
/**
330
 * admin_index method
331
 *
332
 * @return void
333
 */
14408 anikendra 334
 
335
	public function admin_pushnotifications(){
336
		if ($this->request->is('post')) {
337
			$sql = $this->request->data['User']['sql'];
338
			if(!empty($sql)){
339
				$users = $this->User->query($sql);
340
				$this->set(compact('users'));
341
			}
342
		}
343
	}
344
 
14445 anikendra 345
	public function generateAffiliateUrl($url,$user_id,$store){
346
		//Get StoreProduct Info		
14428 anikendra 347
		$storeId = $store['Store']['id'];
348
		$prefix = "SHA".$storeId;
349
		$tag = $prefix.time();
350
		if($storeId == 2){				
351
			$url = str_replace('www','m',$url);
352
		} elseif($storeId == 3) {
353
			$url_parts = parse_url($url);
354
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
355
			if(isset($url_parts['query'])) {
356
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
357
			}else{
358
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
359
			}
360
		} elseif($storeId == 4){
14445 anikendra 361
			$next = str_replace('www','m',$url);	
14428 anikendra 362
			$url = $this->getAutoLoginUrl($userId,$next);
363
			$url .= '?utm_source=profitmandi';
364
		}
365
		if( strpos($url, '?') === false ) {
366
			$firstChar = '?';
367
		} else {
368
			$firstChar = '&';
369
		}
370
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
371
		if(!empty($store['Store']['sub_tag_param'])){
372
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
373
		}
374
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
375
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
376
		$this->loadModel('Click');
377
		$this->Click->create();
378
		$this->Click->save($data);
379
		return $url;
380
	}
381
 
14408 anikendra 382
	public function admin_push(){
383
		if ($this->request->is('post')) {
384
			if(empty($this->request->data['userIds'])){
385
				$this->Session->setFlash(__('Please choose a few users'));
386
				$this->redirect(array('action' => 'admin_pushnotifications'));
387
			}else{
14824 anikendra 388
				$this->log(print_r($this->request->data,1),'pushnotifications');
14445 anikendra 389
				$message = $this->request->data['User'];
14776 anikendra 390
				$this->loadModel('NotificationCampaign');
391
				$this->NotificationCampaign->create();
14781 anikendra 392
				$data = array('name'=>$message['name'],'title'=>$message['title'],'type'=>$message['type'],'message'=>$message['message'],'url'=>$message['url'],'expiresat'=>$message['expiresat']);
14776 anikendra 393
				if($this->NotificationCampaign->save($data)){
394
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
395
				} else{
396
					debug($this->NotificationCampaign->validationErrors);
397
					$message['cid'] = $message['name'];
398
				}
14445 anikendra 399
				if($message['type'] == 'url' && !empty($message['url'])) {
400
					$url = $message['url'];
401
					$this->loadModel('Store');
402
					$store = $this->Store->getByUrl($url);					
403
				}				
14408 anikendra 404
				$this->loadModel('GcmUser');
405
				foreach ($this->request->data['userIds'] as $key => $value) {					
14770 anikendra 406
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
14408 anikendra 407
					$gcmUser = $this->GcmUser->find('first',$options);
408
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
14445 anikendra 409
					// $message = array('message'=>$this->request->data['User']['message']);					
410
					if($message['type'] == 'url' && !empty($message['url'])) {
411
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14428 anikendra 412
					}					
413
					$this->send_push_notification($regIds,$message,$value);
14408 anikendra 414
				}
415
			}
416
		}
417
	}
418
 
15414 manas 419
	/*private function send_push_notification($registatoin_ids, $message, $user_id) {
14409 anikendra 420
		$msg = array(
421
		    'message'       => $message['message'],
14776 anikendra 422
		    'cid'       	=> $message['cid'],
14428 anikendra 423
		    'title'         => $message['title'],
424
		    'type'      	=> $message['type'],
425
		    'url'		    => $message['url'],
14782 anikendra 426
		    // 'expiresat'	    => strtotime($message['expiresat']),
14409 anikendra 427
		    'vibrate'       => 1,
428
		    'sound'         => 1,
429
		    'largeIcon'     => 'large_icon',
430
		    'smallIcon'     => 'small_icon'
431
		);
432
		// Set POST variables
433
		$url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 434
 
14409 anikendra 435
		$fields = array(
436
		    'registration_ids' => $registatoin_ids,
437
		    'data' => $msg,
438
		);
439
		$headers = array(
440
		    'Authorization: key=' . Configure::read('googleapikey'),
441
		    'Content-Type: application/json'
442
		);
443
		//print_r($headers);
444
		// Open connection
445
		$ch = curl_init();
14408 anikendra 446
 
14409 anikendra 447
		// Set the url, number of POST vars, POST data
448
		curl_setopt($ch, CURLOPT_URL, $url);
449
		curl_setopt($ch, CURLOPT_POST, true);
450
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
451
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
14408 anikendra 452
 
14409 anikendra 453
		// Disabling SSL Certificate support temporarly
454
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
14408 anikendra 455
 
14409 anikendra 456
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
14408 anikendra 457
 
14409 anikendra 458
		// Execute post
459
		$result = curl_exec($ch);
460
		if ($result === FALSE) {
461
		    die('Curl failed: ' . curl_error($ch));
462
		}
14776 anikendra 463
		$res = json_decode($result,1);
464
		$this->loadModel('Pushnotification');
465
		$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
466
		$this->Pushnotification->create();
467
		$this->Pushnotification->save($data);
14409 anikendra 468
		// Close connection
469
		curl_close($ch);
15085 anikendra 470
		$this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
15414 manas 471
	}*/
472
	private function send_push_notification($registatoin_ids, $message, $user_id) {
473
                $msg = array(
474
                    'message'       => $message['message'],
475
                    'cid'               => $message['cid'],
476
                    'title'         => $message['title'],
477
                    'type'              => $message['type'],
478
                    'url'                   => $message['url'],
479
                    // 'expiresat'          => strtotime($message['expiresat']),
480
                    'vibrate'       => 1,
481
                    'sound'         => 1,
482
                    'largeIcon'     => 'large_icon',
483
                    'smallIcon'     => 'small_icon'
484
                );
485
                // Set POST variables
486
                $url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 487
 
15414 manas 488
                $fields = array(
489
                    'registration_ids' => $registatoin_ids,
490
                    'data' => $msg,
491
                );
492
                $headers = array(
493
                    'Authorization: key=' . Configure::read('googleapikey'),
494
                    'Content-Type: application/json'
495
                );
496
                //print_r($headers);
497
                // Open connection
498
                $ch = curl_init();
499
 
500
                // Set the url, number of POST vars, POST data
501
                curl_setopt($ch, CURLOPT_URL, $url);
502
                curl_setopt($ch, CURLOPT_POST, true);
503
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
504
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
505
 
506
                // Disabling SSL Certificate support temporarly
507
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
508
 
509
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
510
 
511
                // Execute post
512
                $result = curl_exec($ch);
513
                if ($result === FALSE) {
514
                    die('Curl failed: ' . curl_error($ch));
515
                }
516
                $res = json_decode($result,1);
517
 
518
                $this->loadModel('Pushnotification');
519
                if($res['success']==1){
520
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>'success');
521
				}else if($res['success']==0){
522
					$error_message=$res['results'][0]['error'];
523
					$sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
524
					$resultData=$this->GcmUser->query($sqlQuery);
525
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>$error_message);
526
				}
527
                #$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
528
                $this->Pushnotification->create();
529
                $this->Pushnotification->save($data);
530
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($data,1),'pushnotifications');
531
                // Close connection
532
                curl_close($ch);
533
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
534
        }
535
 
14408 anikendra 536
	public function admin_index() {		
13532 anikendra 537
		$this->User->recursive = 0;
14395 anikendra 538
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
539
		$this->Paginator->settings = $options;
540
		$users = $this->Paginator->paginate();
13532 anikendra 541
		$groups = $this->User->Group->find('list');
542
		$this->set(compact('groups','users'));
543
	}
544
 
545
/**
546
 * admin_view method
547
 *
548
 * @throws NotFoundException
549
 * @param string $id
550
 * @return void
551
 */
552
	public function admin_view($id = null) {
553
		$this->User->id = $id;
554
		if (!$this->User->exists()) {
555
			throw new NotFoundException(__('Invalid user'));
556
		}
557
		$this->set('user', $this->User->read(null, $id));
558
	}
559
 
560
/**
561
 * admin_add method
562
 *
563
 * @return void
564
 */
565
	public function admin_add() {
566
		if ($this->request->is('post')) {
567
			$this->User->create();
568
			if ($this->User->save($this->request->data)) {
569
				$this->Session->setFlash(__('The user has been saved'));
570
				$this->redirect(array('action' => 'index'));
571
			} else {
572
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
573
			}
574
		}
575
		$groups = $this->User->Group->find('list');
576
		$this->set(compact('groups'));
577
	}
578
 
579
/**
580
 * admin_edit method
581
 *
582
 * @throws NotFoundException
583
 * @param string $id
584
 * @return void
585
 */
586
	public function admin_edit($id = null) {
587
		$this->User->id = $id;
588
		if (!$this->User->exists()) {
589
			throw new NotFoundException(__('Invalid user'));
590
		}
591
		if ($this->request->is('post') || $this->request->is('put')) {
592
			if ($this->User->save($this->request->data)) {
593
				$this->Session->setFlash(__('The user has been saved'));
594
				$this->redirect(array('action' => 'index'));
595
			} else {
596
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
597
			}
598
		} else {
599
			$this->request->data = $this->User->read(null, $id);
600
		}
601
		$groups = $this->User->Group->find('list');
602
		$this->set(compact('groups'));
603
	}
604
 
605
/**
606
 * admin_delete method
607
 *
608
 * @throws MethodNotAllowedException
609
 * @throws NotFoundException
610
 * @param string $id
611
 * @return void
612
 */
15217 anikendra 613
/*
13532 anikendra 614
	public function admin_delete($id = null) {
615
		if (!$this->request->is('post')) {
616
			throw new MethodNotAllowedException();
617
		}
618
		$this->User->id = $id;
619
		if (!$this->User->exists()) {
620
			throw new NotFoundException(__('Invalid user'));
621
		}
622
		if ($this->User->delete()) {
623
			$this->Session->setFlash(__('User deleted'));
624
			$this->redirect(array('action' => 'index'));
625
		}
626
		$this->Session->setFlash(__('User was not deleted'));
627
		$this->redirect(array('action' => 'index'));
628
	}
15217 anikendra 629
*/
13532 anikendra 630
 
15217 anikendra 631
	public function admin_search() {
632
		$type = $this->request->query('type');
633
		$search = $this->request->query('search');
634
		$this->User->recursive = -1;
635
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
15232 anikendra 636
		if($type == 'unactivated'){
637
			$options['conditions'] = array('activated' =>0);
638
		}
639
		else if(!empty($type) && !empty($search)){
640
			$options['conditions'] = array($type.' LIKE '=>"%$search%");			
641
		}else{
642
			$options['conditions'] = array('date(created)'=>date('Y-m-d',time()));			
15217 anikendra 643
		}		
15232 anikendra 644
		$this->Paginator->settings = $options;
645
		$users = $this->Paginator->paginate();		
15380 anikendra 646
 
647
		$this->set(compact('users'));	
15217 anikendra 648
	}
649
 
13532 anikendra 650
	public function dashboard() {
651
		App::uses('CakeTime', 'Utility');
652
		$user = $this->User->read(null,$this->Auth->user('id'));
653
		$this->set('user',$user);
654
		$this->set('title_for_layout', "Dashboard");
655
	}
656
 
657
/**
658
* user authentication funtions
659
*/
660
	public function register() {
661
		$referrer = $this->request->query('referrer');
662
		$this->log('referrer = '.$referrer);
663
		$this->Cookie->write('referrer',$referrer);
664
		$this->layout = 'auth';
665
		$this->set('title_for_layout','Register your free letushaggle.com account');
666
		$this->SignMeUp->register();
667
	}
668
 
669
	public function activate() {
13714 anikendra 670
		$this->layout = 'auth';
13532 anikendra 671
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 672
		$this->SignMeUp->activate();
13532 anikendra 673
	}
674
 
675
	public function forgotten_password() {
13714 anikendra 676
		$this->layout = 'auth';
13532 anikendra 677
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 678
		$this->SignMeUp->forgottenPassword();
13532 anikendra 679
	}	
680
 
681
	public function login() {
682
		$this->layout = 'auth';
683
		if (!empty($this->data['User']['next'])) {
684
		    $next = $this->data['User']['next'];
685
		    $this->Session->write('next', $next);
686
		} elseif (!empty($this->params['url']['next'])) {
687
		    $next = $this->params['url']['next'];
688
		    $this->Session->write('next', $next);
689
		}
690
		if ($this->Auth->login()) {
691
		    $next = $this->Session->read('next');
692
		    if (!empty($next)) {
693
				header('location:' . $next);
694
				exit();
695
		    }
15188 anikendra 696
		    $user = $this->User->read(null, $this->Auth->User('id'));		 		    
13532 anikendra 697
			if ($user['User']['group_id'] == 1) {
13736 anikendra 698
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 699
				exit();
700
			}
15188 anikendra 701
			else if ($user['User']['group_id'] >= 2) {
702
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
703
				exit();
704
		    }
13532 anikendra 705
		} else {
706
		    if (!empty($this->data)) {                
13736 anikendra 707
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 708
		    }
709
		}
710
		$this->set('title_for_layout', "Login to letushaggle.com");
711
	}
712
 
713
	public function logout() {
714
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
715
		$this->redirect($this->Auth->logout());
716
	}
717
 
718
	public function updatetimezone() {
719
		$this->layout = 'ajax';		
720
		$timezone = $_GET['tz'];
721
		Configure::load('constant');
722
		$timeZones = Configure::read("timeZones");
723
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
724
		if($this->User->query($query)){
725
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
726
		}else{
727
			$result = array('success' => false);
728
		}
729
		$this->set('result',$result);
730
	}
731
 
13736 anikendra 732
	public function verifymobile() {
733
		$this->layout = 'innerpages';
734
	}
13532 anikendra 735
 
13736 anikendra 736
	public function getdial2verifynumber() {
737
		$TelNumber=substr($this->request->data("phone_number"),-10);
738
 
739
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
740
	    $API_KEY = Configure::read("dial2verifyapikey");
741
 
742
	  	//Get API Image Response
743
	    $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";
744
	    // $json=file_get_contents($APIUrl);
745
	    $json = json_encode($this->make_request($url,null));
746
	  	$this->response->type('json');
747
		$this->layout = 'ajax';
748
	    echo($json);die;
749
	}
750
 
751
	public function getdial2verifystatus() { 
752
 
753
		$SID=$_REQUEST["SID"];
754
 
755
	    $json = array();
756
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
757
 
758
	   // Make a call to Dial2Verify API & Parse The JSON Response
759
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
760
		$RequestPayload = $this->make_request($VerificationCall,null);
761
		// $RequestPayload = json_decode($response,true);
762
 
763
		$VerifStatus=$RequestPayload["VerificationStatus"];
764
 
765
		$json["VerificationStatus"]=$VerifStatus;
766
 
767
	   	$this->response->type('json');
768
		$this->layout = 'ajax';
769
	    echo(json_encode($json));die;
770
	}
771
 
772
	public function skipmobileverification() {
773
		$this->Session->write('skipmobileverification',1);
13739 anikendra 774
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 775
	}
776
 
777
	public function reauthenticate($userId) {
778
		$user = $this->User->read(null,$userId);
779
		$this->Auth->login($user['User']);
780
		$json = array('success'=>true);
781
		$this->response->type('json');
782
		$this->layout = 'ajax';
14150 anikendra 783
	    echo(json_encode($json));die;
13736 anikendra 784
	}
13739 anikendra 785
}