Subversion Repositories SmartDukaan

Rev

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