Subversion Repositories SmartDukaan

Rev

Rev 20978 | 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('Controller', 'Controller');
3
 
4
/**
5
 * Application Controller
6
 *
7
 * Add your application-wide methods in the class below, your controllers
8
 * will inherit them.
9
 *
10
 * @package       app.Controller
11
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
12
 */
13
class AppController extends Controller {
13808 anikendra 14
 
15
	public $limit;
16
	public $apihost;
15311 anikendra 17
	public $acls;
13808 anikendra 18
 
13532 anikendra 19
	public $components = array(
14970 anikendra 20
		'Session','Resize','Cookie',
13532 anikendra 21
		'Auth' => array(
20861 amit.gupta 22
			'loginAction' => array('controller' => 'users', 'action' => 'login'),
23
			'allowedActions' => array('retry')
13532 anikendra 24
		)			
25
	);
13808 anikendra 26
 
13532 anikendra 27
	var $helpers = array('Session', 'Form', 'Html');
28
	var $keywords = array('instagram followers','instagram button','instagram follow back','instagram tool','instagram automation','free istagram followers','instagram stats','instagram follow button');
29
 
30
	function beforeFilter() {
20135 naman 31
		$this->Auth->autoRedirect = false;
32
		if($this->request->is('ajax')){
33
			$this->Auth->allow($this->params->params['action']);
34
		}
13579 anikendra 35
		//Set config settings according to domain
13532 anikendra 36
		// get host name from URL
37
		preg_match('@^(?:http://)?([^/]+)@i',$_SERVER['HTTP_HOST'], $matches);
38
		$host = $matches[1];
39
		switch($host){			
13567 anikendra 40
			case 'localdtr':
13532 anikendra 41
				Configure::load('dev');
42
				break;
13946 anikendra 43
			case 'staging.profittill.com':
44
			case 'www.staging.profittill.com':
13944 anikendra 45
				Configure::load('staging');
46
				break;
13532 anikendra 47
			default:
13567 anikendra 48
			case 'www.profittill.com':
49
			case 'profittill.com':
13633 anikendra 50
			case 'api.profittill.com':
13532 anikendra 51
				Configure::load('live');
52
				break;
53
		}
17639 naman 54
 
13579 anikendra 55
		$facebookConfig = Configure::read("Facebook");		
56
		$categories = Configure::read('Categories');
20135 naman 57
//		$allowedController = Configure::read('allowcontroller');
20107 naman 58
 
20135 naman 59
// 		if($this->params->params['controller'] == 'categories' || $this->params->params['controller'] == 'orders' 
60
// 	||  $this->params->params['controller'] == 'store_products' ||  $this->params->params['controller'] == 'brands')
61
// 		if(in_array($this->params->params['controller'] , $allowedController))		
62
// 		{
20107 naman 63
			//Check access for apps tab	
20135 naman 64
 
65
			$userId = $this->isAuthorized();
66
			if(!$userId){
67
				$userId = $this->request->query('user_id');
68
				if(isset($userId) && !empty($userId)) {
69
					$this->loadModel('User');
70
					$dbuser = $this->User->findById($userId);
20858 amit.gupta 71
					if($dbuser['User']['activated']==0) {
21163 amit.gupta 72
						if($this->params['controller']=='users' &&  $this->params['action']=='mine'){
73
 
74
						} else {
75
							return $this->redirect('/users/retry');
76
						}	
20858 amit.gupta 77
					}
20135 naman 78
					$this->Auth->login($dbuser['User']);
79
				}else
80
					return;
81
			}
16724 anikendra 82
			$cachekey = 'appacls-'.$userId;			
83
			$access = Cache::read($cachekey,'day');
84
			if(empty($access)) {
85
				$this->loadModel('Appacl');
86
				$this->Appacl->recursive = -1;
87
				$conditions = array('user_id'=>$userId);
88
				$access = $this->Appacl->find('first',array('conditions'=>$conditions));		
89
				if(empty($access) || $access['Appacl']['access']==0){
90
					unset($categories[2]);
91
					$this->set('noappcashback',true);
92
				}		
93
				Cache::write($cachekey,$access,'day');
94
			}
20135 naman 95
// 		}
13532 anikendra 96
		//Facebook configuration
97
		$this->set('fbappid', $facebookConfig['fbappid']);
13579 anikendra 98
		$this->set('apihost', Configure::read('apihost'));
13532 anikendra 99
	   	$sessionState = $this->Session->read('state');
100
		if(!isset($sessionState)){
101
			$this->Session->write('state' , md5(uniqid(rand(), TRUE))); // CSRF protection
102
		}
103
	 	$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
104
		   . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/') . "&state="
105
		   . $this->Session->read('state').'&scope=publish_stream,email,user_birthday,publish_actions,user_location';
106
	   	$this->set('dialog_url', $dialog_url);
107
		$this->set('description','Why spend money when you can get something for free');
13579 anikendra 108
		$this->set('categories',$categories);
13532 anikendra 109
		if(isset($this->params['admin'])) {
13739 anikendra 110
			$this->layout = 'admin';
13808 anikendra 111
		}	
112
		$this->apihost = Configure::read('pythonapihost');
113
		$this->limit = Configure::read('dealsperpage');	
13685 anikendra 114
		$staticVersion = Configure::read('staticversion');
115
		$this->set('staticversion',$staticVersion);
14929 anikendra 116
		$this->set('requiremobileverification',Configure::read('requiremobileverification'));			
20497 amit.gupta 117
 
15188 anikendra 118
		//acl
119
		$cachekey = 'acls';
120
		$acls = Cache::read($cachekey,'month');
121
		if(empty($acls)) {
122
			$acls = array();
123
			$this->loadModel('Acl');
124
			$result = $this->Acl->find('all');
125
			foreach ($result as $key => $value) {
126
				if($value['Acl']['access']) {
127
					$acls[$value['Acl']['group_id']]['allowed'][] = $value['Acl']['action'];
128
				}else{
129
					$acls[$value['Acl']['group_id']]['disallowed'][] = $value['Acl']['action'];
130
				}				
131
			}
132
			Cache::write($cachekey,$acls,'month');
133
		}
15311 anikendra 134
		$this->acls = $acls;
15188 anikendra 135
		$this->set('acls',$acls);
17885 manish.sha 136
 
137
		if(isset($_COOKIE['txn_comp']) && $_COOKIE['txn_comp']=='no'){
138
			$suserId = base64_decode($_COOKIE['s_id']);
139
			$scartId = base64_decode($_COOKIE['s_cart']);
140
			$semailId = base64_decode($_COOKIE['s_email']);
141
 
142
			$pincode = 0;
143
 
144
			if($pincode==0 && isset($_COOKIE['s_pincode'])){
145
				$pincode = base64_decode($_COOKIE['s_pincode']);
146
			}
147
			$cartItems = array();
20978 amit.gupta 148
			$postData = array('cartItems'	=>	$cartItems);
149
			$params = array('cartMap' => urlencode(json_encode($postData)));
17885 manish.sha 150
 
151
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
152
			if($pincode!='0'){
153
				$url = $url.'&pinCode='.$pincode;
154
			}
155
			$localCartHistory = $this->post_cartinfo_request($url,$params);
156
			if(isset($localCartHistory['response']) && $localCartHistory['response']=='error'){
157
				setcookie('txn_comp', 'no', -1, '/');
158
			}elseif(isset($localCartHistory['cartItems'])&& count($localCartHistory['cartItems'])==0) {
159
				setcookie('txn_comp', 'yes', -1, '/');
160
			}else{
161
				$this->set('localCartHistory',$localCartHistory);
162
			}
20327 amit.gupta 163
 
20329 amit.gupta 164
		}
20334 amit.gupta 165
		if($this->checkToken($userId)==1){
166
			ob_start();
167
			if(!@include("category.php")) {
168
				$this->set('outputcategory','');
169
			} else {
170
				$this->set('outputcategory', ob_get_clean());
171
			}
20333 amit.gupta 172
		}
17639 naman 173
 
13532 anikendra 174
    }
175
 
15311 anikendra 176
	function checkAcl() {		
177
    	if(!in_array($this->here,$this->acls[$this->Session->read('Auth.User.group_id')]['allowed'])){
15227 anikendra 178
    		$this->Session->setFlash(__('You are not authorized to access this page.'));
179
    		return $this->redirect(array('controller'=>'administration','action' => 'dashboard','admin'=>false));
180
    	}
181
    }
182
 
13532 anikendra 183
    function isAuthorized() {
184
        return $this->Auth->user('id');
185
    }
186
 
187
    function isFbAuthorized() {
188
        return $this->Session->read('facebook_id');
189
    }
190
 
191
    function afterFilter() {
13579 anikendra 192
		$result['ucadcode'] = $this->ucadcode;
13532 anikendra 193
    }
194
 
13659 anikendra 195
    function beforeRender() {   
13736 anikendra 196
    	$logged_user = $this->Auth->user();
197
    	$this->set('logged_user', $logged_user); 	
13579 anikendra 198
        $this->set('base_url', 'http://' . $_SERVER['SERVER_NAME'] . Router::url('/'));
13532 anikendra 199
    }
200
 
13736 anikendra 201
    function checkMobileNumber() {
202
    	$logged_user = $this->Auth->user();
203
    	if(empty($logged_user['mobile_verified']) && $this->params['controller'] !='users') {
204
			$skipmobileverification = $this->Session->read('skipmobileverification');
205
			if(!isset($skipmobileverification) || empty($skipmobileverification)) {
206
				$this->redirect('/users/verifymobile');
207
			}
208
		}
209
    }
210
 
15335 anikendra 211
    function checkToken($userId = null) {
212
        $headers =  $this->getallheaders();
14890 anikendra 213
        $this->log(print_r($headers,1),'headers');
14897 anikendra 214
        $token = $_COOKIE['token'];
15188 anikendra 215
        $checkToken = $_COOKIE['walletAuthentication'];
14894 anikendra 216
        $this->log("Token : $token",'headers');
15188 anikendra 217
        $this->log("CheckToken : $checkToken",'headers');
218
        if(isset($checkToken) && !empty($checkToken) && isset($token) && !empty($token)) {
15335 anikendra 219
                $this->loadModel('SocialProfile');
220
                $options = array('conditions'=>array('access_token'=>$token),'fields'=>array('user_id'),'recursive'=>-1);
221
                $user = $this->SocialProfile->find('first',$options);
15767 anikendra 222
                $this->log($userId." ".print_r($user['SocialProfile'],1),'headers');
15380 anikendra 223
                /*if(!$userId){
15335 anikendra 224
                	$userId = $this->request->query('user_id');
15767 anikendra 225
                }                */
15335 anikendra 226
                if(isset($userId) && !empty($userId)){
227
                    if($userId == $user['SocialProfile']['user_id']){
15380 anikendra 228
                    	$this->log("User authenticated",'headers');
15651 anikendra 229
                        return 1;//success
15335 anikendra 230
                    } else{
231
                    	// token mismatch, so maybe hack attempt
15380 anikendra 232
                    	$this->log("Mismatch hence user not authenticated",'headers');
15651 anikendra 233
                        return 0;//fail
15335 anikendra 234
                    }
235
                } else {
236
                	// userId is not sent so maybe hack attempt
15380 anikendra 237
                	$this->log("Id not sent hence user not authenticated",'headers');
15651 anikendra 238
                	return 0;//fail
15335 anikendra 239
                }
15380 anikendra 240
        } else {    
241
        	$this->log("Old User hence pass",'headers');            
16308 anikendra 242
            return -1;//token not set in cookie
14890 anikendra 243
        }
244
    }
245
 
13659 anikendra 246
    function getallheaders() { 
247
	   $headers = ''; 
248
       foreach ($_SERVER as $name => $value) 
249
       { 
250
	   if (substr($name, 0, 5) == 'HTTP_') 
251
	   { 
252
	       $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; 
253
	   } 
254
       } 
255
       return $headers; 
256
    } 
13633 anikendra 257
 
17682 naman 258
    public function getDealsApiUrl($page=1,$userId = null,$categoryId=0,$sort=null,$direction=null,$filter=null,$brands=null,$subcategories=null){
13808 anikendra 259
    	$this->log('categoryId '.$categoryId,'api');
260
    	$this->log('page '.$page,'api');
261
    	$offset = ($page - 1) * $this->limit;
17639 naman 262
 
13808 anikendra 263
    	if(isset($sort) && !empty($sort) && $sort!=-1){
264
    		$url = $this->apihost.'deals/'.$userId.'?categoryId='.$categoryId.'&sort='.$sort.'&direction='.$direction.'&limit='.$this->limit.'&offset='.$offset;
265
    	}else{
266
    		$url = $this->apihost.'deals/'.$userId.'?categoryId='.$categoryId.'&limit='.$this->limit.'&offset='.$offset;
17639 naman 267
    	}    
268
 
269
    	$get_url = "'".$_SERVER['REQUEST_URI']."'";
270
    	$urlArray = explode('=',$_SERVER['REQUEST_URI']);
271
		$last = $urlArray[sizeof($urlArray)-1];
272
 
273
    	if(!isset($filter) && empty($filter)){
17682 naman 274
    		// $get_url = "'".$_SERVER['REQUEST_URI']."'";
17639 naman 275
    		if (strpos($get_url,'filter=brand&brands') !== false)
276
    		{
277
    			$url .= "&filterData=brandFilter:".$last;
278
    			// echo $url;
279
    		}
17682 naman 280
    		if (strpos($get_url,'filter=subcategory&subcategories') !== false)
281
    		{
282
    			$url .= "&filterData=subCategoryFilter:".$last;
283
    			// echo "url",$url;
284
 
285
    		}
17639 naman 286
 
287
    	}
288
 
17682 naman 289
 
290
 
15015 anikendra 291
    	if(isset($filter) && !empty($filter)){
17682 naman 292
    		if(isset($brands) && !empty($brands)){
293
    			$url .= "&filterData=brandFilter:".$brands;
294
    			if(isset($subcategories) && !empty($subcategories)){
295
    				$url .= "|subCategoryFilter:".$subcategories;
296
    			}
297
    		}else{
298
    			if(isset($subcategories) && !empty($subcategories)){
299
    				$url .= "&filterData=subCategoryFilter:".$subcategories;
300
    			}
301
    		}
15015 anikendra 302
    	}
17682 naman 303
    	// print_r($url);
13808 anikendra 304
    	return $url;
305
    }
306
 
13633 anikendra 307
	function make_request($url,$fields,$format='json'){
13683 anikendra 308
		$this->log("[url] $url",'api');
309
		$this->log("[fields] ".print_r($fields,1),'api');
13633 anikendra 310
		$fields_string = '';
311
		//open connection
312
		$ch = curl_init();
313
		//set the url, number of POST vars, POST data
314
		curl_setopt($ch,CURLOPT_URL, $url);
315
		curl_setopt($ch,CURLOPT_RETURNTRANSFER , true);
316
		if(!empty($fields)) {
317
			curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
318
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
319
			    'Content-Type: application/json',                                                                                
13994 anikendra 320
			    // 'Content-Length: ' . sizeof($fields))                                                                       
321
			    'Content-Length: ' . strlen($fields))                                                                       
13633 anikendra 322
			);   
323
		}
