Subversion Repositories SmartDukaan

Rev

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