Proyectos de Subversion LeadersLinked - Services

Rev

Rev 60 | Ir a la última revisión | | Ultima modificación | Ver Log |

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