Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4402 | Rev 4415 | 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,
4402 efrain 219
                'defaultNetwork' => $currentNetwork->default,
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,
4401 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();
4409 efrain 812
            print_r($dataPost);
4398 efrain 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
            }
4409 efrain 819
            print_r($dataPost);
4398 efrain 820
 
821
 
1 www 822
            $form = new  BasicForm();
823
            $form->setData($dataPost);
824
 
825
            if($form->isValid()) {
826
                $currentUserPlugin = $this->plugin('currentUserPlugin');
827
                $currentUser = $currentUserPlugin->getUser();
828
 
829
                $dataPost = (array) $form->getData();
830
                $hydrator = new ObjectPropertyHydrator();
831
 
832
 
833
                $userMapper = UserMapper::getInstance($this->adapter);
4409 efrain 834
                $user = $userMapper->fetchOne($currentUser->id);
1 www 835
 
4409 efrain 836
                $hydrator->hydrate($dataPost, $user);
837
 
838
                print_r($user);
839
 
840
                if($userMapper->updateBasic($user)) {
1 www 841
                    $this->logger->info('Se guardaron los datos básicos ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
842
                    $data = [
843
                        'success'   => true,
844
                        'data'      => 'LABEL_BASIC_UPDATE'
845
                    ];
846
                } else {
847
                    $data = [
848
                        'success'   => false,
849
                        'data'   => 'ERROR_UNKNOWN'
850
                    ];
851
                }
852
 
853
                return new JsonModel($data);
854
 
855
            } else {
856
                $messages = [];
857
 
858
 
859
 
860
                $form_messages = (array) $form->getMessages();
861
                foreach($form_messages  as $fieldname => $field_messages)
862
                {
863
 
864
                    $messages[$fieldname] = array_values($field_messages);
865
                }
866
 
867
                return new JsonModel([
868
                    'success'   => false,
869
                    'data'   => $messages
870
                ]);
871
            }
872
        }  else {
873
            $data = [
874
                'success' => false,
875
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
876
            ];
877
 
878
            return new JsonModel($data);
879
        }
880
 
881
        return new JsonModel($data);
882
 
883
    }
884
 
885
    public function browsersAction()
886
    {
887
        $request = $this->getRequest();
888
        if($request->isGet()) {
889
 
890
            $currentUserPlugin = $this->plugin('currentUserPlugin');
891
            $currentUser = $currentUserPlugin->getUser();
892
 
893
            $search = '';
894
            $page               = intval($this->params()->fromQuery('start', 1), 10);
895
            $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
896
            $order_field        = 'updated_on';
897
            $order_direction = 'DESC';
898
 
899
 
900
 
901
            $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
902
            $paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
903
 
904
            $items = [];
905
            $records = $paginator->getCurrentItems();
906
            foreach($records as $record)
907
            {
908
                $item = [
909
                    'id' => $record->id,
910
                    'platform' => $record->platform,
911
                    'browser' => $record->browser,
912
                    'device_type' => $record->device_type,
913
                    'version' => $record->version,
914
                    'updated_on' => $record->updated_on,
915
                ];
916
 
917
                array_push($items, $item);
918
            }
919
 
920
            return new JsonModel([
921
                'success' => true,
922
                'data' => [
923
                    'items' => $items,
924
                    'total' => $paginator->getTotalItemCount(),
925
                ]
926
            ]);
927
 
928
        } else {
929
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
930
        }
931
    }
932
    public function devicesAction()
