Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 2019 | Rev 3639 | 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
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
8
use Laminas\Mvc\Controller\AbstractActionController;
9
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
use Laminas\View\Model\JsonModel;
13
use LeadersLinked\Mapper\UserMapper;
14
use LeadersLinked\Library\Functions;
15
use LeadersLinked\Mapper\UserPasswordMapper;
16
use LeadersLinked\Form\AccountSetting\NotificationSettingForm;
17
use LeadersLinked\Mapper\UserNotificationSettingMapper;
18
use LeadersLinked\Form\AccountSetting\ChangePasswordForm;
19
use LeadersLinked\Form\AccountSetting\ChangeImageForm;
20
use LeadersLinked\Library\Image;
21
use LeadersLinked\Form\AccountSetting\LocationForm;
22
use LeadersLinked\Model\Location;
23
use LeadersLinked\Mapper\LocationMapper;
24
use LeadersLinked\Form\AccountSetting\PrivacySettingForm;
25
use LeadersLinked\Mapper\UserProfileMapper;
26
use LeadersLinked\Form\AccountSetting\BasicForm;
27
use LeadersLinked\Form\Transaction\FundsAddForm;
28
use LeadersLinked\Mapper\UserBrowserMapper;
29
use LeadersLinked\Mapper\QueryMapper;
30
use LeadersLinked\Mapper\DeviceHistoryMapper;
31
use LeadersLinked\Mapper\DeviceMapper;
32
use Laminas\Hydrator\ArraySerializableHydrator;
33
use Laminas\Db\ResultSet\HydratingResultSet;
34
use Laminas\Paginator\Adapter\DbSelect;
35
use Laminas\Paginator\Paginator;
36
use LeadersLinked\Mapper\UserIpMapper;
37
use LeadersLinked\Model\Transaction;
38
use LeadersLinked\Model\Provider;
39
use LeadersLinked\Mapper\TransactionMapper;
40
use PayPalCheckoutSdk\Core\SandboxEnvironment;
41
use PayPalCheckoutSdk\Core\ProductionEnvironment;
42
use PayPalCheckoutSdk\Core\PayPalHttpClient;
43
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
44
use PayPalHttp\HttpException;
45
use LeadersLinked\Mapper\UserProviderMapper;
46
use LeadersLinked\Model\UserProvider;
47
use LeadersLinked\Model\UserPassword;
1979 efrain 48
use LeadersLinked\Model\UserDeleted;
49
use LeadersLinked\Mapper\UserDeletedMapper;
50
use LeadersLinked\Model\UserType;
51
use LeadersLinked\Model\User;
52
use LeadersLinked\Library\QueueEmail;
53
use LeadersLinked\Mapper\EmailTemplateMapper;
54
use LeadersLinked\Model\EmailTemplate;
1 www 55
 