324
		//execute post
325
		$result = curl_exec($ch);
15335 anikendra 326
		$this->log("[response] ".print_r($result,1),'api');
13633 anikendra 327
		//close connection
328
		curl_close($ch);
329
		switch($format){
330
			case 'json':
331
			$response = json_decode($result,1);
332
			break;
333
		}
334
		return $response;	
335
	}
17804 manish.sha 336
 
337
	function post_cartinfo_request($url,$fields,$format='json'){
338
		$this->log("[url] $url",'api');
339
		//$this->log("[fields] ".print_r($fields,1),'api');
340
		$fields_string = '';
341
		//open connection
342
		$ch = curl_init();
343
		//execute post
344
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
345
		rtrim($fields_string, '&');
346
		//set the url, number of POST vars, POST data
347
		curl_setopt($ch,CURLOPT_URL, $url);
348
		curl_setopt($ch,CURLOPT_POST, count($fields));
349
		curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
350
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
351
		curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
352
		$result = curl_exec($ch);
353
		//close connection
354
		curl_close($ch);
355
		switch($format){
356
			case 'json':
357
			$response = json_decode($result,1);
358
			break;
359
		}
360
		return $response;	
361
	}
362
 
14016 anikendra 363
	function post_request($url,$fields,$format='json'){
364
		$this->log("[url] $url",'api');
365
		$this->log("[fields] ".print_r($fields,1),'api');
366
		$fields_string = '';
367
		//open connection
368
		$ch = curl_init();
369
		//execute post
19233 amit.gupta 370
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.urlencode($value).'&'; }
14016 anikendra 371
		rtrim($fields_string, '&');
