Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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