933
    {
934
        $request = $this->getRequest();
935
        if($request->isGet()) {
936
 
937
            $currentUserPlugin = $this->plugin('currentUserPlugin');
938
            $currentUser = $currentUserPlugin->getUser();
939
 
940
            $page               = intval($this->params()->fromPost('start', 1), 10);
941
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
942
 
943
 
944
            /*
945
             select d.platform, d.brand, d.manufacturer, d.model, d.version,
946
             dh.ip, dh.updated_on  from tbl_device_history as dh
947
             inner join tbl_devices as d on d.id  = dh.device_id
948
             where dh.user_id = 4 order by dh.updated_on  desc
949
             */
950
 
951
            $queryMapper = QueryMapper::getInstance($this->adapter);
952
            $select = $queryMapper->getSql()->select();
953
            $select->columns(['ip', 'updated_on']);
954
            $select->from(['dh' => DeviceHistoryMapper::_TABLE]);
955
            $select->join(['d' => DeviceMapper::_TABLE], 'd.id  = dh.device_id', ['id', 'platform','brand','manufacturer','model','version']);
956
            $select->where->equalTo('dh.user_id', $currentUser->id);
957
            $select->order('updated_on desc ');
958
 
959
 
960
 
961
            $hydrator   = new ArraySerializableHydrator();
962
            $resultset  = new HydratingResultSet($hydrator);
963
 
964
            $adapter = new DbSelect($select, $queryMapper->getSql(), $resultset);
965
            $paginator = new Paginator($adapter);
966
            $paginator->setItemCountPerPage($records_x_page);
967
            $paginator->setCurrentPageNumber($page);
968
 
969
            $items = [];
970
            $records = $paginator->getCurrentItems();
971
            foreach($records as $record)
972
            {
973
                $item = [
974
                    'id' => $record['id'],
975
                    'platform' => $record['platform'],
976
                    'brand' => $record['brand'],
977
                    'manufacturer' => $record['manufacturer'],
978
                    'version' => $record['version'],
979
                    'model' => $record['model'],
980
                    'version' => $record['version'],
981
                    'ip' => $record['ip'],
982
                    'updated_on' => $record['updated_on'],
983
                ];
984
 
985
                array_push($items, $item);
986
            }
987
 
988
            return new JsonModel([
989
                'success' => true,
990
                'data' => [
991
                    'items' => $items,
992
                    'total' => $paginator->getTotalItemCount(),
993
                ]
994
            ]);
995
 
996
        } else {
997
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
998
        }
999
    }
1000
 
1001
 
1002
    public function ipsAction()
1003
    {
1004
        $request = $this->getRequest();
1005
        if($request->isGet()) {
1006
 
1007
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1008
            $currentUser = $currentUserPlugin->getUser();
1009
 
1010
            $search = '';
1011
            $page               = intval($this->params()->fromPost('start', 1), 10);
1012
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
1013
            $order_field        = 'updated_on';
1014
            $order_direction = 'DESC';
1015
 
1016
 
1017
 
1018
            $userBrowserMapper = UserIpMapper::getInstance($this->adapter);
1019
            $paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
1020
 
1021
            $items = [];
1022
            $records = $paginator->getCurrentItems();
1023
            foreach($records as $record)
1024
            {
1025
                $item = [
1026
                    'id' => $record->id,
1027
                    'ip' => $record->ip,
1028
                    'country_name' => $record->country_name,
1029
                    'state_name' => $record->state_name,
1030
                    'city' => $record->city,
1031
                    'postal_code' => $record->postal_code,
1032
                    'updated_on' => $record->updated_on,
1033
                ];
1034
 
1035
                array_push($items, $item);
1036
            }
1037
 
1038
            return new JsonModel([
1039
                'success' => true,
1040
                'data' => [
1041
                    'items' => $items,
1042
                    'total' => $paginator->getTotalItemCount(),
1043
                ]
1044
            ]);
1045
 
1046
        } else {
1047
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1048
        }
1049
    }
1050
 
1051
    public function transactionsAction()