372
		//set the url, number of POST vars, POST data
373
		curl_setopt($ch,CURLOPT_URL, $url);
374
		curl_setopt($ch,CURLOPT_POST, count($fields));
375
		curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
376
		$result = curl_exec($ch);
377
		$this->log("[response] ".print_r($result,1),'api');
378
		//close connection
379
		curl_close($ch);
380
		switch($format){
381
			case 'json':
382
			$response = json_decode($result,1);
383
			break;
384
		}
385
		return $response;	
386
	}
14215 anikendra 387
 
13901 anikendra 388
	public function get_solr_result($q,$page) {
16363 anikendra 389
		$dealsperpage = Configure::read('searchresultsperpage');
13901 anikendra 390
		$offset = ($page - 1)*$dealsperpage;
13993 anikendra 391
		$cond = "$q";
13901 anikendra 392
	 	$sort = "store desc";
393
 
394
		$params = array(
395
			'conditions' =>array(
396
		 	'solr_query' => $cond
397
	 	),
398
		 	//'order' => $sort,
399
		 	'offset' => $offset,
400
		 	'limit' => $dealsperpage
401
	 	);
14215 anikendra 402
		$this->loadModel('Solr');		
13901 anikendra 403
		$solroutput = $this->Solr->find('all', $params);
404
		$result = array();
14215 anikendra 405
		if(sizeof($solroutput)<$dealsperpage){
406
			$hasMore = false;
407
		}else{
408
			$hasMore = true;
409
		}
13901 anikendra 410
		if(!empty($solroutput['Solr'])) {			
411
			$skuMap = array();
14215 anikendra 412
			foreach ($solroutput['Solr'] as $key => $value) {
14432 anikendra 413
				// if(!$value['in_stock'])continue;
13901 anikendra 414
				$skuMap[$value['id']] = $value;
415
				$result[$value['skuBundleId']][$value['id']] = $value['available_price'];
14215 anikendra 416
			}	
417
			if(!empty($result)) {
418
				foreach ($result as $key => $value) {					
419
					asort($value);
420
					$lowestPriceSku = key($value);
421
					$result[$key] = $skuMap[$lowestPriceSku];
422
				}
13901 anikendra 423
			}
14215 anikendra 424
		}		
425
		$result['hasMore'] = $hasMore;
13901 anikendra 426
		return $result;
427
	}
