Subversion Repositories SmartDukaan

Rev

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