Subversion Repositories SmartDukaan

Rev

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