Subversion Repositories SmartDukaan

Rev

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