14098 anikendra 428
 
429
	public function admin_update(){
430
		$this->response->type('json');
431
		$this->layout = 'ajax';
432
		$data[$this->request->data['id']] = $this->request->data['value'];
433
		$data['oid'] = $this->request->data['oid'];
14584 anikendra 434
		$id = $this->request->data['id'];
435
		$multi = $this->request->data['multi'];
14098 anikendra 436
		if($this->modelClass == 'Exceptionalskudiscount') {
437
			$data['class'] = 'SkuDiscountInfo';	
438
		}elseif($this->modelClass == 'Skuscheme'){
16234 anikendra 439
			if($id == 'dp' || $id == 'showDp'){
14584 anikendra 440
				$data['class'] = 'SkuDealerPrices';
441
			}else{
442
				$data['class'] = 'SkuSchemeDetails';
443
			}
14426 anikendra 444
		}elseif($this->modelClass == 'Exceptionalnlc'){
445
			$data['class'] = 'ExceptionalNlc';
16494 anikendra 446
		}elseif($this->modelClass == 'ManualDeal' && ($id == 'dealPoints' || $id == 'dealThresholdPrice')){
447
			$data['class'] = 'DealPoints';
14426 anikendra 448
		}
449
		else{
14098 anikendra 450
			$data['class'] = $this->modelClass;
451
		}		
14584 anikendra 452
		$data_string = json_encode($data,JSON_NUMERIC_CHECK);		
14098 anikendra 453
		$ch = curl_init();
454
		$url = $this->apihost.'Catalog/updateCollection';
14584 anikendra 455
		if(isset($multi) && $multi==1){
456
			$url .= "/?multi=1";
457
		}		
14098 anikendra 458
		$this->log("[url] $url",'api');
459
		$this->log("[fields] ".print_r($data_string,1),'api');
460
		curl_setopt($ch, CURLOPT_URL, $url);
461
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
462
		curl_setopt($ch, CURLOPT_POST, true);
463
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // note the PUT here
464
 
465
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
466
		curl_setopt($ch, CURLOPT_HEADER, true);
467
 
468
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
469
		    'Content-Type: application/json',                                                                                
470
		    'Content-Length: ' . strlen($data_string)                                                                       
471
		));       
