Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6749 | Rev 6804 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
/**
3
 *
4
 * Este controllador agrupa las funciones de Callback para todas las operaciones de OAUTH
5
 */
6
namespace LeadersLinked\Controller;
7
 
6803 efrain 8
 
1 www 9
use Laminas\Db\Adapter\AdapterInterface;
6749 efrain 10
use LeadersLinked\Cache\CacheInterface;
1 www 11
use Laminas\Mvc\Controller\AbstractActionController;
12
use Laminas\Log\LoggerInterface;
13
use Laminas\View\Model\JsonModel;
14
use GeoIp2\Database\Reader As GeoIp2Reader;
15
use LeadersLinked\Model\UserProvider;
16
use LeadersLinked\Mapper\UserMapper;
17
use LeadersLinked\Mapper\UserProviderMapper;
18
use LeadersLinked\Model\User;
19
use LeadersLinked\Model\UserType;
20
use LeadersLinked\Authentication\AuthSocialAdapter;
21
use LeadersLinked\Library\Functions;
22
use LeadersLinked\Library\Image;
23
use LeadersLinked\Library\Facebook;
24
use LeadersLinked\Model\Provider;
25
use LeadersLinked\Mapper\UserBrowserMapper;
26
use LeadersLinked\Model\UserBrowser;
27
use LeadersLinked\Mapper\UserIpMapper;
28
use LeadersLinked\Model\UserIp;
29
 
