Subversion Repositories SmartDukaan

Rev

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