Subversion Repositories SmartDukaan

Rev

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