Subversion Repositories SmartDukaan

Rev

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