Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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