Proyectos de Subversion LeadersLinked - Services

Rev

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