1052
    {
1053
        $request = $this->getRequest();
1054
        if($request->isGet()) {
1055
 
1056
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1057
            $currentUser = $currentUserPlugin->getUser();
1058
 
1059
            $search = '';
1060
            $page               = intval($this->params()->fromPost('start', 1), 10);
1061
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
1062
            $order_field        = 'updated_on';
1063
            $order_direction = 'DESC';
1064
 
1065
            $status = [
1066
                Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',
1067
                Transaction::STATUS_PENDING => 'LABEL_PENDING',
1068
                Transaction::STATUS_PROCESSING => 'LABEL_PROCESSING',
1069
                Transaction::STATUS_REJECTED => 'LABEL_REJECTED',
1070
                Transaction::STATUS_COMPLETED => 'LABEL_COMPLETED',
1071
                Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',
1072
            ];
1073
 
1074
            $types = [
1075
                Transaction::TYPE_COUPON => 'LABEL_COUPON',
1076
                Transaction::TYPE_PAYMENT => 'LABEL_PAYMENT',
1077
                Transaction::TYPE_REVERSE => 'LABEL_REVERSE',
1078
                Transaction::TYPE_TRANSFER => 'LABEL_TRANSFER',
1079
            ];
1080
 
1081
            $providers = [
1082
                Provider::PAYPAL => 'LABEL_PAYPAL',
1083
            ];
1084
 
1085
            $transactionMapper = TransactionMapper::getInstance($this->adapter);
1086
            $paginator = $transactionMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
1087
 
1088
            $items = [];
1089
            $records = $paginator->getCurrentItems();
1090
            foreach($records as $record)
1091
            {
1092
                $item = [
1093
                    'id' => $record->id,
1094
                    'description' => $record->description,
1095
                    'provider' => $providers[$record->provider],
1096
                    'type' => $types[$record->type],
1097
                    'status' => $status[$record->status],
1098
                    'previous' => $record->previous,
1099
                    'amount' => $record->amount,
1100
                    'current' => $record->current,
1101
                    'updated_on' => $record->updated_on,
1102
                ];
1103
 
1104
                array_push($items, $item);
1105
            }
1106
 
1107
            return new JsonModel([
1108
                'success' => true,
1109
                'data' => [
1110
                    'items' => $items,
1111
                    'total' => $paginator->getTotalItemCount(),
1112
                ]
1113
            ]);
1114
 
1115
        } else {
1116
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1117
        }
1118
    }
1119
 
1120
 
1121
 
1122
    public function addFundAction()
