Subversion Repositories SmartDukaan

Rev

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