56
class AccountSettingController extends AbstractActionController
57
{
58
    /**
59
     *
60
     * @var AdapterInterface
61
     */
62
    private $adapter;
63
 
64
 
65
    /**
66
     *
67
     * @var AbstractAdapter
68
     */
69
    private $cache;
70
 
71
    /**
72
     *
73
     * @var  LoggerInterface
74
     */
75
    private $logger;
76
 
77
    /**
78
     *
79
     * @var array
80
     */
81
    private $config;
82
 
83
 
84
 
85
 
86
    /**
87
     *
88
     * @param AdapterInterface $adapter
89
     * @param AbstractAdapter $cache
90
     * @param LoggerInterface $logger
91
     * @param array $config
92
     */
93
    public function __construct($adapter, $cache , $logger, $config)
94
    {
95
        $this->adapter      = $adapter;
96
        $this->cache        = $cache;
97
        $this->logger       = $logger;
98
        $this->config       = $config;
99
    }
100
 
101
    public function indexAction()
102
    {
103
        $request = $this->getRequest();
104
        if($request->isGet()) {
105
 
106
            $tab = filter_var($this->params()->fromQuery('tab'), FILTER_SANITIZE_STRING);
107
            if(!in_array($tab, ['nav-basic', 'nav-notification', 'nav-password', 'nav-image', 'nav-location', 'nav-privacy', 'nav-ips', 'nav-browsers', 'nav-transactions', 'nav-social-networks'])) {
108
                $tab = 'nav-basic';
109
            }
110
 
111
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
112
            if($sandbox) {
113
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
114
            } else {
115
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
116
            }
117
 
118
            $currentUserPlugin = $this->plugin('currentUserPlugin');
119
            $currentUser = $currentUserPlugin->getUser();
120
 
121
            $userUserNotificationSettingMapper = UserNotificationSettingMapper::getInstance($this->adapter);
122
            $userUserNotificationSetting = $userUserNotificationSettingMapper->fetchOne($currentUser->id);
123
 
124
            $formNotificationSetting = new NotificationSettingForm();
125
            $formNotificationSetting->setData((array) $userUserNotificationSetting );
126
 
127
            $formLocation = new LocationForm();
128
 
129
            if($currentUser->location_id) {
130
 
131
                $locationMapper = LocationMapper::getInstance($this->adapter);
132
                $location = $locationMapper->fetchOne($currentUser->location_id);
133
                if($location) {
134
                    $location_formatted_address = $location->formatted_address;
135
                    $formLocation->setData((array) $location);
136
                }
137
            } else {
138
                $location_formatted_address = '';
139
            }
140
 
141
            $facebook    = 0;
142
            $twitter     = 0;
143
            $google      = 0;
144
 
145
 
146
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
147
            $userProviders = $userProviderMapper->fetchAllByUserId($currentUser->id);
148
            foreach($userProviders as $userProvider)
149
            {
150
                switch($userProvider->provider)
151
                {
152
                    case  UserProvider::PROVIDER_FACEBOOK :
153
                        $facebook  = 1;
154
                        break;
155
 
156
                    case  UserProvider::PROVIDER_TWITTER :
157
                        $twitter = 1;
158
                        break;
159
 
160
                    case  UserProvider::PROVIDER_GOOGLE :
161
                        $google  = 1;
162
                        break;
163
 
164
                }
165
            }
166
 
167
            $hydrator = new ObjectPropertyHydrator();
168
            $user_data = $hydrator->extract($currentUser);
169
 
170
            $formBasic = new BasicForm();
171
            $formBasic->setData($user_data);
172
 
173
            $formChangePassword = new ChangePasswordForm();
174
            $formChangeImage = new ChangeImageForm($this->config);
175
            $formPrivacy = new PrivacySettingForm();
176
            $formPrivacy->setData([
177
                'show_in_search' => $currentUser->show_in_search,
178
            ]);
179
 
180
            $formAddFund = new FundsAddForm();
181
 
182
            $this->layout()->setTemplate('layout/layout.phtml');
183
            $viewModel = new ViewModel();
184
            $viewModel->setTemplate('leaders-linked/account-settings/index.phtml');
185
            $viewModel->setVariables([
186
                'tab' => $tab,
187
                'balance' => number_format(floatval($currentUser->balance), 2),
188
                'amounts' => [
189
                    '5' => '5 LABEL_USD',
190
                    '10' => '10 LABEL_USD',
191
                    '15' => '15 LABEL_USD',
192
                    '20' => '20 LABEL_USD',
193
                    '25' => '25 LABEL_USD',
194
                    '50' => '50 LABEL_USD',
195
                    '75' => '75 LABEL_USD',
196
                    '100' => '100 LABEL_USD',
197
                ],
198
                'usertype_id' => $currentUser->usertype_id,
199
                'image' => $this->url()->fromRoute('storage',['type' => 'user', 'code' => $currentUser->uuid, 'filename' => $currentUser->image]),
200
                'formNotificationSetting' => $formNotificationSetting,
201
                'formBasic' => $formBasic,
202
                'formChangePassword' => $formChangePassword,
203
                'formChangeImage' => $formChangeImage,
204
                'formLocation' => $formLocation,
205
                'formPrivacy' => $formPrivacy,
206
                'formAddFund' => $formAddFund,
207
                'config' => $this->config,
208
                'google_map_key' => $google_map_key,
209
                'location_formatted_address' => $location_formatted_address,
210
                'google' => $google,
211
                'facebook' => $facebook,
212
                'twitter' => $twitter,
213
 
214
            ]);
215
            return $viewModel ;
216
 
217
        } else {
218
            return new JsonModel([
219
                'success' => false,
220
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
221
            ]);
222
        }
223
    }
224
 
225
    public function notificationAction()
226
    {
227
        $request = $this->getRequest();
228
 
229
        if($request->isGet()) {
230
            $hydrator = new ObjectPropertyHydrator();
231
 
232
            $currentUserPlugin = $this->plugin('currentUserPlugin');
233
            $currentUser = $currentUserPlugin->getUser();
234
 
235
            $userUserNotificationSettingMapper = UserNotificationSettingMapper::getInstance($this->adapter);
236
            $userUserNotificationSetting = $userUserNotificationSettingMapper->fetchOne($currentUser->id);
237
 
238
 
239
            return new JsonModel([
240
               'success' => true,
241
               'data' => [
242
                   'receive_connection_request' => $userUserNotificationSetting->receive_connection_request ? 1 : 0,
243
                   'accept_my_request_connection' => $userUserNotificationSetting->accept_my_request_connection ? 1 : 0,
244
 
245
                   'receive_invitation_group' => $userUserNotificationSetting->receive_invitation_group ? 1 : 0,
246
                   'accept_my_request_join_group' => $userUserNotificationSetting->accept_my_request_join_group ? 1 : 0,
247
                   'receive_request_join_my_group' => $userUserNotificationSetting->receive_request_join_my_group ? 1 : 0,
248
 
249
 
250
                   'receive_invitation_company' => $userUserNotificationSetting->receive_invitation_company ? 1 : 0,
251
 
252
                   'like_my_feed' => $userUserNotificationSetting->like_my_feed ? 1 : 0,
253
                   'comment_my_feed' => $userUserNotificationSetting->comment_my_feed ? 1 : 0,
254
                   'share_my_feed' => $userUserNotificationSetting->share_my_feed ? 1 : 0,
255
                   'receive_inmail' => $userUserNotificationSetting->receive_inmail ? 1 : 0,
256
 
257
                   'receive_invitation_meeting' => $userUserNotificationSetting->receive_invitation_meeting ? 1 : 0,
258
                   'receive_reminder_meeting' => $userUserNotificationSetting->receive_reminder_meeting ? 1 : 0,
259
                   'receive_records_available_meeting' => $userUserNotificationSetting->receive_records_available_meeting ? 1 : 0,
260
 
261
               ]
262
            ]);
263
 
264
 
265
        } else  if($request->isPost()) {
266
 
267
            $dataPost = $request->getPost()->toArray();
268
            $form = new NotificationSettingForm();
269
            $form->setData($dataPost);
270
 
271
            if($form->isValid()) {
272
                $currentUserPlugin = $this->plugin('currentUserPlugin');
273
                $currentUser = $currentUserPlugin->getUser();
274
 
275
                $dataPost = (array) $form->getData();
276
                $hydrator = new ObjectPropertyHydrator();
277
 
278
                $userUserNotificationSettingMapper = UserNotificationSettingMapper::getInstance($this->adapter);
279
                $userUserNotificationSetting = $userUserNotificationSettingMapper->fetchOne($currentUser->id);
280
                $hydrator->hydrate($dataPost, $userUserNotificationSetting);
281
 
282
                if($userUserNotificationSettingMapper->update($userUserNotificationSetting)) {
283
                    $this->logger->info('Se guardo las preferencias de notificación', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
284
                    $data = [
285
                        'success'   => true,
286
                        'data'      => 'LABEL_NOTIFICATION_SETTINGS_UPDATE'
287
                    ];
288
                } else {
289
                    $data = [
290
                        'success'   => false,
291
                        'data'   => 'ERROR_UNKNOWN'
292
                    ];
293
                }
294
 
295
                return new JsonModel($data);
296
 
297
            } else {
298
                $messages = [];
299
 
300
 
301
 
302
                $form_messages = (array) $form->getMessages();
303
                foreach($form_messages  as $fieldname => $field_messages)
304
                {
305
 
306
                    $messages[$fieldname] = array_values($field_messages);
307
                }
308
 
309
                return new JsonModel([
310
                    'success'   => false,
311
                    'data'   => $messages
312
                ]);
313
            }
314
        }  else {
315
            $data = [
316
                'success' => false,
317
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
318
            ];
319
 
320
            return new JsonModel($data);
321
        }
322
 
323
        return new JsonModel($data);
324
 
325
    }
326
 
327
 
328
 
329
 
330
 
331
    public function passwordAction()
332
    {
333
        $request = $this->getRequest();
334
        if($request->isPost()) {
335
            $dataPost = $request->getPost()->toArray();
336
            $form = new ChangePasswordForm();
337
            $form->setData($dataPost);
338
 
339
            if($form->isValid()) {
340
                $data = (array) $form->getData();
341
                $password = $data['password'];
342
 
343
                $currentUserPlugin = $this->plugin('currentUserPlugin');
344
                $currentUser = $currentUserPlugin->getUser();
345
 
346
 
347
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
348
                $userPasswords = $userPasswordMapper->fetchAllByUserId($currentUser->id);
349
 
350
                $oldPassword = false;
351
                foreach($userPasswords as $userPassword)
352
                {
353
                    if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password))
354
                    {
355
                        $oldPassword = true;
356
                        break;
357
                    }
358
                }
359
 
360
                if($oldPassword) {
361
                    $this->logger->err('Cambio de contraseña del usuario - error contraseña ya utilizada anteriormente', ['user_id' =>  $currentUser->id, 'ip' => Functions::getUserIP()]);
362
 
363
                    return new JsonModel([
364
                        'success'   => false,
365
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
366
 
367
                    ]);
368
                } else {
369
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
370
 
371
                    $userMapper = UserMapper::getInstance($this->adapter);
372
                    $result = $userMapper->updatePassword($currentUser, $password_hash);
373
                    if($result) {
374
 
375
                        $userPassword = new UserPassword();
376
                        $userPassword->user_id = $currentUser->id;
377
                        $userPassword->password = $password_hash;
378
                        $userPasswordMapper->insert($userPassword);
379
 
380
                        $this->logger->info('Cambio de contraseña del usuario realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
381
 
382
 
383
                        return new JsonModel([
384
                            'success'   => true,
385
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
386
 
387
                        ]);
388
                    } else {
389
                        $this->logger->err('Cambio de contraseña del usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
390
 
391
                        return new JsonModel([
392
                            'success'   => true,
393
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
394
 
395
                        ]);
396
                    }
397
                }
398
 
399
            } else {
400
                $messages = [];
401
 
402
                $form_messages = (array) $form->getMessages();
403
                foreach($form_messages  as $fieldname => $field_messages)
404
                {
405
                    $messages[$fieldname] = array_values($field_messages);
406
                }
407
 
408
                return new JsonModel([
409
                    'success'   => false,
410
                    'data'   => $messages
411
                ]);
412
            }
413
 
414
        }
415
 
416
 
417
 
418
        return new JsonModel([
419
            'success' => false,
420
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
421
        ]);
422
    }
423
 
424
    public function imageAction()
425
    {
426
        $currentUserPlugin = $this->plugin('currentUserPlugin');
427
        $currentUser = $currentUserPlugin->getUser();
428
        $operation = $this->params()->fromRoute('operation');
429
 
430
 
431
 
432
 
433
        $request = $this->getRequest();
434
        if($request->isGet()) {
435
 
436
            $currentUserPlugin = $this->plugin('currentUserPlugin');
437
            $currentUser = $currentUserPlugin->getUser();
438
 
439
            $userMapper = UserMapper::getInstance($this->adapter);
440
 
441
            $target_path = $this->config['leaderslinked.fullpath.user'] . DIRECTORY_SEPARATOR . $currentUser->uuid;
442
 
443
            return new JsonModel([
444
                'success' => true,
445
                'data' => $this->url()->fromRoute('storage', ['code' => $currentUser->uuid, 'type' => 'user', 'filename' => $currentUser->image])
446
            ]);
447
 
448
 
449
        } else  if($request->isPost()) {
450
            $target_path = $this->config['leaderslinked.fullpath.user'] . DIRECTORY_SEPARATOR . $currentUser->uuid;
451
 
452
            $userMapper = UserMapper::getInstance($this->adapter);
453
 
454
            if($operation == 'delete') {
455
                $this->logger->info('Se borro el image  del usuario ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
456
 
457
                if($currentUser->image) {
458
                    if(!image ::delete($target_path, $currentUser->image)) {
459
                        return new JsonModel([
460
                            'success'   => false,
461
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
462
                        ]);
463
                    }
464
                }
465
 
466
                $currentUser->image = '';
467
                if(!$userMapper->update($currentUser)) {
468
                    return new JsonModel([
469
                        'success'   => false,
470
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
471
                    ]);
472
                }
473
 
474
 
475
 
476
            } else {
477
                $form = new ChangeImageForm($this->config);
478
                $data 	= array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
479
 
480
                $form->setData($data);
481
 
482
                if($form->isValid()) {
483
 
484
                    $files = $request->getFiles()->toArray();
485
                    if(!empty($files['image']['error'])) {
486
 
487
                        return new JsonModel([
488
                            'success'   => false,
489
                            'data'   =>  'ERROR_UPLOAD_FILE'
490
                        ]);
491
 
492
 
493
                    }
494
 
495
                    if($currentUser->image) {
496
                        if(!Image::delete($target_path, $currentUser->image)) {
497
                            return new JsonModel([
498
                                'success'   => false,
499
                                'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
500
                            ]);
501
                        }
502
                    }
503
 
504
                    $target_filename    = 'user-' . uniqid() . '.png';
505
                    list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
506
                    $source             = $files['image']['tmp_name'];
507
                    $crop_to_dimensions = true;
508
                    if(!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
509
                        return new JsonModel([
510
                            'success'   => false,
511
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
512
                        ]);
513
                    }
514
 
515
 
516
                    $currentUser->image = $target_filename;
517
                    if(!$userMapper->updateImage($currentUser)) {
518
 
519
                        return new JsonModel([
520
                            'success'   => false,
521
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
522
                        ]);
523
                    } else {
3163 efrain 524
 
525
 
526
 
1 www 527
                        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
528
                        $userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->id);
3163 efrain 529
 
530
                        if($userProfile) {
1 www 531
                            $userProfile->image = $currentUser->image;
532
                            $userProfileMapper->updateImage($userProfile);
533
                        }
3163 efrain 534
 
1 www 535
                    }
536
 
537
 
538
 
539
                    $this->logger->info('Se actualizo el image del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
540
 
541
                } else {
542
                    $messages = [];
543
                    $form_messages = (array) $form->getMessages();
544
                    foreach($form_messages  as $fieldname => $field_messages)
545
                    {
546
                        $messages[$fieldname] = array_values($field_messages);
547
                    }
548
 
549
                    return new JsonModel([
550
                        'success'   => false,
551
                        'data'   => $messages
552
                    ]);
553
                }
554
            }
555
            return new JsonModel([
556
                'success'   => true,
557
                'data' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $currentUser->uuid, 'filename' => $currentUser->image])
558
 
559
            ]);
560
        }
561
 
562
 
563
        $data = [
564
            'success' => false,
565
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
566
        ];
567
 
568
 
569
        return new JsonModel($data);
570
    }
571
 
572
    /**
573
     * Actualización de la ubucación
574
     * @return \Laminas\View\Model\JsonModel
575
     */
576
    public function locationAction()
577
    {
578
        $currentUserPlugin = $this->plugin('currentUserPlugin');
579
        $currentUser = $currentUserPlugin->getUser();
580
 
581
        $request = $this->getRequest();
582
        if($request->isGet()) {
583
            $hydrator = new ObjectPropertyHydrator();
584
 
585
            $currentUserPlugin = $this->plugin('currentUserPlugin');
586
            $currentUser = $currentUserPlugin->getUser();
587
 
588
            $locationMapper = LocationMapper::getInstance($this->adapter);
589
            $location = $locationMapper->fetchOne($currentUser->location_id);
590
 
591
 
592
            $data = [
593
                'formatted_address' => $location ? $location->formatted_address : '',
594
                'address1' => $location ? $location->address1 : '',
595
                'address2' => $location ? $location->address2 : '',
596
                'country' => $location ? $location->country : '',
597
                'state' => $location ? $location->state : '',
598
                'city1' => $location ? $location->city1 : '',
599
                'city2' => $location ? $location->city2 : '',
600
                'postal_code' => $location ? $location->postal_code : '',
601
                'latitude' => $location ? $location->latitude : '',
602
                'longitude' => $location ? $location->longitude : '',
603
            ];
604
 
605
            return new JsonModel([
606
                'success' => true,
607
                'data' => $data
608
            ]);
609
 
610
 
611
        } else  if($request->isPost()) {
612
 
613
            $form = new LocationForm();
614
            $dataPost = $request->getPost()->toArray();
615
 
616
            $form->setData($dataPost);
617
 
618
            if($form->isValid()) {
619
 
620
 
621
                $dataPost = (array) $form->getData();
622
 
623
                $location = new Location();
624
                $hydrator = new ObjectPropertyHydrator();
625
                $hydrator->hydrate($dataPost, $location);
626
 
627
                $location->id = $currentUser->location_id;
628
 
629
                $locationMapper = LocationMapper::getInstance($this->adapter);
630
                if($currentUser->location_id) {
631
                    $result = $locationMapper->update($location);
632
                } else {
633
                    $result = $locationMapper->insert($location);
634
 
635
                    if($result) {
636
                        $currentUser->location_id = $location->id;
637
 
638
 
639
                        $userMapper = UserMapper::getInstance($this->adapter);
640
                        $userMapper->updateLocation($currentUser);
641
                    }
642
                }
643
 
644
                if($result) {
645
                    $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
646
                    $userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->id);
647
                    if($userProfile) {
648
                        $userProfile->location_id = $location->id;
649
                        $userProfileMapper->updateLocation($userProfile);
650
                    }
651
                }
652
 
653
                if($result) {
654
                    $this->logger->info('Se actualizo la ubicación del usuario ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
655
 
656
                    $response = [
657
                        'success'   => true,
658
                        'data' => [
659
                            'formatted_address' => $location->formatted_address,
660
                            'message' =>  'LABEL_LOCATION_UPDATED' ,
661
 
662
                        ]
663
                    ];
664
                } else {
665
                    $response = [
666
                        'success'   => false,
667
                        'data' => 'ERROR_THERE_WAS_AN_ERROR'
668
                    ];
669
                }
670
 
671
 
672
 
673
                return new JsonModel($response);
674
 
675
            } else {
676
                return new JsonModel([
677
                    'success'   => false,
678
                    'data'   =>   'ERROR_PLACED_AUTOCOMPLETE_DOES_NOT_CONTAIN_GEOMETRY'
679
                ]);
680
            }
681
        }
682
 
683
 
684
        $data = [
685
            'success' => false,
686
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
687
        ];
688
 
689
 
690
        return new JsonModel($data);
691
    }
692
 
693
    public function privacyAction()
694
    {
695
        $request = $this->getRequest();
696
 
697
        if($request->isGet()) {
698
 
699
            $currentUserPlugin = $this->plugin('currentUserPlugin');
700
            $currentUser = $currentUserPlugin->getUser();
701
 
702
            $userMapper = UserMapper::getInstance($this->adapter);
703
            $user = $userMapper->fetchOne($currentUser->id);
704
 
705
            return new JsonModel([
706
                'success' => true,
707
                'data' => [
708
                    'show_in_search' => $user->show_in_search ? 1  : 0
709
                ]
710
            ]);
711
 
712
 
713
        } else if($request->isPost()) {
714
 
715
            $dataPost = $request->getPost()->toArray();
716
            $form = new PrivacySettingForm();
717
            $form->setData($dataPost);
718
 
719
            if($form->isValid()) {
720
                $currentUserPlugin = $this->plugin('currentUserPlugin');
721
                $currentUser = $currentUserPlugin->getUser();
722
 
723
                $dataPost = (array) $form->getData();
724
                $hydrator = new ObjectPropertyHydrator();
725
 
726
 
727
                $userMapper = UserMapper::getInstance($this->adapter);
728
                $hydrator->hydrate($dataPost, $currentUser);
729
 
730
                if($userMapper->updatePrivacy($currentUser)) {
731
                    $this->logger->info('Se guardo las preferencias de privacidad', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
732
                    $data = [
733
                        'success'   => true,
734
                        'data'      => 'LABEL_PRIVACY_UPDATE'
735
                    ];
736
                } else {
737
                    $data = [
738
                        'success'   => false,
739
                        'data'   => 'ERROR_UNKNOWN'
740
                    ];
741
                }
742
 
743
                return new JsonModel($data);
744
 
745
            } else {
746
                $messages = [];
747
 
748
 
749
 
750
                $form_messages = (array) $form->getMessages();
751
                foreach($form_messages  as $fieldname => $field_messages)
752
                {
753
 
754
                    $messages[$fieldname] = array_values($field_messages);
755
                }
756
 
757
                return new JsonModel([
758
                    'success'   => false,
759
                    'data'   => $messages
760
                ]);
761
            }
762
        }  else {
763
            $data = [
764
                'success' => false,
765
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
766
            ];
767
 
768
            return new JsonModel($data);
769
        }
770
 
771
        return new JsonModel($data);
772
 
773
    }
774
 
775
    public function basicAction()
776
    {
777
        $request = $this->getRequest();
778
 
779
        if($request->isGet()) {
780
            $currentUserPlugin = $this->plugin('currentUserPlugin');
781
            $currentUser = $currentUserPlugin->getUser();
782
 
783
            $userMapper = UserMapper::getInstance($this->adapter);
784
            $user = $userMapper->fetchOne($currentUser->id);
785
 
786
            return new JsonModel([
787
                'success' => true,
788
                'data' => [
789
                    'first_name' => $user->first_name,
790
                    'last_name' => $user->last_name,
791
                    'gender' => $user->gender ? $user->gender : '',
792
                    'phone' => $user->phone ? $user->phone : '',
793
                    'email' => $user->email,
794
                ]
795
            ]);
796
 
797
 
798
        } else if($request->isPost()) {
799
 
800
            $dataPost = $request->getPost()->toArray();
801
            $form = new  BasicForm();
802
            $form->setData($dataPost);
803
 
804
            if($form->isValid()) {
805
                $currentUserPlugin = $this->plugin('currentUserPlugin');
806
                $currentUser = $currentUserPlugin->getUser();
807
 
808
                $dataPost = (array) $form->getData();
809
                $hydrator = new ObjectPropertyHydrator();
810
 
811
 
812
                $userMapper = UserMapper::getInstance($this->adapter);
813
                $hydrator->hydrate($dataPost, $currentUser);
814
 
815
                if($userMapper->updateBasic($currentUser)) {
816
                    $this->logger->info('Se guardaron los datos básicos ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
817
                    $data = [
818
                        'success'   => true,
819
                        'data'      => 'LABEL_BASIC_UPDATE'
820
                    ];
821
                } else {
822
                    $data = [
823
                        'success'   => false,
824
                        'data'   => 'ERROR_UNKNOWN'
825
                    ];
826
                }
827
 
828
                return new JsonModel($data);
829
 
830
            } else {
831
                $messages = [];
832
 
833
 
834
 
835
                $form_messages = (array) $form->getMessages();
836
                foreach($form_messages  as $fieldname => $field_messages)
837
                {
838
 
839
                    $messages[$fieldname] = array_values($field_messages);
840
                }
841
 
842
                return new JsonModel([
843
                    'success'   => false,
844
                    'data'   => $messages
845
                ]);
846
            }
847
        }  else {
848
            $data = [
849
                'success' => false,
850
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
851
            ];
852
 
853
            return new JsonModel($data);
854
        }
855
 
856
        return new JsonModel($data);
857
 
858
    }
859
 
860
    public function browsersAction()
861
    {
862
        $request = $this->getRequest();
863
        if($request->isGet()) {
864
 
865
            $currentUserPlugin = $this->plugin('currentUserPlugin');
866
            $currentUser = $currentUserPlugin->getUser();
867
 
868
            $search = '';
869
            $page               = intval($this->params()->fromQuery('start', 1), 10);
870
            $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
871
            $order_field        = 'updated_on';
872
            $order_direction = 'DESC';
873
 
874
 
875
 
876
            $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
877
            $paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
878
 
879
            $items = [];
880
            $records = $paginator->getCurrentItems();
881
            foreach($records as $record)
882
            {
883
                $item = [
884
                    'id' => $record->id,
885
                    'platform' => $record->platform,
886
                    'browser' => $record->browser,
887
                    'device_type' => $record->device_type,
888
                    'version' => $record->version,
889
                    'updated_on' => $record->updated_on,
890
                ];
891
 
892
                array_push($items, $item);
893
            }
894
 
895
            return new JsonModel([
896
                'success' => true,
897
                'data' => [
898
                    'items' => $items,
899
                    'total' => $paginator->getTotalItemCount(),
900
                ]
901
            ]);
902
 
903
        } else {
904
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
905
        }
906
    }
907
    public function devicesAction()
908
    {
909
        $request = $this->getRequest();
910
        if($request->isGet()) {
911
 
912
            $currentUserPlugin = $this->plugin('currentUserPlugin');
913
            $currentUser = $currentUserPlugin->getUser();
914
 
915
            $page               = intval($this->params()->fromPost('start', 1), 10);
916
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
917
 
918
 
919
            /*
920
             select d.platform, d.brand, d.manufacturer, d.model, d.version,
921
             dh.ip, dh.updated_on  from tbl_device_history as dh
922
             inner join tbl_devices as d on d.id  = dh.device_id
923
             where dh.user_id = 4 order by dh.updated_on  desc
924
             */
925
 
926
            $queryMapper = QueryMapper::getInstance($this->adapter);
927
            $select = $queryMapper->getSql()->select();
928
            $select->columns(['ip', 'updated_on']);
929
            $select->from(['dh' => DeviceHistoryMapper::_TABLE]);
930
            $select->join(['d' => DeviceMapper::_TABLE], 'd.id  = dh.device_id', ['id', 'platform','brand','manufacturer','model','version']);
931
            $select->where->equalTo('dh.user_id', $currentUser->id);
932
            $select->order('updated_on desc ');
933
 
934
 
935
 
936
            $hydrator   = new ArraySerializableHydrator();
937
            $resultset  = new HydratingResultSet($hydrator);
938
 
939
            $adapter = new DbSelect($select, $queryMapper->getSql(), $resultset);
940
            $paginator = new Paginator($adapter);
941
            $paginator->setItemCountPerPage($records_x_page);
942
            $paginator->setCurrentPageNumber($page);
943
 
944
            $items = [];
945
            $records = $paginator->getCurrentItems();
946
            foreach($records as $record)
947
            {
948
                $item = [
949
                    'id' => $record['id'],
950
                    'platform' => $record['platform'],
951
                    'brand' => $record['brand'],
952
                    'manufacturer' => $record['manufacturer'],
953
                    'version' => $record['version'],
954
                    'model' => $record['model'],
955
                    'version' => $record['version'],
956
                    'ip' => $record['ip'],
957
                    'updated_on' => $record['updated_on'],
958
                ];
959
 
960
                array_push($items, $item);
961
            }
962
 
963
            return new JsonModel([
964
                'success' => true,
965
                'data' => [
966
                    'items' => $items,
967
                    'total' => $paginator->getTotalItemCount(),
968
                ]
969
            ]);
970
 
971
        } else {
972
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
973
        }
974
    }
975
 
976
 
977
    public function ipsAction()
978
    {
979
        $request = $this->getRequest();
980
        if($request->isGet()) {
981
 
982
            $currentUserPlugin = $this->plugin('currentUserPlugin');
983
            $currentUser = $currentUserPlugin->getUser();
984
 
985
            $search = '';
986
            $page               = intval($this->params()->fromPost('start', 1), 10);
987
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
988
            $order_field        = 'updated_on';
989
            $order_direction = 'DESC';
990
 
991
 
992
 
993
            $userBrowserMapper = UserIpMapper::getInstance($this->adapter);
994
            $paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
995
 
996
            $items = [];
997
            $records = $paginator->getCurrentItems();
998
            foreach($records as $record)
999
            {
1000
                $item = [
1001
                    'id' => $record->id,
1002
                    'ip' => $record->ip,
1003
                    'country_name' => $record->country_name,
1004
                    'state_name' => $record->state_name,
1005
                    'city' => $record->city,
1006
                    'postal_code' => $record->postal_code,
1007
                    'updated_on' => $record->updated_on,
1008
                ];
1009
 
1010
                array_push($items, $item);
1011
            }
1012
 
1013
            return new JsonModel([
1014
                'success' => true,
1015
                'data' => [
1016
                    'items' => $items,
1017
                    'total' => $paginator->getTotalItemCount(),
1018
                ]
1019
            ]);
1020
 
1021
        } else {
1022
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1023
        }
1024
    }
1025
 
1026
    public function transactionsAction()
1027
    {
1028
        $request = $this->getRequest();
1029
        if($request->isGet()) {
1030
 
1031
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1032
            $currentUser = $currentUserPlugin->getUser();
1033
 
1034
            $search = '';
1035
            $page               = intval($this->params()->fromPost('start', 1), 10);
1036
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
1037
            $order_field        = 'updated_on';
1038
            $order_direction = 'DESC';
1039
 
1040
            $status = [
1041
                Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',
1042
                Transaction::STATUS_PENDING => 'LABEL_PENDING',
1043
                Transaction::STATUS_PROCESSING => 'LABEL_PROCESSING',
1044
                Transaction::STATUS_REJECTED => 'LABEL_REJECTED',
1045
                Transaction::STATUS_COMPLETED => 'LABEL_COMPLETED',
1046
                Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',
1047
            ];
1048
 
1049
            $types = [
1050
                Transaction::TYPE_COUPON => 'LABEL_COUPON',
1051
                Transaction::TYPE_PAYMENT => 'LABEL_PAYMENT',
1052
                Transaction::TYPE_REVERSE => 'LABEL_REVERSE',
1053
                Transaction::TYPE_TRANSFER => 'LABEL_TRANSFER',
1054
            ];
1055
 
1056
            $providers = [
1057
                Provider::PAYPAL => 'LABEL_PAYPAL',
1058
            ];
1059
 
1060
            $transactionMapper = TransactionMapper::getInstance($this->adapter);
1061
            $paginator = $transactionMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
1062
 
1063
            $items = [];
1064
            $records = $paginator->getCurrentItems();
1065
            foreach($records as $record)
1066
            {
1067
                $item = [
1068
                    'id' => $record->id,
1069
                    'description' => $record->description,
1070
                    'provider' => $providers[$record->provider],
1071
                    'type' => $types[$record->type],
1072
                    'status' => $status[$record->status],
1073
                    'previous' => $record->previous,
1074
                    'amount' => $record->amount,
1075
                    'current' => $record->current,
1076
                    'updated_on' => $record->updated_on,
1077
                ];
1078
 
1079
                array_push($items, $item);
1080
            }
1081
 
1082
            return new JsonModel([
1083
                'success' => true,
1084
                'data' => [
1085
                    'items' => $items,
1086
                    'total' => $paginator->getTotalItemCount(),
1087
                ]
1088
            ]);
1089
 
1090
        } else {
1091
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1092
        }
1093
    }
1094
 
1095
 
1096
 
1097
    public function addFundAction()
1098
    {
1099
 
1100
        $request = $this->request;
1101
        if($request->isPost()) {
1102
 
1103
            $form = new FundsAddForm();
1104
            $form->setData($request->getPost()->toArray());
1105
            if($form->isValid()) {
1106
 
1107
                $currentUserPlugin = $this->plugin('currentUserPlugin');
1108
                $currentUser = $currentUserPlugin->getUser();
1109
 
1110
 
1111
 
1112
 
1113
                $dataPost = (array) $form->getData();
1114
 
1115
                $description    = $dataPost['description'];
1116
                $amount         = $dataPost['amount'];
1117
 
1118
 
1119
 
1120
                $sandbox = $this->config['leaderslinked.runmode.sandbox_paypal'];
1121
                if($sandbox) {
1122
                    //$account_id     = $this->config['leaderslinked.paypal.sandbox_account_id'];
1123
                    $client_id      = $this->config['leaderslinked.paypal.sandobx_client_id'];
1124
                    $client_secret  = $this->config['leaderslinked.paypal.sandbox_client_secret'];
1125
 
1126
 
1127
                    $environment = new SandboxEnvironment($client_id, $client_secret);
1128
 
1129
                } else {
1130
                    // $account_id     = $this->config['leaderslinked.paypal.production_account_id'];
1131
                    $client_id      = $this->config['leaderslinked.paypal.production_client_id'];
1132
                    $client_secret  = $this->config['leaderslinked.paypal.production_client_secret'];
1133
 
1134
                    $environment = new ProductionEnvironment($client_id, $client_secret);
1135
                }
1136
 
1137
                $internal_id = uniqid(Provider::PAYPAL, true);
1138
                $client = new PayPalHttpClient($environment);
1139
                $request = new OrdersCreateRequest;
1140
 
1141
 
1142
                //$request->prefer('return=representation');
1143
                $request->body = [
1144
                    'intent' => 'CAPTURE',
1145
                    'purchase_units' => [[
1146
                        'reference_id' => $internal_id,
1147
                        'description' => $description,
1148
                        'amount' => [
1149
                            'value' => number_format($amount, 2),
1150
                            'currency_code' => 'USD'
1151
                        ]
1152
                    ]],
1153
                    'application_context' => [
1154
                        'brand_name' => 'Leaders Linked',
1155
                        'locale' => 'es-UY',
1156
                        'cancel_url' => $this->url()->fromRoute('paypal/cancel', [] , ['force_canonical' => true]),
1157
                        'return_url' => $this->url()->fromRoute('paypal/success', [] , ['force_canonical' => true]),
1158
                    ]
1159
                ];
1160
 
1161
                try {
1162
                    // Call API with your client and get a response for your call
1163
                    $response = $client->execute($request);
1164
 
1165
 
1166
                    $external_id = $response->result->id;
1167
                    $approve_url = '';
1168
                    if($response->result->status == 'CREATED') {
1169
 
1170
                        $response->result->id;
1171
                        foreach($response->result->links as $link)
1172
                        {
1173
                            if($link->rel == 'approve') {
1174
                                $approve_url = $link->href;
1175
                            }
1176
                            //print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
1177
                        }
1178
 
1179
 
1180
                    }
1181
 
1182
 
1183
                    //echo json_encode($resp, JSON_PRETTY_PRINT), "\n";
1184
 
1185
 
1186
 
1187
 
1188
 
1189
                    // To toggle printing the whole response body comment/uncomment below line
1190
                    // echo json_encode($resp->result, JSON_PRETTY_PRINT), "\n";
1191
                    if($external_id && $approve_url) {
1192
 
1193
                        $transaction = new Transaction();
1194
                        $transaction->internal_id = $internal_id;
1195
                        $transaction->external_id = $external_id;
1196
                        $transaction->provider = Provider::PAYPAL;
1197
                        $transaction->user_id = $currentUser->id;
1198
                        $transaction->previous = 0;
1199
                        $transaction->amount = $amount;
1200
                        $transaction->current = 0;
1201
                        $transaction->status = Transaction::STATUS_PENDING;
1202
                        $transaction->type = Transaction::TYPE_PAYMENT;
1203
                        $transaction->description = $description;
1204
                        $transaction->request = json_encode($response, JSON_PRETTY_PRINT);
1205
 
1206
                        $requestId = Provider::PAYPAL . '-' . $external_id;
1207
 
1208
                        $this->cache->setItem($requestId, serialize($transaction));
1209
 
1210
 
1211
 
1212
 
1213
                        return new JsonModel(['success' => true, 'data' => $approve_url]);
1214
                    } else {
1215
                        return new JsonModel(['success' => false, 'data' => 'ERROR_TRANSACTION_NOT_SAVED']);
1216
                    }
1217
 
1218
 
1219
 
1220
                } catch (HttpException $ex) {
1221
 
1222
 
1223
                    return new JsonModel(['success' => false, 'data' => $ex->getMessage()]);
1224
                }
1225
 
1226
            } else {
1227
 
1228
                $message = '';;
1229
                $form_messages = (array) $form->getMessages();
1230
                foreach($form_messages  as $fieldname => $field_messages)
1231
                {
1232
                    foreach( $field_messages as $key => $value)
1233
                    {
1234
                        $message = $value;
1235
                    }
1236
                }
1237
 
1238
                $response = [
1239
                    'success'   => false,
1240
                    'data'   => $message
1241
                ];
1242
 
1243
                return new JsonModel($response);
1244
 
1245
            }
1246
 
1247
        } else {
1248
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1249
        }
1250
    }
1251
 
1252
    public function removeFacebookAction()
1253
    {
1254
        $request = $this->getRequest();
1255
        if($request->isPost()) {
1256
 
1257
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1258
            $currentUser = $currentUserPlugin->getUser();
1259
 
1260
 
1261
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1262
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK);
1263
 
1264
            if($userProvider) {
1265
 
1266
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK)) {
1267
                    return new JsonModel([
1268
                        'success' => true,
1269
                        'data' => 'LABEL_USER_PROVIDER_FACEBOOK_REMOVED'
1270
                    ]);
1271
 
1272
                } else {
1273
                    return new JsonModel([
1274
                        'success' => false,
1275
                        'data' => $userProviderMapper->getError()
1276
                    ]);
1277
                }
1278
 
1279
 
1280
            } else {
1281
                return new JsonModel([
1282
                    'success' => false,
1283
                    'data' => 'ERROR_USER_PROVIDER_FACEBOOK_NOT_FOUND'
1284
                ]);
1285
            }
1286
 
1287
 
1288
        } else {
1289
            return new JsonModel([
1290
                'success' => false,
1291
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1292
            ]);
1293
        }
1294
    }
