Subversion Repositories SmartDukaan

Rev

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