Subversion Repositories SmartDukaan

Rev

Rev 20334 | Rev 20613 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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