Subversion Repositories SmartDukaan

Rev

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