Proyectos de Subversion LeadersLinked - Services

Rev

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