1295
 
1296
    public function addFacebookAction()
1297
    {
1298
        $request = $this->getRequest();
1299
        if($request->isGet()) {
1300
 
1301
            try {
1302
                $app_id = $this->config['leaderslinked.facebook.app_id'];
1303
                $app_password = $this->config['leaderslinked.facebook.app_password'];
1304
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
1305
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
1306
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
1307
 
1308
 
1309
 
1310
                $fb = new \Facebook\Facebook([
1311
                    'app_id' => $app_id,
1312
                    'app_secret' => $app_password,
1313
                    'default_graph_version' => $app_graph_version,
1314
                ]);
1315
 
1316
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
1317
                $helper = $fb->getRedirectLoginHelper();
1318
                $permissions = ['email', 'public_profile']; // Optional permissions
1319
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
1320
 
1321
                return new JsonModel([
1322
                    'success' => true,
1323
                    'data' => $facebookUrl
1324
                ]);
1325
            } catch (\Throwable $e) {
1326
                return new JsonModel([
1327
                    'success' => false,
1328
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
1329
                ]);
1330
            }
1331
 
1332
        } else {
1333
            return new JsonModel([
1334
                'success' => false,
1335
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1336
            ]);
1337
        }
1338
    }
1339
 
1340
    public function removeTwitterAction()
