Subversion Repositories SmartDukaan

Rev

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