Proyectos de Subversion LeadersLinked - Services

Rev

Rev 203 | Ir a la última revisión | | Ultima modificación | Ver Log |

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