Subversion Repositories SmartDukaan

Rev

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