1341
    {
1342
        $request = $this->getRequest();
1343
        if($request->isPost()) {
1344
 
1345
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1346
            $currentUser = $currentUserPlugin->getUser();
1347
 
1348
 
1349
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1350
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER);
1351
 
1352
            if($userProvider) {
1353
 
1354
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER)) {
1355
                    return new JsonModel([
1356
                        'success' => true,
1357
                        'data' => 'LABEL_USER_PROVIDER_TWITTER_REMOVED'
1358
                    ]);
1359
 
1360
                } else {
1361
                    return new JsonModel([
1362
                        'success' => false,
1363
                        'data' => $userProviderMapper->getError()
1364
                    ]);
1365
                }
1366
 
1367
 
1368
            } else {
1369
                return new JsonModel([
1370
                    'success' => false,
1371
                    'data' => 'ERROR_USER_PROVIDER_TWITTER_NOT_FOUND'
1372
                ]);
1373
            }
1374
 
1375
 
1376
        } else {
1377
            return new JsonModel([
1378
                'success' => false,
1379
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1380
            ]);
1381
        }
1382
    }
1383
 
1384
    public function addTwitterAction()
1385
    {
1386
        $request = $this->getRequest();
1387
        if($request->isGet()) {
1388
 
1389
            try {
1390
                if($this->config['leaderslinked.runmode.sandbox']) {
1391
 
1392
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
1393
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
1394
 
1395
                } else {
1396
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
1397
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
1398
                }
1399
 
1400
                /*
1401
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
1402
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
1403
                 exit;
1404
                 */
1405
 
1406
                //Twitter
1407
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
1408
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
1409
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
1410
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url ]);
1411
                $twitterUrl = $twitter->url('oauth/authorize', [ 'oauth_token' => $request_token['oauth_token'] ]);
1412
 
1413
                $twitterSession = new \Laminas\Session\Container('twitter');
1414
                $twitterSession->oauth_token = $request_token['oauth_token'];
1415
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
1416
 
1417
                return new JsonModel([
1418
                    'success' => true,
1419
                    'data' =>  $twitterUrl
1420
                ]);
1421
            } catch (\Throwable $e) {
1422
                return new JsonModel([
1423
                    'success' => false,
1424
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
1425
                ]);
1426
            }
