Subversion Repositories SmartDukaan

Rev

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