30
class OauthController extends AbstractActionController
31
{
32
    /**
33
     *
34
     * @var AdapterInterface
35
     */
36
    private $adapter;
37
 
38
    /**
39
     *
6749 efrain 40
     * @var CacheInterface
1 www 41
     */
42
    private $cache;
43
 
44
    /**
45
     *
46
     * @var  LoggerInterface
47
     */
48
    private $logger;
49
 
50
 
51
    /**
52
     *
53
     * @var array
54
     */
55
    private $config;
56
 
57
 
58
 
59
    /**
60
     *
61
     * @param AdapterInterface $adapter
6749 efrain 62
     * @param CacheInterface $cache
1 www 63
     * @param LoggerInterface $logger
64
     * @param array $config
65
     */
66
    public function __construct($adapter, $cache , $logger, $config)
67
    {
68
        $this->adapter      = $adapter;
69
        $this->cache        = $cache;
70
        $this->logger       = $logger;
71
        $this->config       = $config;
72
    }
73
 
74
    public function indexAction()
75
    {
76
        return new JsonModel(['success' => false, 'error' => 'Missing authentication']);
77
    }
78
 
79
    /**
80
     *
81
     * @param string $id
82
     * @param string $name
83
     * @param string $email
84
     * @param string $picture
85
     * @param string $provider
86
     */
87
    private function process($id , $name, $email, $picture, $provider)
88
    {
89
        $flashMessenger = $this->plugin('FlashMessenger');
90
        if(empty($id) || empty($name) || empty($email))
91
        {
92
            if($provider == UserProvider::PROVIDER_FACEBOOK) {
93
                $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
94
            }
95
            if($provider == UserProvider::PROVIDER_TWITTER) {
96
                $flashMessenger->addErrorMessage('ERROR_TWITTER_AUTH');
97
            }
98
            if($provider == UserProvider::PROVIDER_GOOGLE) {
99
                $flashMessenger->addErrorMessage('ERROR_GOOGLE_AUTH');
100
            }
101
 
102
            $this->logger->err('Parámetro(s) inválido(s) [id = ' . $id . ' email = ' . $email .' name = ' . $name . ' picture = ' . $picture, ['ip' => Functions::getUserIP()]);
103
 
104
            return  $this->redirect()->toRoute('home');
105
        }
106
 
107
 
108
        $userMapper = UserMapper::getInstance($this->adapter);
109
        $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
110
        $userProvider = $userProviderMapper->fetchOneByIdAndProdiver($id, $provider);
111
 
112
        //El usuario tiene una sesión activa
113
        $currentUserPlugin = $this->plugin('currentUserPlugin');
114
        $currentUser = $currentUserPlugin->getUser();
115
        if($currentUser) {
116
 
117
            if(!$currentUser->image) {
118
                $this->downloadImage($picture, $currentUser, $userMapper);
119
            }
120
 
121
            if(!$userProvider) {
122
 
123
                $userProvider = new UserProvider();
124
                $userProvider->user_id = $currentUser->id;
125
                $userProvider->id = $id;
126
                $userProvider->name = $name;
127
                $userProvider->email = $email;
128
                $userProvider->image = $picture;
129
                $userProvider->provider = $provider;
130
 
131
                if($userProviderMapper->insert($userProvider)) {
132
 
133
                    if($provider == UserProvider::PROVIDER_FACEBOOK) {
134
                        $this->logger->info('Registro del token de Facebook', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
135
                    }
136
                    if($provider == UserProvider::PROVIDER_TWITTER) {
137
                        $this->logger->info('Registro del token de Twitter', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
138
                    }
139
                    if($provider == UserProvider::PROVIDER_GOOGLE) {
140
                        $this->logger->info('Registro del token de  Google', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
141
                    }
142
 
143
 
144
                } else {
145
                    $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
146
                }
147
            }
148
 
149
            $this->registerBroserAndIp($currentUser);
150
 
151
            return $this->redirect()->toRoute('account-settings', [], ['query'=>['tab'=>'nav-social-networks']]);
152
 
153
        } else {
154
            //El usuario no tiene sesión activa
155
 
156
            //Si existe la cuenta del provider en el sistema recuperamos el usuario
157
            if($userProvider) {
158
                $user = $userMapper->fetchOne($userProvider->user_id);
159
            } else {
160
                //Buscamos si esta registrado el usuario por email
161
                $user = $userMapper->fetchOneByEmail($email);
162
 
163
                //Creamos un usuario
164
                if(empty($user))
165
                {
166
 
167
 
168
 
169
                    $names = explode(' ', $name);
170
                    $user = new User();
171
                    $user->email                = $email;
172
                    $user->first_name           = $names[0];
173
                    $user->last_name            = count($names) > 1 ?  implode(' ', array_slice($names, 1)) : '';
174
                    $user->usertype_id          = UserType::USER;
175
                    $user->password             = '';
176
                    $user->activation_key       = '';
177
                    $user->status               = User::STATUS_ACTIVE;
178
                    $user->blocked              = User::BLOCKED_NO;
179
                    $user->email_verified       = User::EMAIL_VERIFIED_YES;
180
                    $user->login_attempt        = 0;
181
                    $user->balance              = 0;
182
 
183
 
184
                    if($userMapper->insert($user)) {
185
                        $this->logger->info('Creamos el usuario usando los datos del provider', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
186
 
187
                    } else {
188
                        $flashMessenger->addErrorMessage($userMapper->getError());
189
                        return  $this->redirect()->toRoute('home');
190
                    }
191
                    $user = $userMapper->fetchOne($user->id);
192
                }
193
                if($user) {
194
                    if(!$user->image) {
195
                        $this->downloadImage($picture, $user, $userMapper);
196
                    }
197
                    $userProvider = new UserProvider();
198
                    $userProvider->user_id = $user->id;
199
                    $userProvider->id = $id;
200
                    $userProvider->name = $name;
201
                    $userProvider->email = $email;
202
                    $userProvider->image = $picture;
203
                    $userProvider->provider = $provider;
204
 
205
                    if($userProviderMapper->insert($userProvider)) {
206
                        if($provider == UserProvider::PROVIDER_FACEBOOK) {
207
                            $this->logger->info('Registro del token de Facebook', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
208
                        }
209
                        if($provider == UserProvider::PROVIDER_TWITTER) {
210
                            $this->logger->info('Registro del token de Twitter', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
211
                        }
212
                        if($provider == UserProvider::PROVIDER_GOOGLE) {
213
                            $this->logger->info('Registro del token de  Google', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
214
                        }
215
                    }
216
                }
217
            }
218
 
219
 
220
 
221
            $authSocialAdapter = new AuthSocialAdapter($this->adapter, $this->logger);
222
            $authSocialAdapter->setData($id, $provider);
223
 
224
            $authService = new \Laminas\Authentication\AuthenticationService();
225
            $authService->setAdapter($authSocialAdapter);
226
 
227
 
228
            $result = $authService->authenticate();
229
            if($result->getCode() == \Laminas\Authentication\Result::SUCCESS)
230
            {
231
                if($provider == UserProvider::PROVIDER_FACEBOOK) {
232
                    $this->logger->info('Acceso Facebook', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
233
                }
234
                if($provider == UserProvider::PROVIDER_TWITTER) {
235
                    $this->logger->info('Acceso Twitter', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
236
                }
237
                if($provider == UserProvider::PROVIDER_GOOGLE) {
238
                    $this->logger->info('Acceso Google', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
239
                }
240
 
241
                $this->registerBroserAndIp($user);
242
 
243
 
244
                return $this->redirect()->toRoute('dashboard');
245
            }
246
            else
247
            {
248
                $message = $result->getMessages()[0];
249
                $flashMessenger->addErrorMessage($message);
250
 
251
                return  $this->redirect()->toRoute('home');
252
            }
253
        }
254
    }
255
 
256
    /**
257
     *
258
     * @param string $picture
259
     * @param User $user
260
     * @param UserMapper $userMapper
261
     */
262
    private function downloadImage($picture, $user, $userMapper)
263
    {
264
        $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
265
 
266
        $picture_content = file_get_contents($picture);
267
        if($picture_content) {
268
            $temp_file = tempnam(sys_get_temp_dir(), 'Tux');
269
            file_put_contents($temp_file, $picture_content);
270
 
271
            $target_filename    = 'user-' . uniqid() . '.png';
272
            list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
273
            $source             = $temp_file;
274
            $crop_to_dimensions = true;
275
            if(Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
276
                $user->image = $target_filename;
277
                $userMapper->updateImage($user);
278
            }
279
        }
280
    }
281
 
282
    public function facebookAction()
283
    {
6749 efrain 284
        /*
1 www 285
        $flashMessenger = $this->plugin('FlashMessenger');
286
 
287
        $app_id = $this->config['leaderslinked.facebook.app_id'];
288
        $app_password = $this->config['leaderslinked.facebook.app_password'];
289
        $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
290
 
291
 
292
 
293
        if(!isset($_GET['code']) && !isset($_GET['state']))
294
        {
295
            $flashMessenger->addErrorMessage('Facebook code or state not available');
296
            return $this->redirect()->toRoute('home');
297
        }
6749 efrain 298
        //$code   = Functions::sanitizeFilterString($_GET['code']);
299
        $state  = Functions::sanitizeFilterString($_GET['state']);
1 www 300
 
301
        $fb = new \Facebook\Facebook([
302
            'app_id' => $app_id,
303
            'app_secret' => $app_password,
304
            'default_graph_version' => $app_graph_version
305
        ]);
306
 
307
        $helper = $fb->getRedirectLoginHelper();
308
        $helper->getPersistentDataHandler()->set('state', $state);
309
 
310
        $accessToken = null;
311
        try {
312
            $accessToken = $helper->getAccessToken();
313
        }
314
        catch(\Facebook\Exceptions\FacebookResponseException $e)
315
        {
316
            $this->logger->err('Facebook Graph: ' . $e->getMessage(), ['ip' => Functions::getUserIP()]);
317
            $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
318
 
319
            return $this->redirect()->toRoute('home');
320
        }
321
        catch(\Facebook\Exceptions\FacebookSDKException $e)
322
        {
323
            $this->logger->err('Facebook SDK: ' . $e->getMessage(), ['ip' => Functions::getUserIP()]);
324
            $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
325
 
326
            return $this->redirect()->toRoute('home');
327
        }
328
 
329
 
330
 
331
        if (!$accessToken) {
332
            if ($helper->getError()) {
333
                $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
334
                $this->logger->err($helper->getErrorDescription(), ['ip' => Functions::getUserIP()]);
335
 
336
                return $this->redirect()->toRoute('home');
337
            } else {
338
                $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
339
                $this->logger->err('Facebook Bad request', ['ip' => Functions::getUserIP()]);
340
 
341
 
342
                return $this->redirect()->toRoute('home');
343
            }
344
        }
345
 
346
        try {
347
            $response = $fb->get('/me?fields=id,name,email,picture',  $accessToken->getValue());
348
        } catch(\Facebook\Exceptions\FacebookResponseException $e) {
349
            $this->logger->err('Facebook Graph: ' . $e->getMessage(), ['ip' => Functions::getUserIP()]);
350
            $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
351
 
352
        } catch(\Facebook\Exceptions\FacebookSDKException $e) {
353
            $this->logger->err('Facebook SDK: ' . $e->getMessage(), ['ip' => Functions::getUserIP()]);
354
            $flashMessenger->addErrorMessage('ERROR_FACEBOOK_AUTH');
355
 
356
            return $this->redirect()->toRoute('home');
357
        }
358
 
359
        $fb_user = $response->getGraphUser();
360
        if(is_object($fb_user)) {
6749 efrain 361
            $id      = Functions::sanitizeFilterString($fb_user->getId());
362
            $name    = Functions::sanitizeFilterString($fb_user->getName());
1 www 363
            $email   = filter_var($fb_user->getEmail(), FILTER_SANITIZE_EMAIL);
364
            $picture = $fb_user->getPicture();
365
            if(is_array($picture)) {
366
                $picture = filter_var($picture['url'], FILTER_SANITIZE_URL);
367
            } else if(is_object($picture)) {
368
                $picture = filter_var($picture->getUrl(), FILTER_SANITIZE_URL);
369
            } else {
370
                $picture = filter_var($picture, FILTER_SANITIZE_URL);
371
            }
372
        }
373
 
374
        return $this->process($id, $name, $email, $picture, UserProvider::PROVIDER_FACEBOOK);
6749 efrain 375
        */
1 www 376
    }
377
 
378
    public function facebookDeleteAction()
379
    {
380
        error_log('---START FACEBOOK DELETE---');
381
        error_log('GET');
382
        error_log(print_r($_GET, true));
383
        error_log('POST');
384
        error_log(print_r($_POST, true));
385
        error_log('---END FACEBOOK DELETE---');
386
 
387
 
388
        return new JsonModel([
389
            'success' => true,
390
        ]);
391
 
392
    }
393
 
394
    public function facebookCancelAction()
395
    {
6749 efrain 396
        $signed_request = $_POST['signed_request'] ? Functions::sanitizeFilterString($_POST['signed_request']) : '';
1 www 397
        if($signed_request) {
398
            $facebook = new \LeadersLinked\Library\Facebook($this->config);
399
            $data = $facebook->parse_signed_request($signed_request);
400
            if($data && $data['user_id']) {
401
                $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
402
                $userProvider = $userProviderMapper->fetchOneByIdAndProdiver($data['user_id'], Provider::FACEBOOK);
403
                if($userProvider) {
404
                    if($userProviderMapper->deleteByIdAndProvider($userProvider->id, $userProvider->provider)) {
405
                        $this->logger->info('Se borro la cuenta de Facebook');
406
                        return new JsonModel([
407
                            'success' => true,
408
                        ]);
409
                    }
410
                }
411
            }
412
        }
413
 
414
        return new JsonModel([
415
            'success' => false,
416
        ]);
417
    }
418
 
419
    public function googleAction()
420
    {
421
        $currentUserPlugin = $this->plugin('currentUserPlugin');
422
        $currentUser = $currentUserPlugin->getUser();
423
 
424
        $google = new \Google_Client();
425
        $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
426
        $google->setAccessType("offline");        // offline access
427
        $google->setIncludeGrantedScopes(true);   // incremental auth
428
 
429
        $google->addScope('profile');
430
        $google->addScope('email');
431
 
432
 
433
        if (! isset($_GET['code'])) {
434
            $auth_url = $google->createAuthUrl();
435
            return $this->redirect()->toUrl(filter_var($auth_url, FILTER_SANITIZE_URL));
436
        }
437
 
6749 efrain 438
        $google->authenticate(Functions::sanitizeFilterString($_GET['code']));
1 www 439
        $accessToken = $google->getAccessToken();
440
 
441
        if(empty($accessToken)) {
442
            $flashMessenger = $this->plugin('FlashMessenger');
443
            $flashMessenger->addErrorMessage('Google access token is wrong');
444
 
445
 
446
 
447
 
448
            return $this->redirect()->toRoute('home');
449
        }
450
 
451
        $userInfo   = $google->verifyIdToken();
452
        if(!is_array($userInfo) || empty($userInfo['sub']) || empty($userInfo['name']) || empty($userInfo['email']) || empty($userInfo['picture'])) {
453
            $flashMessenger = $this->plugin('FlashMessenger');
454
            $flashMessenger->addErrorMessage('Google verify token is wrong');
455
            return $this->redirect()->toRoute('home');
456
        }
457
 
6749 efrain 458
        $id         = Functions::sanitizeFilterString($userInfo['sub']);
459
        $name       =Functions::sanitizeFilterString($userInfo['name']);
1 www 460
        $email      = filter_var($userInfo['email'], FILTER_SANITIZE_EMAIL);
6749 efrain 461
        $picture    = filter_var($userInfo['picture'], FILTER_SANITIZE_URL);
1 www 462
 
463
        return $this->process($id, $name, $email, $picture, UserProvider::PROVIDER_GOOGLE);
464
    }
465
 
466
    public function twitterAction()
467
    {
468
        if($this->config['leaderslinked.runmode.sandbox']) {
469
 
470
            $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
471
            $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
472
 
473
        } else {
474
            $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
475
            $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
476
        }
477
 
478
        $twitterSession = new \Laminas\Session\Container('twitter');
479
 
480
        $request_token = [];
481
        $request_token['oauth_token']           = $twitterSession->oauth_token;
482
        $request_token['oauth_token_secret']    = $twitterSession->oauth_token_secret;
483
 
484
        if (isset($_GET['oauth_token']) && $request_token['oauth_token'] !== $_GET['oauth_token']) {
485
            // Abort! Something is wrong.
486
 
487
 
488
            $flashMessenger = $this->plugin('FlashMessenger');
489
            $flashMessenger->addErrorMessage('Twitter Oauth token is wrong');
490
            return $this->redirect()->toRoute('home');
491
        }
492
 
493
        $twitter = new  \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret, $request_token['oauth_token'], $request_token['oauth_token_secret']);
494
        $access_token = $twitter->oauth('oauth/access_token', ['oauth_verifier' => $_GET['oauth_verifier']]);
495
 
496
        $oauth_token        = $access_token['oauth_token'];
497
        $oauth_token_secret = $access_token['oauth_token_secret'];
498
 
499
        /*
500
         stdClass Object ( [id] => 144499524 [id_str] => 144499524 [name] => Efrain Yanez R [screen_name] => eyanezve [location] => [description] => [url] => [entities] => stdClass Object ( [description] => stdClass Object ( [urls] => Array ( ) ) ) [protected] => 1 [followers_count] => 30 [friends_count] => 44 [listed_count] => 0 [created_at] => Sun May 16 13:36:21 +0000 2010 [favourites_count] => 5 [utc_offset] => [time_zone] => [geo_enabled] => [verified] => [statuses_count] => 0 [lang] => [contributors_enabled] => [is_translator] => [is_translation_enabled] => [profile_background_color] => C0DEED [profile_background_image_url] => http://abs.twimg.com/images/themes/theme1/bg.png [profile_background_image_url_https] => https://abs.twimg.com/images/themes/theme1/bg.png [profile_background_tile] => [profile_image_url] => http://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png [profile_image_url_https] => https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png [profile_link_color] => 1DA1F2 [profile_sidebar_border_color] => C0DEED [profile_sidebar_fill_color] => DDEEF6 [profile_text_color] => 333333 [profile_use_background_image] => 1 [has_extended_profile] => 1 [default_profile] => 1 [default_profile_image] => 1 [following] => [follow_request_sent] => [notifications] => [translator_type] => none [suspended] => [needs_phone_verification] => [email] => eyanezve@gmail.com )
501
         */
502
 
503
 
504
        $twitter = new  \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret, $oauth_token, $oauth_token_secret);
505
        $response =  $twitter->get('account/verify_credentials', ['include_entities' => true, 'skip_status' => true, 'include_email' => true]);
506
 
6749 efrain 507
        $id         = $response->id ? Functions::sanitizeFilterString($response->id) : '';
508
        $name       = $response->name ? Functions::sanitizeFilterString($response->name) : '';
1 www 509
        $email      = isset($response->email) ? filter_var($response->email, FILTER_SANITIZE_EMAIL) : '';
510
        $picture    = isset($response->profile_image_url_https) ? filter_var($response->profile_image_url_https, FILTER_SANITIZE_URL) : '';
511
 
512
        return $this->process($id, $name, $email, $picture, UserProvider::PROVIDER_TWITTER);
513
    }
514
 
515
    private function registerBroserAndIp($user)
516
    {
517
        $navigator = get_browser(null, true);
518
        $device_type    =  $navigator['device_type'];
519
        $platform       =  $navigator['platform'];
520
        $browser        =  $navigator['browser'];
521
 
522
        $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
523
        $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
524
        if($userBrowser) {
525
            $userBrowserMapper->update($userBrowser);
526
        } else {
527
            $userBrowser = new UserBrowser();
528
            $userBrowser->user_id           = $user->id;
529
            $userBrowser->browser           = $browser;
530
            $userBrowser->platform          = $platform;
531
            $userBrowser->device_type       = $device_type;
532
            $userBrowser->is_tablet         = intval( $navigator['istablet']);
533
            $userBrowser->is_mobile_device  = intval( $navigator['ismobiledevice']);
534
            $userBrowser->version           = $navigator['version'];
535
 
536
            $userBrowserMapper->insert($userBrowser);
537
        }
538
        //
539
 
540
        $ip = Functions::getUserIP();
541
        $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
542
 
543
        $userIpMapper = UserIpMapper::getInstance($this->adapter);
544
        $userIp = $userIpMapper->fetch($user->id, $ip);
545
        if(empty($userIp)) {
546
 
547
            if($this->config['leaderslinked.runmode.sandbox']) {
548
                $filename = $this->config['leaderslinked.geoip2.production_database'];
549
            } else {
550
                $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
551
            }
552
 
553
            $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
554
            $record = $reader->city($ip);
555
            if($record) {
556
                $userIp = new UserIp();
557
                $userIp->user_id = $user->id;
558
                $userIp->city = utf8_decode($record->city->name);
559
                $userIp->state_code = utf8_decode($record->mostSpecificSubdivision->isoCode);
560
                $userIp->state_name = utf8_decode($record->mostSpecificSubdivision->name);
561
                $userIp->country_code = utf8_decode($record->country->isoCode);
562
                $userIp->country_name = utf8_decode($record->country->name);
563
                $userIp->ip = $ip;
564
                $userIp->latitude = $record->location->latitude;
565
                $userIp->longitude = $record->location->longitude;
566
                $userIp->postal_code =  $record->postal->code;
567
 
568
                $userIpMapper->insert($userIp);
569
            }
570
 
571
 
572
        } else {
573
            $userIpMapper->update($userIp);
574
        }
575
    }
576
}