472
 
473
		// execute the request
474
 
475
		$output = curl_exec($ch);
476
		$result = $this->request->data['value'];
477
		$this->log("[response] ".print_r($output,1),'api');
478
		curl_close($ch);
479
		$this->set(array(
480
		    'result' => $result,
481
		    '_serialize' => array('result')
482
		));
483
		$this->render('/Elements/json');
484
	}
14150 anikendra 485
 
14509 anikendra 486
	public function remove($id,$class){
487
		$data['oid'] = $id;
488
		$data['class'] = $class;
489
 
490
		$data_string = json_encode($data,JSON_NUMERIC_CHECK);
491
		$ch = curl_init();
492
		$url = $this->apihost.'Catalog/deleteDocument';
493
		$this->log("[url] $url",'api');
494
		$this->log("[fields] ".print_r($data_string,1),'api');
495
		curl_setopt($ch, CURLOPT_URL, $url);
496
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
497
		curl_setopt($ch, CURLOPT_POST, true);
498
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // note the PUT here
499
 
500
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
15848 anikendra 501
		// curl_setopt($ch, CURLOPT_HEADER, true);
14509 anikendra 502
 
503
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
504
		    'Content-Type: application/json',                                                                                
505
		    'Content-Length: ' . strlen($data_string)                                                                       
506
		));       