1123
    {
1124
 
1125
        $request = $this->request;
1126
        if($request->isPost()) {
1127
 
1128
            $form = new FundsAddForm();
1129
            $form->setData($request->getPost()->toArray());
1130
            if($form->isValid()) {
1131
 
1132
                $currentUserPlugin = $this->plugin('currentUserPlugin');
1133
                $currentUser = $currentUserPlugin->getUser();
1134
 
1135
 
1136
 
1137
 
1138
                $dataPost = (array) $form->getData();
1139
 
1140
                $description    = $dataPost['description'];
1141
                $amount         = $dataPost['amount'];
1142
 
1143
 
1144
 
1145
                $sandbox = $this->config['leaderslinked.runmode.sandbox_paypal'];
1146
                if($sandbox) {
1147
                    //$account_id     = $this->config['leaderslinked.paypal.sandbox_account_id'];
1148
                    $client_id      = $this->config['leaderslinked.paypal.sandobx_client_id'];
1149
                    $client_secret  = $this->config['leaderslinked.paypal.sandbox_client_secret'];
1150
 
1151
 
1152
                    $environment = new SandboxEnvironment($client_id, $client_secret);
1153
 
1154
                } else {
1155
                    // $account_id     = $this->config['leaderslinked.paypal.production_account_id'];
1156
                    $client_id      = $this->config['leaderslinked.paypal.production_client_id'];
1157
                    $client_secret  = $this->config['leaderslinked.paypal.production_client_secret'];
1158
 
1159
                    $environment = new ProductionEnvironment($client_id, $client_secret);
1160
                }
1161
 
1162
                $internal_id = uniqid(Provider::PAYPAL, true);
1163
                $client = new PayPalHttpClient($environment);
1164
                $request = new OrdersCreateRequest;
1165
 
1166
 
1167
                //$request->prefer('return=representation');
1168
                $request->body = [
1169
                    'intent' => 'CAPTURE',
1170
                    'purchase_units' => [[
1171
                        'reference_id' => $internal_id,
1172
                        'description' => $description,
1173
                        'amount' => [
1174
                            'value' => number_format($amount, 2),
1175
                            'currency_code' => 'USD'
1176
                        ]
1177
                    ]],
1178
                    'application_context' => [
1179
                        'brand_name' => 'Leaders Linked',
1180
                        'locale' => 'es-UY',
1181
                        'cancel_url' => $this->url()->fromRoute('paypal/cancel', [] , ['force_canonical' => true]),
1182
                        'return_url' => $this->url()->fromRoute('paypal/success', [] , ['force_canonical' => true]),
1183
                    ]
1184
                ];
1185
 
1186
                try {
1187
                    // Call API with your client and get a response for your call
1188
                    $response = $client->execute($request);
1189
 
1190
 
1191
                    $external_id = $response->result->id;
1192
                    $approve_url = '';
1193
                    if($response->result->status == 'CREATED') {
1194
 
1195
                        $response->result->id;
1196
                        foreach($response->result->links as $link)
1197
                        {
1198
                            if($link->rel == 'approve') {
1199
                                $approve_url = $link->href;
1200
                            }
1201
                            //print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
1202
                        }
1203
 
1204
 
1205
                    }
1206
 
1207
 
1208
                    //echo json_encode($resp, JSON_PRETTY_PRINT), "\n";
1209
 
1210
 
1211
 
1212
 
1213
 
1214
                    // To toggle printing the whole response body comment/uncomment below line
1215
                    // echo json_encode($resp->result, JSON_PRETTY_PRINT), "\n";
1216
                    if($external_id && $approve_url) {
1217
 
1218
                        $transaction = new Transaction();
1219
                        $transaction->internal_id = $internal_id;
1220
                        $transaction->external_id = $external_id;
1221
                        $transaction->provider = Provider::PAYPAL;
1222
                        $transaction->user_id = $currentUser->id;
1223
                        $transaction->previous = 0;
1224
                        $transaction->amount = $amount;
1225
                        $transaction->current = 0;
1226
                        $transaction->status = Transaction::STATUS_PENDING;
1227
                        $transaction->type = Transaction::TYPE_PAYMENT;
1228
                        $transaction->description = $description;
1229
                        $transaction->request = json_encode($response, JSON_PRETTY_PRINT);
1230
 
1231
                        $requestId = Provider::PAYPAL . '-' . $external_id;
1232
 
1233
                        $this->cache->setItem($requestId, serialize($transaction));
1234
 
1235
 
1236
 
1237
 
1238
                        return new JsonModel(['success' => true, 'data' => $approve_url]);
1239
                    } else {
1240
                        return new JsonModel(['success' => false, 'data' => 'ERROR_TRANSACTION_NOT_SAVED']);
1241
                    }
1242
 
1243
 
1244
 
1245
                } catch (HttpException $ex) {
1246
 
1247
 
1248
                    return new JsonModel(['success' => false, 'data' => $ex->getMessage()]);
1249
                }
1250
 
1251
            } else {
1252
 
1253
                $message = '';;
1254
                $form_messages = (array) $form->getMessages();
1255
                foreach($form_messages  as $fieldname => $field_messages)
1256
                {
1257
                    foreach( $field_messages as $key => $value)
1258
                    {
1259
                        $message = $value;
1260
                    }
1261
                }
1262
 
1263
                $response = [
1264
                    'success'   => false,
1265
                    'data'   => $message
1266
                ];
1267
 
1268
                return new JsonModel($response);
1269
 
1270
            }
1271
 
1272
        } else {
1273
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1274
        }
1275
    }
1276
 
1277
    public function removeFacebookAction()
1278
    {
1279
        $request = $this->getRequest();
1280
        if($request->isPost()) {
1281
 
1282
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1283
            $currentUser = $currentUserPlugin->getUser();
1284
 
1285
 
1286
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1287
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK);
1288
 
1289
            if($userProvider) {
1290
 
1291
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK)) {
1292
                    return new JsonModel([
1293
                        'success' => true,
1294
                        'data' => 'LABEL_USER_PROVIDER_FACEBOOK_REMOVED'
1295
                    ]);
1296
 
1297
                } else {
1298
                    return new JsonModel([
1299
                        'success' => false,
1300
                        'data' => $userProviderMapper->getError()
1301
                    ]);
1302
                }
