Subversion Repositories SmartDukaan

Rev

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