Subversion Repositories SmartDukaan

Rev

Rev 17044 | Rev 17664 | 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);
282
		$result = curl_exec($ch);
283
		$this->log("[response] ".print_r($result,1),'api');
284
		//close connection
285
		curl_close($ch);
286
		switch($format){
287
			case 'json':
288
			$response = json_decode($result,1);
289
			break;
290
		}
291
		return $response;	
292
	}
14215 anikendra 293
 
13901 anikendra 294
	public function get_solr_result($q,$page) {
16363 anikendra 295
		$dealsperpage = Configure::read('searchresultsperpage');
13901 anikendra 296
		$offset = ($page - 1)*$dealsperpage;
13993 anikendra 297
		$cond = "$q";
13901 anikendra 298
	 	$sort = "store desc";
299
 
300
		$params = array(
301
			'conditions' =>array(
302
		 	'solr_query' => $cond
303
	 	),
304
		 	//'order' => $sort,
305
		 	'offset' => $offset,
306
		 	'limit' => $dealsperpage
307
	 	);
14215 anikendra 308
		$this->loadModel('Solr');		
13901 anikendra 309
		$solroutput = $this->Solr->find('all', $params);
310
		$result = array();
14215 anikendra 311
		if(sizeof($solroutput)<$dealsperpage){
312
			$hasMore = false;
313
		}else{
314
			$hasMore = true;
315
		}
13901 anikendra 316
		if(!empty($solroutput['Solr'])) {			
317
			$skuMap = array();
14215 anikendra 318
			foreach ($solroutput['Solr'] as $key => $value) {
14432 anikendra 319
				// if(!$value['in_stock'])continue;
13901 anikendra 320
				$skuMap[$value['id']] = $value;
321
				$result[$value['skuBundleId']][$value['id']] = $value['available_price'];
14215 anikendra 322
			}	
323
			if(!empty($result)) {
324
				foreach ($result as $key => $value) {					
325
					asort($value);
326
					$lowestPriceSku = key($value);
327
					$result[$key] = $skuMap[$lowestPriceSku];
328
				}
13901 anikendra 329
			}
14215 anikendra 330
		}		
331
		$result['hasMore'] = $hasMore;
13901 anikendra 332
		return $result;
333
	}
14098 anikendra 334
 
335
	public function admin_update(){
336
		$this->response->type('json');
337
		$this->layout = 'ajax';
338
		$data[$this->request->data['id']] = $this->request->data['value'];
339
		$data['oid'] = $this->request->data['oid'];
14584 anikendra 340
		$id = $this->request->data['id'];
341
		$multi = $this->request->data['multi'];
14098 anikendra 342
		if($this->modelClass == 'Exceptionalskudiscount') {
343
			$data['class'] = 'SkuDiscountInfo';	
344
		}elseif($this->modelClass == 'Skuscheme'){
16234 anikendra 345
			if($id == 'dp' || $id == 'showDp'){
14584 anikendra 346
				$data['class'] = 'SkuDealerPrices';
347
			}else{
348
				$data['class'] = 'SkuSchemeDetails';
349
			}
14426 anikendra 350
		}elseif($this->modelClass == 'Exceptionalnlc'){
351
			$data['class'] = 'ExceptionalNlc';
16494 anikendra 352
		}elseif($this->modelClass == 'ManualDeal' && ($id == 'dealPoints' || $id == 'dealThresholdPrice')){
353
			$data['class'] = 'DealPoints';
14426 anikendra 354
		}
355
		else{
14098 anikendra 356
			$data['class'] = $this->modelClass;
357
		}		
14584 anikendra 358
		$data_string = json_encode($data,JSON_NUMERIC_CHECK);		
14098 anikendra 359
		$ch = curl_init();
360
		$url = $this->apihost.'Catalog/updateCollection';
14584 anikendra 361
		if(isset($multi) && $multi==1){
362
			$url .= "/?multi=1";
363
		}		
14098 anikendra 364
		$this->log("[url] $url",'api');
365
		$this->log("[fields] ".print_r($data_string,1),'api');
366
		curl_setopt($ch, CURLOPT_URL, $url);
367
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
368
		curl_setopt($ch, CURLOPT_POST, true);
369
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // note the PUT here
370
 
371
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
372
		curl_setopt($ch, CURLOPT_HEADER, true);
373
 
374
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
375
		    'Content-Type: application/json',                                                                                
376
		    'Content-Length: ' . strlen($data_string)                                                                       
377
		));       
378
 
379
		// execute the request
380
 
381
		$output = curl_exec($ch);
382
		$result = $this->request->data['value'];
383
		$this->log("[response] ".print_r($output,1),'api');
384
		curl_close($ch);
385
		$this->set(array(
386
		    'result' => $result,
387
		    '_serialize' => array('result')
388
		));
389
		$this->render('/Elements/json');
390
	}
14150 anikendra 391
 