1303
 
1304
 
1305
            } else {
1306
                return new JsonModel([
1307
                    'success' => false,
1308
                    'data' => 'ERROR_USER_PROVIDER_FACEBOOK_NOT_FOUND'
1309
                ]);
1310
            }
1311
 
1312
 
1313
        } else {
1314
            return new JsonModel([
1315
                'success' => false,
1316
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1317
            ]);
1318
        }
1319
    }
1320
 
1321
    public function addFacebookAction()
1322
    {
1323
        $request = $this->getRequest();
1324
        if($request->isGet()) {
1325
 
1326
            try {
1327
                $app_id = $this->config['leaderslinked.facebook.app_id'];
1328
                $app_password = $this->config['leaderslinked.facebook.app_password'];
1329
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
1330
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
1331
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
1332
 
1333
 
1334
 
1335
                $fb = new \Facebook\Facebook([
1336
                    'app_id' => $app_id,
1337
                    'app_secret' => $app_password,
1338
                    'default_graph_version' => $app_graph_version,
1339
                ]);
1340
 
1341
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
1342
                $helper = $fb->getRedirectLoginHelper();
1343
                $permissions = ['email', 'public_profile']; // Optional permissions
1344
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
1345
 
1346
                return new JsonModel([
1347
                    'success' => true,
1348
                    'data' => $facebookUrl
1349
                ]);
1350
            } catch (\Throwable $e) {
1351
                return new JsonModel([
1352
                    'success' => false,
1353
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
1354
                ]);
1355
            }
1356
 
1357
        } else {
1358
            return new JsonModel([
1359
                'success' => false,
1360
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1361
            ]);
1362
        }
1363
    }
1364
 
1365
    public function removeTwitterAction()
1366
    {
1367
        $request = $this->getRequest();
1368
        if($request->isPost()) {
1369
 
1370
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1371
            $currentUser = $currentUserPlugin->getUser();
1372
 
1373
 
1374
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1375
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER);
1376
 
1377
            if($userProvider) {
1378
 
1379
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER)) {
1380
                    return new JsonModel([
1381
                        'success' => true,
1382
                        'data' => 'LABEL_USER_PROVIDER_TWITTER_REMOVED'
1383
                    ]);
1384
 
1385
                } else {
1386
                    return new JsonModel([
1387
                        'success' => false,
1388
                        'data' => $userProviderMapper->getError()
1389
                    ]);
1390
                }
1391
 
1392
 
1393
            } else {
1394
                return new JsonModel([
1395
                    'success' => false,
1396
                    'data' => 'ERROR_USER_PROVIDER_TWITTER_NOT_FOUND'
1397
                ]);
1398
            }
1399
 
1400
 
1401
        } else {
1402
            return new JsonModel([
1403
                'success' => false,
1404
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1405
            ]);
1406
        }
1407
    }
1408
 
1409
    public function addTwitterAction()
1410
    {
1411
        $request = $this->getRequest();
1412
        if($request->isGet()) {
1413
 
1414
            try {
1415
                if($this->config['leaderslinked.runmode.sandbox']) {
1416
 
1417
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
1418
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
1419
 
1420
                } else {
1421
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
1422
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
1423
                }
1424
 
1425
                /*
1426
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
1427
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
1428
                 exit;
1429
                 */
1430
 
1431
                //Twitter
1432
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
1433
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
1434
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
1435
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url ]);
1436
                $twitterUrl = $twitter->url('oauth/authorize', [ 'oauth_token' => $request_token['oauth_token'] ]);
1437
 
1438
                $twitterSession = new \Laminas\Session\Container('twitter');
1439
                $twitterSession->oauth_token = $request_token['oauth_token'];
1440
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
1441
 
1442
                return new JsonModel([
1443
                    'success' => true,
1444
                    'data' =>  $twitterUrl
1445
                ]);
1446
            } catch (\Throwable $e) {
1447
                return new JsonModel([
1448
                    'success' => false,
1449
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
1450
                ]);
1451
            }
1452
 
