Subversion Repositories SmartDukaan

Rev

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