Subversion Repositories SmartDukaan

Rev

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