Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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