Subversion Repositories SmartDukaan

Rev

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

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