Subversion Repositories SmartDukaan

Rev

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