507
 
508
		// execute the request
509
 
510
		$output = curl_exec($ch);
15848 anikendra 511
		// $result = $this->request->data['value'];
14509 anikendra 512
		$this->log("[response] ".print_r($output,1),'api');
513
		curl_close($ch);
514
		// $this->set(array(
515
		    // 'result' => $result,
516
		    // '_serialize' => array('result')
517
		// ));
518
		// $this->render('/Elements/json');
15848 anikendra 519
		$result = json_decode($output,1);
14509 anikendra 520
		return $result;
521
	}
522
 
14150 anikendra 523
	function getAutoLoginUrl($userId,$next) {
14996 anikendra 524
		$saholicoffline = Configure::read('saholicoffline');
525
		if($saholicoffline) {
526
			$url = "/abouts/saholicoffline";
527
			return $url;
528
		}
14150 anikendra 529
		$this->loadModel('User');
530
		$this->User->Behaviors->attach('Containable');
14166 anikendra 531
		$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
14150 anikendra 532
		$user = $this->User->find('first',$options);
15380 anikendra 533
		$this->log("user_accounts ".print_r($user,1),'headers');
14441 anikendra 534
		$data = array('email'=>$user['User']['email'],'Id'=>$user['UserAccount'][0]['account_key'],'cartId' => $user['UserAccount'][1]['account_key'],'isPrivateDealUser'=>1,'next'=>$next);
14150 anikendra 535
		$data = '?data='.base64_encode(serialize($data));
536
		$token = '&token='.md5(Configure::read('saholicapikey').'|'.$user['UserAccount'][0]['account_key']);		
15335 anikendra 537
		$url = Configure::read('saholicapihost')."login!authorizeProfitMandiUser?userId=".$user['UserAccount'][0]['account_key']."&source=ProfitMandi";
15380 anikendra 538
		$result = $this->make_request($url,null);
539
		$this->log(print_r($result,1),'headers');
15335 anikendra 540
		if(!empty($result['tokenString'])){
541
			$token = '&token='.$result['tokenString'];
542
			return Configure::read('saholicauthurl').$data.$token.'&v=2';
543
		}
14441 anikendra 544
		return Configure::read('saholicauthurl').$data.$token;
14150 anikendra 545
	}
14509 anikendra 546
 
20613 amit.gupta 547
	function getBigUtsavAutoLoginUrl($userId,$next) {
548
		$saholicoffline = Configure::read('saholicoffline');
549
		if($saholicoffline) {
550
			$url = "/abouts/saholicoffline";
551
			return $url;
552
		}
553
		$this->loadModel('User');
554
		$this->User->Behaviors->attach('Containable');
555
		$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
556
		$user = $this->User->find('first',$options);
557
		$this->log("user_accounts ".print_r($user,1),'headers');
558
		$data = array('email'=>$user['User']['email'],'Id'=>$user['UserAccount'][0]['account_key'],'cartId' => $user['UserAccount'][1]['account_key'],'isPrivateDealUser'=>1,'next'=>$next);
559
		$data = '?data='.base64_encode(serialize($data));
560
		$token = '&token='.md5(Configure::read('saholicapikey').'|'.$user['UserAccount'][0]['account_key']);		
561
		$url = Configure::read('saholicapihost')."login!authorizeProfitMandiUser?userId=".$user['UserAccount'][0]['account_key']."&source=ProfitMandi";
562
		$result = $this->make_request($url,null);
563
		$this->log(print_r($result,1),'headers');
564
		if(!empty($result['tokenString'])){
565
			$token = '&token='.$result['tokenString'];
566
			return Configure::read('bigutsavauthurl').$data.$token.'&v=2';
567
		}
568
		return Configure::read('bigutsavauthurl').$data.$token;
569
	}
570
 
14509 anikendra 571
 	function createUploadDirectory($modelClass) {
572
        //Create directory
573
        if (!is_dir(WWW_ROOT.'uploads'.DS.$modelClass)) {            
574
            $this->log("making directory for $modelClass". WWW_ROOT.DS.'uploads'.DS.$modelClass);
575
            mkdir(WWW_ROOT.'uploads'.DS.$modelClass,0777);
576
        }
577
        if (!is_dir(WWW_ROOT.'uploads'.DS.$modelClass)) {
578
            $this->log("failed to create directory for $modelClass");
579
            return false; 
580
        } else {
581
            return true;
582
        }
583
    }
584
 