1427
 
1428
        } else {
1429
            return new JsonModel([
1430
                'success' => false,
1431
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1432
            ]);
1433
        }
1434
 
1435
 
1436
    }
1437
 
1438
    public function removeGoogleAction()
1439
    {
1440
        $request = $this->getRequest();
1441
        if($request->isPost()) {
1442
 
1443
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1444
            $currentUser = $currentUserPlugin->getUser();
1445
 
1446
 
1447
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1448
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE);
1449
 
1450
            if($userProvider) {
1451
 
1452
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE)) {
1453
                    return new JsonModel([
1454
                        'success' => true,
1455
                        'data' => 'LABEL_USER_PROVIDER_GOOGLE_REMOVED'
1456
                    ]);
1457
 
1458
                } else {
1459
                    return new JsonModel([
1460
                        'success' => false,
1461
                        'data' => $userProviderMapper->getError()
1462
                    ]);
1463
                }
1464
 
1465
 
1466
            } else {
1467
                return new JsonModel([
1468
                    'success' => false,
1469
                    'data' => 'ERROR_USER_PROVIDER_GOOGLE_NOT_FOUND'
1470
                ]);
1471
            }
1472
 
1473
 
1474
        } else {
1475
            return new JsonModel([
1476
                'success' => false,
1477
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1478
            ]);
1479
        }