1453
        } else {
1454
            return new JsonModel([
1455
                'success' => false,
1456
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1457
            ]);
1458
        }
1459
 
1460
 
1461
    }
1462
 
1463
    public function removeGoogleAction()
1464
    {
1465
        $request = $this->getRequest();
1466
        if($request->isPost()) {
1467
 
1468
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1469
            $currentUser = $currentUserPlugin->getUser();
1470
 
1471
 
1472
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1473
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE);
1474
 
1475
            if($userProvider) {
1476
 
1477
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE)) {
1478
                    return new JsonModel([
1479
                        'success' => true,
1480
                        'data' => 'LABEL_USER_PROVIDER_GOOGLE_REMOVED'
1481
                    ]);
1482
 
1483
                } else {
1484
                    return new JsonModel([
1485
                        'success' => false,
1486
                        'data' => $userProviderMapper->getError()
1487
                    ]);
1488
                }
1489
 
1490
 
1491
            } else {
1492
                return new JsonModel([
1493
                    'success' => false,
1494
                    'data' => 'ERROR_USER_PROVIDER_GOOGLE_NOT_FOUND'
1495
                ]);
1496
            }
1497
 
1498
 
1499
        } else {
1500
            return new JsonModel([
1501
                'success' => false,
1502
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1503
            ]);
1504
        }
1505
    }
1506
 
1507
    public function addGoogleAction()
1508
    {
1509
        $request = $this->getRequest();
1510
        if($request->isGet()) {
1511
 
1512
            try {
1513
 
1514
 
1515
                //Google
1516
                $google = new \Google_Client();
1517
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
1518
                $google->setAccessType("offline");        // offline access
1519
 
1520
                $google->setIncludeGrantedScopes(true);   // incremental auth
1521
 
1522
                $google->addScope('profile');
1523
                $google->addScope('email');
1524
 
1525
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
1526
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
1527
 
1528
                $google->setRedirectUri($redirect_url);
1529
                $googleUrl = $google->createAuthUrl();
1530
 
1531
                return new JsonModel([
1532
                    'success' => true,
1533
                    'data' =>  $googleUrl
1534
                ]);
1535
            } catch (\Throwable $e) {
1536
                return new JsonModel([
1537
                    'success' => false,
1538
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
1539
                ]);
1540
            }
1541
 
1542
        } else {
1543
            return new JsonModel([
1544
                'success' => false,
1545
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1546
            ]);
1547
        }
1548
    }
1979 efrain 1549
 
1550
    public function deleteAccountAction()