14509 anikendra 392
	public function remove($id,$class){
393
		$data['oid'] = $id;
394
		$data['class'] = $class;
395
 
396
		$data_string = json_encode($data,JSON_NUMERIC_CHECK);
397
		$ch = curl_init();
398
		$url = $this->apihost.'Catalog/deleteDocument';
399
		$this->log("[url] $url",'api');
400
		$this->log("[fields] ".print_r($data_string,1),'api');
401
		curl_setopt($ch, CURLOPT_URL, $url);
402
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
403
		curl_setopt($ch, CURLOPT_POST, true);
404
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // note the PUT here
405
 
406
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
15848 anikendra 407
		// curl_setopt($ch, CURLOPT_HEADER, true);
14509 anikendra 408
 
409
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
410
		    'Content-Type: application/json',                                                                                
411
		    'Content-Length: ' . strlen($data_string)                                                                       
412
		));       
413
 
414
		// execute the request
415
 
416
		$output = curl_exec($ch);
15848 anikendra 417
		// $result = $this->request->data['value'];
14509 anikendra 418
		$this->log("[response] ".print_r($output,1),'api');
419
		curl_close($ch);
420
		// $this->set(array(
421
		    // 'result' => $result,
422
		    // '_serialize' => array('result')
423
		// ));
424
		// $this->render('/Elements/json');
15848 anikendra 425
		$result = json_decode($output,1);
14509 anikendra 426
		return $result;
427
	}
428
 
14150 anikendra 429
	function getAutoLoginUrl($userId,$next) {
14996 anikendra 430
		$saholicoffline = Configure::read('saholicoffline');
431
		if($saholicoffline) {
432
			$url = "/abouts/saholicoffline";
433
			return $url;
434
		}
14150 anikendra 435
		$this->loadModel('User');
436
		$this->User->Behaviors->attach('Containable');
14166 anikendra 437
		$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
14150 anikendra 438
		$user = $this->User->find('first',$options);
15380 anikendra 439
		$this->log("user_accounts ".print_r($user,1),'headers');
14441 anikendra 440
		$data = array('email'=>$user['User']['email'],'Id'=>$user['UserAccount'][0]['account_key'],'cartId' => $user['UserAccount'][1]['account_key'],'isPrivateDealUser'=>1,'next'=>$next);
14150 anikendra 441
		$data = '?data='.base64_encode(serialize($data));
442
		$token = '&token='.md5(Configure::read('saholicapikey').'|'.$user['UserAccount'][0]['account_key']);		
15335 anikendra 443
		$url = Configure::read('saholicapihost')."login!authorizeProfitMandiUser?userId=".$user['UserAccount'][0]['account_key']."&source=ProfitMandi";
15380 anikendra 444
		$result = $this->make_request($url,null);
445
		$this->log(print_r($result,1),'headers');
15335 anikendra 446
		if(!empty($result['tokenString'])){
447
			$token = '&token='.$result['tokenString'];
448
			return Configure::read('saholicauthurl').$data.$token.'&v=2';
449
		}
14441 anikendra 450
		return Configure::read('saholicauthurl').$data.$token;
14150 anikendra 451
	}
14509 anikendra 452
 
453
 	function createUploadDirectory($modelClass) {
454
        //Create directory
455
        if (!is_dir(WWW_ROOT.'uploads'.DS.$modelClass)) {            
456
            $this->log("making directory for $modelClass". WWW_ROOT.DS.'uploads'.DS.$modelClass);
457
            mkdir(WWW_ROOT.'uploads'.DS.$modelClass,0777);
458
        }
459
        if (!is_dir(WWW_ROOT.'uploads'.DS.$modelClass)) {
460
            $this->log("failed to create directory for $modelClass");
461
            return false; 
462
        } else {
463
            return true;
464
        }
465
    }
466
 
467
    public function upload() {
468
        $result['status'] = 0; 
469
        $result['success'] = false;
470
        $result['message'] = __('Unable to upload');
471
 
472
        App::import('Vendor','qqFileUploader',array('file' =>'qqFileUploader.php'));
473
 
474
        $uploader = new qqFileUploader();
475
 
476
        // Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
477
        $uploader->allowedExtensions = array('jpeg','png','jpg','gif','bmp');
478
 
479
        // Specify max file size in bytes.
480
        $uploader->sizeLimit = 10 * 1024 * 1024;
481
 
482
        // Specify the input name set in the javascript.
483
        $uploader->inputName = 'qqfile';
484
 
485
        // If you want to use resume feature for uploader, specify the folder to save parts.
486
        $uploader->chunksFolder = 'chunks';
487
 
488
        // $min_width = isset($this->request->data['minwidth']) ? $this->request->data['minwidth'] : 0; 
489
        // $min_height = isset($this->request->data['minheight']) ? $this->request->data['minheight'] : 0; 
490
        $modelClass = $this->modelClass; 
491
 
492
        $this->log($this->request);
493
        $folderName = Inflector::pluralize(strtolower($modelClass));
494
 
495
        if (!$this->createUploadDirectory($folderName)) {
496
            $result['message'] = 'Failed to create directory :'.$modelClass.
497
            '.  Sorry we are having trouble.  Please try again, or email help@profittill.com';
498
        } else {
499
            // To save the upload with a specified name, set the second parameter
500
            $result = $uploader->handleUpload('uploads'.DS.$folderName.DS, $uploader->getName());
501
            if($result){
502
                //Resize and create thumbnail
503
                $inFile = WWW_ROOT.'uploads'.DS.$folderName.DS. $uploader->getName();
504
 
505
                $largeOutFile = WWW_ROOT.'uploads'.DS.$folderName.DS.'large-'.basename($inFile);
506
                $this->resizeImage($inFile,$largeOutFile,800,800);
507
 
508
                $outFile = WWW_ROOT.'uploads'.DS.$folderName.DS.'small-'.basename($inFile);
509
                $this->resizeImage($inFile,$outFile,200,200);
510
 
511
                $newUrl = '/uploads/'.$folderName.'/'.basename($inFile);
512
                // To return a name used for uploaded file you can use the following line.
513
                $result['uploadName'] = $newUrl;
514
 
515
                $result['status'] = 1;
516
                $result['success'] = true;
517
                // $result['filesize'] = $filesize;
518
                $result['message'] = __('Uploaded');
519
            }
520
        }
521
        $this->log($result);
522
        return new CakeResponse(array('body' => json_encode($result)));
523
    }
