Proyectos de Subversion LeadersLinked - Services

Rev

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

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