1480
    }
1481
 
1482
    public function addGoogleAction()
1483
    {
1484
        $request = $this->getRequest();
1485
        if($request->isGet()) {
1486
 
1487
            try {
1488
 
1489
 
1490
                //Google
1491
                $google = new \Google_Client();
1492
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
1493
                $google->setAccessType("offline");        // offline access
1494
 
1495
                $google->setIncludeGrantedScopes(true);   // incremental auth
1496
 
1497
                $google->addScope('profile');
1498
                $google->addScope('email');
1499
 
1500
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
1501
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
1502
 
1503
                $google->setRedirectUri($redirect_url);
1504
                $googleUrl = $google->createAuthUrl();
1505
 
1506
                return new JsonModel([
1507
                    'success' => true,
1508
                    'data' =>  $googleUrl
1509
                ]);
1510
            } catch (\Throwable $e) {
1511
                return new JsonModel([
1512
                    'success' => false,
1513
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
1514
                ]);
1515
            }
1516
 
1517
        } else {
1518
            return new JsonModel([
1519
                'success' => false,
1520
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1521
            ]);
1522
        }
1523
    }
1979 efrain 1524
 
1525
    public function deleteAccountAction()
1526
    {
1527
 
1528
 
1529
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1530
        $user = $currentUserPlugin->getUser();
1531
 
1532
 
1533
 
1534
        $request = $this->getRequest();
1535
 
1536
        if($request->isGet()) {
1537
 
1538
            $this->sendEmailDeleteAccountKey($user);
1539
 
1540
 
1541
            return new JsonModel([
1542
                'success' => true,
1543
                'data' => [
1544
                    'message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_SENT_A_CONFIRMATION_CODE'
1545
                ]
1546
            ]);
1547
 
1548
        } else  if($request->isPost()) {
1549
 
1550
            $code = $this->params()->fromPost('code');
2013 efrain 1551
            if(empty($code) || $code != $user->delete_account_key) {
1979 efrain 1552
 
1553
                $this->sendEmailDeleteAccountKey($user);
1554
 
1555
                return new JsonModel([
1556
                    'success' => false,
1557
                    'data' => [
1558
                        'message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_IS_WRONG'
1559
                    ]
1560
                ]);
1561
            }
1562
 
1563
            $delete_account_generated_on = strtotime($user->delete_account_generated_on);
1564
            $expiry_time = $delete_account_generated_on + $this->config['leaderslinked.security.delete_account_expired'];
1565
 
1566
 
1567
            if (time() > $expiry_time) {
1568
 
1569
                $this->sendEmailDeleteAccountKey($user) ;
1570
 
1571
                return new JsonModel([
1572
                    'success' => false,
1573
                    'data' => [
1574
                        'message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_EXPIRED'
1575
                    ]
1576
                ]);
1577
 
1578
 
1579
            }
1580
 
1581
            $userDeleted  = new UserDeleted();
1582
            $userDeleted->user_id = $user->id;
1583
            $userDeleted->first_name = $user->first_name;
1584
            $userDeleted->last_name = $user->last_name;
1585
            $userDeleted->email = $user->email;
1586
            $userDeleted->image = $user->image;
1587
            $userDeleted->phone = $user->phone;
1588
            $userDeleted->pending = UserDeleted::PENDING_YES;
1589
 
1590
 
1591
            $userDeletedMapper = UserDeletedMapper::getInstance($this->adapter);
1592
            if ($userDeletedMapper->insert($userDeleted)) {
1593
 
2019 efrain 1594
                $this->sendEmailDeleteAccountCompleted($user);
1595
 
1979 efrain 1596
                $user->first_name = 'LABEL_DELETE_ACCOUNT_FIRST_NAME';
1597
                $user->last_name = 'LABEL_DELETE_ACCOUNT_LAST_NAME';
1984 efrain 1598
                $user->email = 'user-deleted-' . uniqid() . '@leaderslinked.com';
1979 efrain 1599
                $user->image = '';
1600
                $user->usertype_id = UserType::USER_DELETED;
1601
                $user->status = User::STATUS_DELETED;
1602
                $user->delete_account_key = '';
1603
                $user->delete_account_generated_on = '';
1604
 
1605
                $userMapper = UserMapper::getInstance($this->adapter);
1606
                if($userMapper->update($user)) {
1607
 
1608
 
2019 efrain 1609
 
1979 efrain 1610
                    return new JsonModel([
1611
                        'success' => true,
1612
                        'data' => [
1613
                            'message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_STARTED_DELETING_YOUR_DATA',
1614
                            'redirect_url' => $this->url()->fromRoute('signout'),
1615
                        ]
1616
                    ]);
1617
 
1618
 
1619
                } else {
1620
                    return new JsonModel([
1621
                        'success' => false,
1622
                        'data' => [
1623
                            'message' => $userDeletedMapper->getError()
1624
                        ]
1625
                    ]);
1626
                }
1627
 
1628
 
1629
 
1630
            } else {
1631
                return new JsonModel([
1632
                    'success' => false,
1633
                    'data' => [
1634
                        'message' => $userDeletedMapper->getError()
1635
                    ]
1636
                ]);
1637
            }
1638
 
1639
 
1640
 
1641
 
1642
 
1643
        }
1644
 
1645
 
1646
            return new JsonModel([
1647
                'success' => false,
1648
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1649
            ]);
1650
    }
