Subversion Repositories SmartDukaan

Rev

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