1551
    {
1552
 
1553
 
1554
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1555
        $user = $currentUserPlugin->getUser();
1556
 
1557
 
1558
 
1559
        $request = $this->getRequest();
1560
 
1561
        if($request->isGet()) {
1562
 
1563
            $this->sendEmailDeleteAccountKey($user);
1564
 
1565
 
1566
            return new JsonModel([
1567
                'success' => true,
1568
                'data' => [
1569
                    'message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_SENT_A_CONFIRMATION_CODE'
1570
                ]
1571
            ]);
1572
 
1573
        } else  if($request->isPost()) {
1574
 
1575
            $code = $this->params()->fromPost('code');
2013 efrain 1576
            if(empty($code) || $code != $user->delete_account_key) {
1979 efrain 1577
 
1578
                $this->sendEmailDeleteAccountKey($user);
1579
 
1580
                return new JsonModel([
1581
                    'success' => false,
1582
                    'data' => [
1583
                        'message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_IS_WRONG'
1584
                    ]
1585
                ]);
1586
            }
1587
 
1588
            $delete_account_generated_on = strtotime($user->delete_account_generated_on);
1589
            $expiry_time = $delete_account_generated_on + $this->config['leaderslinked.security.delete_account_expired'];
1590
 
1591
 
1592
            if (time() > $expiry_time) {
1593
 
1594
                $this->sendEmailDeleteAccountKey($user) ;
1595
 
1596
                return new JsonModel([
1597
                    'success' => false,
1598
                    'data' => [
1599
                        'message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_EXPIRED'
1600
                    ]
1601
                ]);
1602
 
1603
 
1604
            }
1605
 
1606
            $userDeleted  = new UserDeleted();
1607
            $userDeleted->user_id = $user->id;
1608
            $userDeleted->first_name = $user->first_name;
1609
            $userDeleted->last_name = $user->last_name;
1610
            $userDeleted->email = $user->email;
1611
            $userDeleted->image = $user->image;
1612
            $userDeleted->phone = $user->phone;
1613
            $userDeleted->pending = UserDeleted::PENDING_YES;
1614
 
1615
 
1616
            $userDeletedMapper = UserDeletedMapper::getInstance($this->adapter);
1617
            if ($userDeletedMapper->insert($userDeleted)) {
1618
 
2019 efrain 1619
                $this->sendEmailDeleteAccountCompleted($user);
1620
 
1979 efrain 1621
                $user->first_name = 'LABEL_DELETE_ACCOUNT_FIRST_NAME';
1622
                $user->last_name = 'LABEL_DELETE_ACCOUNT_LAST_NAME';
1984 efrain 1623
                $user->email = 'user-deleted-' . uniqid() . '@leaderslinked.com';
1979 efrain 1624
                $user->image = '';
1625
                $user->usertype_id = UserType::USER_DELETED;
1626
                $user->status = User::STATUS_DELETED;
1627
                $user->delete_account_key = '';
1628
                $user->delete_account_generated_on = '';
1629
 
1630
                $userMapper = UserMapper::getInstance($this->adapter);
1631
                if($userMapper->update($user)) {
1632
 
1633
 
2019 efrain 1634
 
1979 efrain 1635
                    return new JsonModel([
1636
                        'success' => true,
1637
                        'data' => [
1638
                            'message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_STARTED_DELETING_YOUR_DATA',
1639
                            'redirect_url' => $this->url()->fromRoute('signout'),
1640
                        ]
1641
                    ]);
1642
 
1643
 
1644
                } else {
1645
                    return new JsonModel([
1646
                        'success' => false,
1647
                        'data' => [
1648
                            'message' => $userDeletedMapper->getError()
1649
                        ]
1650
                    ]);
1651
                }
1652
 
1653
 
1654
 
1655
            } else {
1656
                return new JsonModel([
1657
                    'success' => false,
1658
                    'data' => [
1659
                        'message' => $userDeletedMapper->getError()
1660
                    ]
1661
                ]);
1662
            }
1663
 
1664
 
1665
 
1666
 
1667
 
1668
        }
1669
 
1670
 
1671
            return new JsonModel([
1672
                'success' => false,
1673
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1674
            ]);
1675
    }
1676
 
4398 efrain 1677
 
4113 efrain 1678
 
1679
 
1979 efrain 1680
    private function sendEmailDeleteAccountKey($user)
1681
    {
1682
        $delete_account_key = Functions::generatePassword(8);
1683
 
1684
        $userMapper = UserMapper::getInstance($this->adapter);
1685
        $userMapper->updateDeleteAccountKey($user->id, $delete_account_key);
1686
 
1687
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3712 efrain 1688
        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_CODE, $user->network_id);
1979 efrain 1689
        if($emailTemplate) {
1690
            $arrayCont = [
1691
                'firstname' => $user->first_name,
1692
                'lastname'  => $user->last_name,
1693
                'code'      => $delete_account_key,
1694
                'link'      => ''
1695
            ];
1696
 
1697
            $email = new QueueEmail($this->adapter);
1698
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1699
        }
1700
    }
1701
 
1702
 
1703
    private function sendEmailDeleteAccountCompleted($user)
1704
    {
1705
 
1706
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3712 efrain 1707
        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_COMPLETED, $user->network_id);
1979 efrain 1708
        if($emailTemplate) {
1709
            $arrayCont = [
1710
                'firstname' => $user->first_name,
1711
                'lastname'  => $user->last_name,
1712
                'code'      => '',
1713
                'link'      => ''
1714
            ];
1715
 
1716
            $email = new QueueEmail($this->adapter);
1717
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1718
        }
1719
    }
1 www 1720
 
1721
}