585
    public function upload() {
586
        $result['status'] = 0; 
587
        $result['success'] = false;
588
        $result['message'] = __('Unable to upload');
589
 
590
        App::import('Vendor','qqFileUploader',array('file' =>'qqFileUploader.php'));
591
 
592
        $uploader = new qqFileUploader();
593
 
594
        // Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
595
        $uploader->allowedExtensions = array('jpeg','png','jpg','gif','bmp');
596
 
597
        // Specify max file size in bytes.
598
        $uploader->sizeLimit = 10 * 1024 * 1024;
599
 
600
        // Specify the input name set in the javascript.
601
        $uploader->inputName = 'qqfile';
602
 
603
        // If you want to use resume feature for uploader, specify the folder to save parts.
604
        $uploader->chunksFolder = 'chunks';
605
 
606
        // $min_width = isset($this->request->data['minwidth']) ? $this->request->data['minwidth'] : 0; 
607
        // $min_height = isset($this->request->data['minheight']) ? $this->request->data['minheight'] : 0; 
608
        $modelClass = $this->modelClass; 
609
 
610
        $this->log($this->request);
611
        $folderName = Inflector::pluralize(strtolower($modelClass));
612
 
613
        if (!$this->createUploadDirectory($folderName)) {
614
            $result['message'] = 'Failed to create directory :'.$modelClass.
615
            '.  Sorry we are having trouble.  Please try again, or email help@profittill.com';
616
        } else {
617
            // To save the upload with a specified name, set the second parameter
618
            $result = $uploader->handleUpload('uploads'.DS.$folderName.DS, $uploader->getName());
619
            if($result){
620
                //Resize and create thumbnail
621
                $inFile = WWW_ROOT.'uploads'.DS.$folderName.DS. $uploader->getName();
622
 
623
                $largeOutFile = WWW_ROOT.'uploads'.DS.$folderName.DS.'large-'.basename($inFile);
624
                $this->resizeImage($inFile,$largeOutFile,800,800);
625
 
626
                $outFile = WWW_ROOT.'uploads'.DS.$folderName.DS.'small-'.basename($inFile);
627
                $this->resizeImage($inFile,$outFile,200,200);
628
 
629
                $newUrl = '/uploads/'.$folderName.'/'.basename($inFile);
630
                // To return a name used for uploaded file you can use the following line.
631
                $result['uploadName'] = $newUrl;
632
 
633
                $result['status'] = 1;
634
                $result['success'] = true;
635
                // $result['filesize'] = $filesize;
636
                $result['message'] = __('Uploaded');
637
            }
638
        }
639
        $this->log($result);
640
        return new CakeResponse(array('body' => json_encode($result)));
641
    }
642
 
643
    function cropImage ($url, $height, $width, $x1, $x2, $y1, $y2) {
644
        ini_set('memory_limit', '2G');
645
        $result['status'] = 0; 
646
        $result['message'] = __('Unable to crop');
647
 
648
        $image_type = substr($url, strrpos($url, '.', -1)); 
649
        $filepath = WWW_ROOT.substr($url, strlen(FULL_BASE_URL)+1);
650
        $croppedfile = substr($filepath, 0, strrpos($filepath, '/', -1)).
651
            '/C_'.substr($filepath, strrpos($filepath, '/', -1)+1);
652
 
653
        // Create image instances
654
        $dest = imagecreatetruecolor($x2,$y2);
655
 
656
        switch ($image_type) {
657
            case '.jpg':
658
            case '.jpeg':
659
            case '.JPEG':
660
            case '.JPG':
661
                $src = imagecreatefromjpeg($filepath);
662
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
663
                imagejpeg($dest, $croppedfile);
664
                $ext = '.jpg';
665
                break;
666
            case '.gif':
667
                $src = imagecreatefromgif($filepath);
668
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
669
                imagegif($dest, $croppedfile);
670
                $ext = '.gif';
671
                break;
672
            case '.png':
673
                $src = imagecreatefrompng($filepath);
674
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
675
                imagepng($dest, $croppedfile);
676
                $ext = '.png';
677
                break;
678
            default: 
679
                $result['message'] = __('Unsupported image format.');   
680
                return $result;
681
        }
682
        $result['status'] = 1; 
683
        $result['message'] = __('Cropped');
684
        $result['data'] = substr($url, 0, strrpos($url, '/', -1)).'/C_'.substr($url, strrpos($url, '/', -1)+1);
685
        return $result;
686
    }
687
 
688
    function resizeImage ($inFile, $outFile, $w, $h) {
689
        $image = $this->Resize;
690
        $image->load($inFile);                       
691
        $image->crop($w,$h);
692
        $image->save($outFile);
693
    }
694
 
