Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 2013 | Rev 3163 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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