Subversion Repositories SmartDukaan

Rev

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