695
    public function crop() {
696
        $url = $this->request->data['file_url'];
697
        $height = $this->request->data['h']; 
698
        $width = $this->request->data['w']; 
699
        $x1 = $this->request->data['x'];
700
        $x2 = $this->request->data['x2'];
701
        $y1 = $this->request->data['y'];
702
        $y2 = $this->request->data['y2'];
703
 
704
        $result = $this->cropImage($url, $height, $width, $x1, $x2, $y1, $y2);
705
 
706
        $this->set('result', $result);
707
        $this->set('_serialize', array('result'));
708
    }
14561 anikendra 709
 
710
    public function generateMultiUrl($url,&$data){
711
    	if(!empty($data['multi']) && $data['multi']==1){
712
    		$url .= '/?multi=1';    		
713
    	}
714
    	unset($data['multi']);
715
    	return $url;
716
    }
15378 anikendra 717
 
718
    public function markUserActivated($id){
15383 anikendra 719
    	$url = Configure::read('pythonapihost').'retailerActivated/'.$id;
15378 anikendra 720
    	$this->make_request($url,null);
721
    	$this->loadModel('User');
17044 anikendra 722
    	$sql = "UPDATE users SET activation_time = NOW() WHERE id = $id AND activation_time IS NULL";
15383 anikendra 723
    	$this->User->query($sql);
16966 anikendra 724
    	$this->loadModel('Appacl');
725
    	$data = array('user_id'=>$id,'access'=>1);
726
		$count = $this->Appacl->find('count',array('conditions'=> $data));
727
		if($count==0){
728
			$this->Appacl->create();
729
			$this->Appacl->save($data);
730
		}	
15378 anikendra 731
    }
18111 amit.gupta 732
 
733
	function post_request_dont_use($url,$fields,$format='json'){
734
		$this->log("[url] $url",'api');
735
		$this->log("[fields] ".print_r($fields,1),'api');
736
		$fields_string = '';
737
		//open connection
738
		$ch = curl_init();
739
		//execute post
740
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
741
		rtrim($fields_string, '&');
742
		//set the url, number of POST vars, POST data
743
		curl_setopt($ch,CURLOPT_URL, $url);
744
		curl_setopt($ch,CURLOPT_POST, count($fields));
745
		curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
746
		curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: multpipart/form-data'));
747
		$result = curl_exec($ch);
748
		$this->log("[response] ".print_r($result,1),'api');
749
		//close connection
750
		curl_close($ch);
751
		switch($format){
752
			case 'json':
753
			$response = json_decode($result,1);
754
			break;
755
		}
756
		return $response;	
757
	}
19610 naman 758
 
759
	public function getuseroffer(){
760
		//check for offer start
761
		$user_id = $this->Auth->user('id');
762
		$cachekey = 'target-'.$user_id;
763
		$getoffer = Cache::read($cachekey,'target');
764
		$current_time = time();
765
		$offerresponse = "";
766
		if(empty($getoffer) || $getoffer === false){
767
			$offerurl = $this->apihost."getOfferForUser/?user_id=".$user_id;
768
			$offerresponse = $this->make_request($offerurl,null);
769
			Cache::write($cachekey , $offerresponse ,'target');
770
			if(!empty($offerresponse)){
771
 
772
				if($offerresponse['startDate']/1000 <= $current_time && $offerresponse['endDate']/1000 >= $current_time ){
773
 
774
				}
775
				else{
776
					$offerresponse = "";
777
				}
778
			}
779
			else{
780
				$offerresponse = "";
781
			}
782
		}else{
783
			if(!empty($getoffer)){
784
				$offerresponse = $getoffer;
785
				if($offerresponse['startDate']/1000 <= $current_time && $offerresponse['endDate']/1000 >= $current_time ){
786
 
787
				}
788
				else{
789
					$offerresponse = "";
790
				}
791
			}
792
 
793
		}
794
		return $offerresponse;	
795
		//check for offer end
796
	}
19990 naman 797
 
798
	public function getpin(){
799
		$getpin = $this->Auth->user('pincode');
800
		if(!isset($getpin)){
801
			$userId = $this->Auth->user('id');
802
			$pinquery = "select pincode from all_user_addresses where user_id = '".$userId."' and pincode is not Null limit 1";
803
			$pinres = $this->Category->query($pinquery);
804
			if(!empty($pinres)){
805
				$getpin =  $pinres[0]['all_user_addresses']['pincode'];
806
			}
807
		}
808
		if(!isset($getpin) && empty($getpin)){
809
			$getpin = '';
810
		}
811
		return $getpin;
812
	}
813
 
15767 anikendra 814
}