524
 
525
    function cropImage ($url, $height, $width, $x1, $x2, $y1, $y2) {
526
        ini_set('memory_limit', '2G');
527
        $result['status'] = 0; 
528
        $result['message'] = __('Unable to crop');
529
 
530
        $image_type = substr($url, strrpos($url, '.', -1)); 
531
        $filepath = WWW_ROOT.substr($url, strlen(FULL_BASE_URL)+1);
532
        $croppedfile = substr($filepath, 0, strrpos($filepath, '/', -1)).
533
            '/C_'.substr($filepath, strrpos($filepath, '/', -1)+1);
534
 
535
        // Create image instances
536
        $dest = imagecreatetruecolor($x2,$y2);
537
 
538
        switch ($image_type) {
539
            case '.jpg':
540
            case '.jpeg':
541
            case '.JPEG':
542
            case '.JPG':
543
                $src = imagecreatefromjpeg($filepath);
544
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
545
                imagejpeg($dest, $croppedfile);
546
                $ext = '.jpg';
547
                break;
548
            case '.gif':
549
                $src = imagecreatefromgif($filepath);
550
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
551
                imagegif($dest, $croppedfile);
552
                $ext = '.gif';
553
                break;
554
            case '.png':
555
                $src = imagecreatefrompng($filepath);
556
                imagecopyresampled($dest,$src,0,0,$x1,$y1,$x2,$y2,$width,$height);
557
                imagepng($dest, $croppedfile);
558
                $ext = '.png';
559
                break;
560
            default: 
561
                $result['message'] = __('Unsupported image format.');   
562
                return $result;
563
        }
564
        $result['status'] = 1; 
565
        $result['message'] = __('Cropped');
566
        $result['data'] = substr($url, 0, strrpos($url, '/', -1)).'/C_'.substr($url, strrpos($url, '/', -1)+1);
567
        return $result;
568
    }
569
 
570
    function resizeImage ($inFile, $outFile, $w, $h) {
571
        $image = $this->Resize;
572
        $image->load($inFile);                       
573
        $image->crop($w,$h);
574
        $image->save($outFile);
575
    }
576
 
577
    public function crop() {
578
        $url = $this->request->data['file_url'];
579
        $height = $this->request->data['h']; 
580
        $width = $this->request->data['w']; 
581
        $x1 = $this->request->data['x'];
582
        $x2 = $this->request->data['x2'];
583
        $y1 = $this->request->data['y'];
584
        $y2 = $this->request->data['y2'];
585
 
586
        $result = $this->cropImage($url, $height, $width, $x1, $x2, $y1, $y2);
587
 
588
        $this->set('result', $result);
589
        $this->set('_serialize', array('result'));
590
    }
14561 anikendra 591
 
592
    public function generateMultiUrl($url,&$data){
593
    	if(!empty($data['multi']) && $data['multi']==1){
594
    		$url .= '/?multi=1';    		
595
    	}
596
    	unset($data['multi']);
597
    	return $url;
598
    }
15378 anikendra 599
 
600
    public function markUserActivated($id){
15383 anikendra 601
    	$url = Configure::read('pythonapihost').'retailerActivated/'.$id;
15378 anikendra 602
    	$this->make_request($url,null);
603
    	$this->loadModel('User');
17044 anikendra 604
    	$sql = "UPDATE users SET activation_time = NOW() WHERE id = $id AND activation_time IS NULL";
15383 anikendra 605
    	$this->User->query($sql);
16966 anikendra 606
    	$this->loadModel('Appacl');
607
    	$data = array('user_id'=>$id,'access'=>1);
608
		$count = $this->Appacl->find('count',array('conditions'=> $data));
609
		if($count==0){
610
			$this->Appacl->create();
611
			$this->Appacl->save($data);
612
		}	
15378 anikendra 613
    }
15767 anikendra 614
}