1651
 
1652
    private function sendEmailDeleteAccountKey($user)
1653
    {
1654
        $delete_account_key = Functions::generatePassword(8);
1655
 
1656
        $userMapper = UserMapper::getInstance($this->adapter);
1657
        $userMapper->updateDeleteAccountKey($user->id, $delete_account_key);
1658
 
1659
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1660
        $emailTemplate = $emailTemplateMapper->fetchOne(EmailTemplate::ID_DELETE_ACCOUNT_CODE);
1661
        if($emailTemplate) {
1662
            $arrayCont = [
1663
                'firstname' => $user->first_name,
1664
                'lastname'  => $user->last_name,
1665
                'code'      => $delete_account_key,
1666
                'link'      => ''
1667
            ];
1668
 
1669
            $email = new QueueEmail($this->adapter);
1670
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1671
        }
1672
    }
1673
 
1674
 
1675
    private function sendEmailDeleteAccountCompleted($user)
1676
    {
1677
 
1678
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1679
        $emailTemplate = $emailTemplateMapper->fetchOne(EmailTemplate::ID_DELETE_ACCOUNT_COMPLETED);
1680
        if($emailTemplate) {
1681
            $arrayCont = [
1682
                'firstname' => $user->first_name,
1683
                'lastname'  => $user->last_name,
1684
                'code'      => '',
1685
                'link'      => ''
1686
            ];
1687
 
1688
            $email = new QueueEmail($this->adapter);
1689
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1690
        }
1691
    }
1 www 1692
 
1693
}