Subversion Repositories SmartDukaan

Rev

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