Proyectos de Subversion LeadersLinked - Services

Rev

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

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
use Laminas\Mvc\Controller\AbstractActionController;
8
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
9
use Laminas\Log\LoggerInterface;
10
use Laminas\View\Model\ViewModel;
11
use Laminas\View\Model\JsonModel;
12
use LeadersLinked\Mapper\UserMapper;
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Mapper\UserPasswordMapper;
15
use LeadersLinked\Form\AccountSetting\NotificationSettingForm;
16
use LeadersLinked\Mapper\UserNotificationSettingMapper;
17
use LeadersLinked\Form\AccountSetting\ChangePasswordForm;
18
use LeadersLinked\Form\AccountSetting\ChangeImageForm;
19
use LeadersLinked\Library\Image;
20
use LeadersLinked\Form\AccountSetting\LocationForm;
21
use LeadersLinked\Model\Location;
22
use LeadersLinked\Mapper\LocationMapper;
23
use LeadersLinked\Form\AccountSetting\PrivacySettingForm;
24
use LeadersLinked\Mapper\UserProfileMapper;
25
use LeadersLinked\Form\AccountSetting\BasicForm;
26
use LeadersLinked\Form\Transaction\FundsAddForm;
27
use LeadersLinked\Mapper\UserBrowserMapper;
28
use LeadersLinked\Mapper\QueryMapper;
29
use LeadersLinked\Mapper\DeviceHistoryMapper;
30
use LeadersLinked\Mapper\DeviceMapper;
31
use Laminas\Hydrator\ArraySerializableHydrator;
32
use Laminas\Db\ResultSet\HydratingResultSet;
33
use Laminas\Paginator\Adapter\DbSelect;
34
use Laminas\Paginator\Paginator;
35
use LeadersLinked\Mapper\UserIpMapper;
36
use LeadersLinked\Model\Transaction;
37
use LeadersLinked\Model\Provider;
38
use LeadersLinked\Mapper\TransactionMapper;
39
use LeadersLinked\Mapper\UserProviderMapper;
40
use LeadersLinked\Model\UserProvider;
41
use LeadersLinked\Model\UserPassword;
42
use LeadersLinked\Model\UserDeleted;
43
use LeadersLinked\Mapper\UserDeletedMapper;
44
use LeadersLinked\Model\UserType;
45
use LeadersLinked\Model\User;
46
use LeadersLinked\Library\QueueEmail;
47
use LeadersLinked\Mapper\EmailTemplateMapper;
48
use LeadersLinked\Model\EmailTemplate;
49
use LeadersLinked\Cache\CacheInterface;
50
use PayPalHttp\HttpException;
51
use PayPalCheckoutSdk\Core\SandboxEnvironment;
52
use PayPalCheckoutSdk\Core\ProductionEnvironment;
53
use PayPalCheckoutSdk\Core\PayPalHttpClient;
54
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
55
use Laminas\Mvc\I18n\Translator;
283 www 56
use LeadersLinked\Library\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
    {
788 stevensc 434
        // Obtener el usuario actual
1 efrain 435
        $currentUserPlugin = $this->plugin('currentUserPlugin');
436
        $currentUser = $currentUserPlugin->getUser();
788 stevensc 437
 
438
        // Obtener el operation
1 efrain 439
        $operation = $this->params()->fromRoute('operation');
440
 
788 stevensc 441
        $request = $this->getRequest();
1 efrain 442
 
789 stevensc 443
        if(!$request->isPost() && !$request->isGet()) {
788 stevensc 444
            return new JsonModel([
445
                'success' => false,
446
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
447
            ]);
448
        }
449
 
450
        $userMapper = UserMapper::getInstance($this->adapter);
451
        $storage = Storage::getInstance($this->config, $this->adapter);
452
        $target_path = $storage->getPathUser();
1 efrain 453
 
454
        if($request->isGet()) {
283 www 455
            $image = $storage->getUserImage($currentUser);
1 efrain 456
 
457
            return new JsonModel([
458
                'success' => true,
283 www 459
                'data' => $image,
1 efrain 460
            ]);
788 stevensc 461
        }
462
 
463
        if($request->isPost()) {
1 efrain 464
            if($operation == 'delete') {
788 stevensc 465
                // Si el usuario no tiene image
466
                if(!$currentUser->image) {
467
                    return new JsonModel([
468
                        'success'   => false,
469
                        'data'   =>  'ERROR_RECORD_NOT_FOUND'
470
                    ]);
1 efrain 471
                }
788 stevensc 472
 
473
                // Si no se puede borrar el archivo
474
                if(!$storage->deleteFile($target_path ,$currentUser->uuid, $currentUser->image)) {
475
                    return new JsonModel([
476
                        'success'   => false,
477
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
478
                    ]);
479
                }
1 efrain 480
 
788 stevensc 481
                // Actualizar el usuario
1 efrain 482
                $currentUser->image = '';
483
                if(!$userMapper->update($currentUser)) {
484
                    return new JsonModel([
485
                        'success'   => false,
486
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
487
                    ]);
488
                }
788 stevensc 489
 
490
                $this->logger->info('Se borro el image  del usuario ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
491
            }
492
 
493
            if($operation == 'upload') {
1 efrain 494
                $form = new ChangeImageForm($this->config);
495
                $data 	= array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
496
 
497
                $form->setData($data);
498
 
788 stevensc 499
                if(!$form->isValid()) {
500
                    $messages = [];
501
                    $form_messages = (array) $form->getMessages();
283 www 502
 
788 stevensc 503
                    foreach($form_messages  as $fieldname => $field_messages)
504
                    {
505
                        $messages[$fieldname] = array_values($field_messages);
1 efrain 506
                    }
507
 
788 stevensc 508
                    return new JsonModel([
509
                        'success'   => false,
510
                        'data'   => $messages
511
                    ]);
512
                }
283 www 513
 
788 stevensc 514
                $storage->setFiles($request->getFiles()->toArray());
515
                if(!$storage->setCurrentFilename('image')) {
516
                    $this->logger->err('Error al subir la imagen del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
517
                    return new JsonModel([
518
                        'success'   => false,
519
                        'data'   =>  'ERROR_UPLOAD_FILE'
520
                    ]);
521
                }
522
 
523
                // Si el usuario tiene image se borra
524
                if($currentUser->image) {
525
                    // Si el usuario tiene image, se borra
526
                    if(!$storage->deleteFile($target_path, $currentUser->uuid, $currentUser->image)) {
527
                        $this->logger->err('Error al borrar la imagen del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 efrain 528
                        return new JsonModel([
529
                            'success'   => false,
530
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
531
                        ]);
532
                    }
788 stevensc 533
                }
534
 
535
                // Obtener el tamaño de la imagen
536
                list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
537
 
538
                // Obtener el archivo temporal
539
                $source_filename = $storage->getTmpFilename();
791 stevensc 540
                $filename = $storage->getFilename();
541
                $target_filename = $storage->composePathToFilename(Storage::TYPE_USER, $currentUser->uuid, $filename);
788 stevensc 542
 
543
                if(!$storage->uploadImageResize($source_filename, $target_filename, $target_width, $target_height)) {
544
                    $this->logger->err('Error al subir la imagen del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 efrain 545
                    return new JsonModel([
546
                        'success'   => false,
788 stevensc 547
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1 efrain 548
                    ]);
549
                }
788 stevensc 550
 
551
 
791 stevensc 552
                $currentUser->image = $filename;
788 stevensc 553
                if(!$userMapper->updateImage($currentUser)) {
554
                    return new JsonModel([
555
                        'success'   => false,
556
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
557
                    ]);
558
                }
559
 
560
                if(!$storage->uploadImageResize($source_filename, $target_filename, $target_width, $target_height)) {
561
                    $this->logger->err('Error al subir la imagen del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
562
                    return new JsonModel([
563
                        'success'   => false,
564
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
565
                    ]);
566
                }
567
 
568
                $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
569
                $userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->id);
791 stevensc 570
 
788 stevensc 571
                if($userProfile) {
791 stevensc 572
                    $userProfile->image = $filename;
788 stevensc 573
                    $userProfileMapper->updateImage($userProfile);
574
                }
575
 
576
                $this->logger->info('Se actualizo el image del usuario', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 efrain 577
            }
283 www 578
 
579
 
1 efrain 580
            return new JsonModel([
581
                'success'   => true,
788 stevensc 582
                'data' =>  $storage->getUserImage($currentUser)
1 efrain 583
            ]);
584
        }
585
    }
586
 
587
 
588
 
589
    /**
590
     * Actualización de la ubucación
591
     * @return \Laminas\View\Model\JsonModel
592
     */
593
    public function locationAction()
594
    {
595
        $currentUserPlugin = $this->plugin('currentUserPlugin');
596
        $currentUser = $currentUserPlugin->getUser();
597
 
598
        $request = $this->getRequest();
599
        if($request->isGet()) {
600
            $hydrator = new ObjectPropertyHydrator();
601
 
602
            $currentUserPlugin = $this->plugin('currentUserPlugin');
603
            $currentUser = $currentUserPlugin->getUser();
604
 
605
            $locationMapper = LocationMapper::getInstance($this->adapter);
606
            $location = $locationMapper->fetchOne($currentUser->location_id);
607
 
608
 
609
            $data = [
610
                'formatted_address' => $location ? $location->formatted_address : '',
611
                'address1' => $location ? $location->address1 : '',
612
                'address2' => $location ? $location->address2 : '',
613
                'country' => $location ? $location->country : '',
614
                'state' => $location ? $location->state : '',
615
                'city1' => $location ? $location->city1 : '',
616
                'city2' => $location ? $location->city2 : '',
617
                'postal_code' => $location ? $location->postal_code : '',
618
                'latitude' => $location ? $location->latitude : '',
619
                'longitude' => $location ? $location->longitude : '',
620
            ];
621
 
622
            return new JsonModel([
623
                'success' => true,
624
                'data' => $data
625
            ]);
626
 
627
 
628
        } else  if($request->isPost()) {
629
 
630
            $form = new LocationForm();
631
            $dataPost = $request->getPost()->toArray();
632
 
633
            $form->setData($dataPost);
634
 
635
            if($form->isValid()) {
636
 
637
 
638
                $dataPost = (array) $form->getData();
639
 
640
                $location = new Location();
641
                $hydrator = new ObjectPropertyHydrator();
642
                $hydrator->hydrate($dataPost, $location);
643
 
644
                $location->id = $currentUser->location_id;
645
 
646
                $locationMapper = LocationMapper::getInstance($this->adapter);
647
                if($currentUser->location_id) {
648
                    $result = $locationMapper->update($location);
649
                } else {
650
                    $result = $locationMapper->insert($location);
651
 
652
                    if($result) {
653
                        $currentUser->location_id = $location->id;
654
 
655
 
656
                        $userMapper = UserMapper::getInstance($this->adapter);
657
                        $userMapper->updateLocation($currentUser);
658
                    }
659
                }
660
 
661
                if($result) {
662
                    $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
663
                    $userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->id);
664
                    if($userProfile) {
665
                        $userProfile->location_id = $location->id;
666
                        $userProfileMapper->updateLocation($userProfile);
667
                    }
668
                }
669
 
670
                if($result) {
671
                    $this->logger->info('Se actualizo la ubicación del usuario ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
672
 
673
                    $response = [
674
                        'success'   => true,
675
                        'data' => [
676
                            'formatted_address' => $location->formatted_address,
677
                            'message' =>  'LABEL_LOCATION_UPDATED' ,
678
 
679
                        ]
680
                    ];
681
                } else {
682
                    $response = [
683
                        'success'   => false,
684
                        'data' => 'ERROR_THERE_WAS_AN_ERROR'
685
                    ];
686
                }
687
 
688
 
689
 
690
                return new JsonModel($response);
691
 
692
            } else {
693
                return new JsonModel([
694
                    'success'   => false,
695
                    'data'   =>   'ERROR_PLACED_AUTOCOMPLETE_DOES_NOT_CONTAIN_GEOMETRY'
696
                ]);
697
            }
698
        }
699
 
700
 
701
        $data = [
702
            'success' => false,
703
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
704
        ];
705
 
706
 
707
        return new JsonModel($data);
708
    }
709
 
710
    public function privacyAction()
711
    {
712
        $request = $this->getRequest();
713
 
714
        if($request->isGet()) {
715
 
716
            $currentUserPlugin = $this->plugin('currentUserPlugin');
717
            $currentUser = $currentUserPlugin->getUser();
718
 
719
            $userMapper = UserMapper::getInstance($this->adapter);
720
            $user = $userMapper->fetchOne($currentUser->id);
721
 
722
            return new JsonModel([
723
                'success' => true,
724
                'data' => [
725
                    'show_in_search' => $user->show_in_search ? 1  : 0
726
                ]
727
            ]);
728
 
729
 
730
        } else if($request->isPost()) {
731
 
732
            $dataPost = $request->getPost()->toArray();
733
            $form = new PrivacySettingForm();
734
            $form->setData($dataPost);
735
 
736
            if($form->isValid()) {
737
                $currentUserPlugin = $this->plugin('currentUserPlugin');
738
                $currentUser = $currentUserPlugin->getUser();
739
 
740
                $dataPost = (array) $form->getData();
741
                $hydrator = new ObjectPropertyHydrator();
742
 
743
 
744
                $userMapper = UserMapper::getInstance($this->adapter);
745
                $hydrator->hydrate($dataPost, $currentUser);
746
 
747
                if($userMapper->updatePrivacy($currentUser)) {
748
                    $this->logger->info('Se guardo las preferencias de privacidad', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
749
                    $data = [
750
                        'success'   => true,
751
                        'data'      => 'LABEL_PRIVACY_UPDATE'
752
                    ];
753
                } else {
754
                    $data = [
755
                        'success'   => false,
756
                        'data'   => 'ERROR_UNKNOWN'
757
                    ];
758
                }
759
 
760
                return new JsonModel($data);
761
 
762
            } else {
763
                $messages = [];
764
 
765
 
766
 
767
                $form_messages = (array) $form->getMessages();
768
                foreach($form_messages  as $fieldname => $field_messages)
769
                {
770
 
771
                    $messages[$fieldname] = array_values($field_messages);
772
                }
773
 
774
                return new JsonModel([
775
                    'success'   => false,
776
                    'data'   => $messages
777
                ]);
778
            }
779
        }  else {
780
            $data = [
781
                'success' => false,
782
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
783
            ];
784
 
785
            return new JsonModel($data);
786
        }
787
 
788
        return new JsonModel($data);
789
 
790
    }
791
 
792
    public function basicAction()
793
    {
794
        $request = $this->getRequest();
795
 
796
        if($request->isGet()) {
797
            $currentUserPlugin = $this->plugin('currentUserPlugin');
798
            $currentUser = $currentUserPlugin->getUser();
799
 
800
            $userMapper = UserMapper::getInstance($this->adapter);
801
            $user = $userMapper->fetchOne($currentUser->id);
802
 
803
            return new JsonModel([
804
                'success' => true,
805
                'data' => [
806
                    'first_name' => $user->first_name,
807
                    'last_name' => $user->last_name,
808
                    'gender' => $user->gender ? $user->gender : '',
809
                    'phone' => $user->phone ? $user->phone : '',
810
                    'email' => $user->email,
811
                    'is_adult' => $user->is_adult,
812
                    'timezone' => $user->timezone,
813
                ]
814
            ]);
815
 
816
 
817
        } else if($request->isPost()) {
818
 
819
            $dataPost = $request->getPost()->toArray();
820
 
821
 
822
            if(empty($dataPost['is_adult'])) {
823
                $dataPost['is_adult'] = User::IS_ADULT_NO;
824
            } else {
825
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
826
            }
827
 
828
 
829
 
830
            $form = new  BasicForm();
831
            $form->setData($dataPost);
832
 
833
            if($form->isValid()) {
834
                $currentUserPlugin = $this->plugin('currentUserPlugin');
835
                $currentUser = $currentUserPlugin->getUser();
836
 
837
                $dataPost = (array) $form->getData();
838
                $hydrator = new ObjectPropertyHydrator();
839
 
840
 
841
                $userMapper = UserMapper::getInstance($this->adapter);
842
                $user = $userMapper->fetchOne($currentUser->id);
843
 
844
                $hydrator->hydrate($dataPost, $user);
845
 
846
 
847
 
848
                if($userMapper->updateBasic($user)) {
849
                    $this->logger->info('Se guardaron los datos básicos ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
850
                    $data = [
851
                        'success'   => true,
852
                        'data'      => 'LABEL_BASIC_UPDATE'
853
                    ];
854
                } else {
855
                    $data = [
856
                        'success'   => false,
857
                        'data'   => 'ERROR_UNKNOWN'
858
                    ];
859
                }
860
 
861
                return new JsonModel($data);
862
 
863
            } else {
864
                $messages = [];
865
 
866
 
867
 
868
                $form_messages = (array) $form->getMessages();
869
                foreach($form_messages  as $fieldname => $field_messages)
870
                {
871
 
872
                    $messages[$fieldname] = array_values($field_messages);
873
                }
874
 
875
                return new JsonModel([
876
                    'success'   => false,
877
                    'data'   => $messages
878
                ]);
879
            }
880
        }  else {
881
            $data = [
882
                'success' => false,
883
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
884
            ];
885
 
886
            return new JsonModel($data);
887
        }
888
 
889
        return new JsonModel($data);
890
 
891
    }
892
 
893
    public function browsersAction()
894
    {
895
        $request = $this->getRequest();
896
        if($request->isGet()) {
897
 
898
            $currentUserPlugin = $this->plugin('currentUserPlugin');
899
            $currentUser = $currentUserPlugin->getUser();
900
 
901
            $search = '';
902
            $page               = intval($this->params()->fromQuery('start', 1), 10);
903
            $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
904
            $order_field        = 'updated_on';
905
            $order_direction = 'DESC';
906
 
907
 
908
 
909
            $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
910
            $paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
911
 
912
            $items = [];
913
            $records = $paginator->getCurrentItems();
914
            foreach($records as $record)
915
            {
916
                $item = [
917
                    'id' => $record->id,
918
                    'platform' => $record->platform,
919
                    'browser' => $record->browser,
920
                    'device_type' => $record->device_type,
921
                    'version' => $record->version,
922
                    'updated_on' => $record->updated_on,
923
                ];
924
 
925
                array_push($items, $item);
926
            }
927
 
928
            return new JsonModel([
929
                'success' => true,
930
                'data' => [
931
                    'items' => $items,
932
                    'total' => $paginator->getTotalItemCount(),
933
                ]
934
            ]);
935
 
936
        } else {
937
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
938
        }
939
    }
940
    public function devicesAction()
941
    {
942
        $request = $this->getRequest();
943
        if($request->isGet()) {
944
 
945
            $currentUserPlugin = $this->plugin('currentUserPlugin');
946
            $currentUser = $currentUserPlugin->getUser();
947
 
948
            $page               = intval($this->params()->fromPost('start', 1), 10);
949
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
950
 
951
 
952
            /*
953
             select d.platform, d.brand, d.manufacturer, d.model, d.version,
954
             dh.ip, dh.updated_on  from tbl_device_history as dh
955
             inner join tbl_devices as d on d.id  = dh.device_id
956
             where dh.user_id = 4 order by dh.updated_on  desc
957
             */
958
 
959
            $queryMapper = QueryMapper::getInstance($this->adapter);
960
            $select = $queryMapper->getSql()->select();
961
            $select->columns(['ip', 'updated_on']);
962
            $select->from(['dh' => DeviceHistoryMapper::_TABLE]);
963
            $select->join(['d' => DeviceMapper::_TABLE], 'd.id  = dh.device_id', ['id', 'platform','brand','manufacturer','model','version']);
964
            $select->where->equalTo('dh.user_id', $currentUser->id);
965
            $select->order('updated_on desc ');
966
 
967
 
968
 
969
            $hydrator   = new ArraySerializableHydrator();
970
            $resultset  = new HydratingResultSet($hydrator);
971
 
972
            $adapter = new DbSelect($select, $queryMapper->getSql(), $resultset);
973
            $paginator = new Paginator($adapter);
974
            $paginator->setItemCountPerPage($records_x_page);
975
            $paginator->setCurrentPageNumber($page);
976
 
977
            $items = [];
978
            $records = $paginator->getCurrentItems();
979
            foreach($records as $record)
980
            {
981
                $item = [
982
                    'id' => $record['id'],
983
                    'platform' => $record['platform'],
984
                    'brand' => $record['brand'],
985
                    'manufacturer' => $record['manufacturer'],
986
                    'version' => $record['version'],
987
                    'model' => $record['model'],
988
                    'version' => $record['version'],
989
                    'ip' => $record['ip'],
990
                    'updated_on' => $record['updated_on'],
991
                ];
992
 
993
                array_push($items, $item);
994
            }
995
 
996
            return new JsonModel([
997
                'success' => true,
998
                'data' => [
999
                    'items' => $items,
1000
                    'total' => $paginator->getTotalItemCount(),
1001
                ]
1002
            ]);
1003
 
1004
        } else {
1005
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1006
        }
1007
    }
1008
 
1009
 
1010
    public function ipsAction()
1011
    {
1012
        $request = $this->getRequest();
1013
        if($request->isGet()) {
1014
 
1015
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1016
            $currentUser = $currentUserPlugin->getUser();
1017
 
1018
            $search = '';
1019
            $page               = intval($this->params()->fromPost('start', 1), 10);
1020
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
1021
            $order_field        = 'updated_on';
1022
            $order_direction = 'DESC';
1023
 
1024
 
1025
 
1026
            $userBrowserMapper = UserIpMapper::getInstance($this->adapter);
1027
            $paginator = $userBrowserMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
1028
 
1029
            $items = [];
1030
            $records = $paginator->getCurrentItems();
1031
            foreach($records as $record)
1032
            {
1033
                $item = [
1034
                    'id' => $record->id,
1035
                    'ip' => $record->ip,
1036
                    'country_name' => $record->country_name,
1037
                    'state_name' => $record->state_name,
1038
                    'city' => $record->city,
1039
                    'postal_code' => $record->postal_code,
1040
                    'updated_on' => $record->updated_on,
1041
                ];
1042
 
1043
                array_push($items, $item);
1044
            }
1045
 
1046
            return new JsonModel([
1047
                'success' => true,
1048
                'data' => [
1049
                    'items' => $items,
1050
                    'total' => $paginator->getTotalItemCount(),
1051
                ]
1052
            ]);
1053
 
1054
        } else {
1055
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1056
        }
1057
    }
1058
 
1059
    public function transactionsAction()
1060
    {
1061
        $request = $this->getRequest();
1062
        if($request->isGet()) {
1063
 
1064
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1065
            $currentUser = $currentUserPlugin->getUser();
1066
 
1067
            $search = '';
1068
            $page               = intval($this->params()->fromPost('start', 1), 10);
1069
            $records_x_page     = intval($this->params()->fromPost('length', 10), 10);
1070
            $order_field        = 'updated_on';
1071
            $order_direction = 'DESC';
1072
 
1073
            $status = [
1074
                Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',
1075
                Transaction::STATUS_PENDING => 'LABEL_PENDING',
1076
                Transaction::STATUS_PROCESSING => 'LABEL_PROCESSING',
1077
                Transaction::STATUS_REJECTED => 'LABEL_REJECTED',
1078
                Transaction::STATUS_COMPLETED => 'LABEL_COMPLETED',
1079
                Transaction::STATUS_CANCELLED => 'LABEL_CANCELLED',
1080
            ];
1081
 
1082
            $types = [
1083
                Transaction::TYPE_COUPON => 'LABEL_COUPON',
1084
                Transaction::TYPE_PAYMENT => 'LABEL_PAYMENT',
1085
                Transaction::TYPE_REVERSE => 'LABEL_REVERSE',
1086
                Transaction::TYPE_TRANSFER => 'LABEL_TRANSFER',
1087
            ];
1088
 
1089
            $providers = [
1090
                Provider::PAYPAL => 'LABEL_PAYPAL',
1091
            ];
1092
 
1093
            $transactionMapper = TransactionMapper::getInstance($this->adapter);
1094
            $paginator = $transactionMapper->fetchAllDataTable($currentUser->id, $search, $page, $records_x_page, $order_field, $order_direction);
1095
 
1096
            $items = [];
1097
            $records = $paginator->getCurrentItems();
1098
            foreach($records as $record)
1099
            {
1100
                $item = [
1101
                    'id' => $record->id,
1102
                    'description' => $record->description,
1103
                    'provider' => $providers[$record->provider],
1104
                    'type' => $types[$record->type],
1105
                    'status' => $status[$record->status],
1106
                    'previous' => $record->previous,
1107
                    'amount' => $record->amount,
1108
                    'current' => $record->current,
1109
                    'updated_on' => $record->updated_on,
1110
                ];
1111
 
1112
                array_push($items, $item);
1113
            }
1114
 
1115
            return new JsonModel([
1116
                'success' => true,
1117
                'data' => [
1118
                    'items' => $items,
1119
                    'total' => $paginator->getTotalItemCount(),
1120
                ]
1121
            ]);
1122
 
1123
        } else {
1124
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1125
        }
1126
    }
1127
 
1128
 
1129
 
1130
    public function addFundAction()
1131
    {
1132
 
1133
        $request = $this->request;
1134
        if($request->isPost()) {
1135
 
1136
            $form = new FundsAddForm();
1137
            $form->setData($request->getPost()->toArray());
1138
            if($form->isValid()) {
1139
 
1140
                $currentUserPlugin = $this->plugin('currentUserPlugin');
1141
                $currentUser = $currentUserPlugin->getUser();
1142
 
1143
 
1144
 
1145
 
1146
                $dataPost = (array) $form->getData();
1147
 
1148
                $description    = $dataPost['description'];
1149
                $amount         = $dataPost['amount'];
1150
 
1151
 
1152
 
1153
                $sandbox = $this->config['leaderslinked.runmode.sandbox_paypal'];
1154
                if($sandbox) {
1155
                    //$account_id     = $this->config['leaderslinked.paypal.sandbox_account_id'];
1156
                    $client_id      = $this->config['leaderslinked.paypal.sandobx_client_id'];
1157
                    $client_secret  = $this->config['leaderslinked.paypal.sandbox_client_secret'];
1158
 
1159
 
1160
                    $environment = new SandboxEnvironment($client_id, $client_secret);
1161
 
1162
                } else {
1163
                    // $account_id     = $this->config['leaderslinked.paypal.production_account_id'];
1164
                    $client_id      = $this->config['leaderslinked.paypal.production_client_id'];
1165
                    $client_secret  = $this->config['leaderslinked.paypal.production_client_secret'];
1166
 
1167
                    $environment = new ProductionEnvironment($client_id, $client_secret);
1168
                }
1169
 
1170
                $internal_id = uniqid(Provider::PAYPAL, true);
1171
                $client = new PayPalHttpClient($environment);
1172
                $request = new OrdersCreateRequest();
1173
 
1174
 
1175
                //$request->prefer('return=representation');
1176
                $request->body = [
1177
                    'intent' => 'CAPTURE',
1178
                    'purchase_units' => [[
1179
                        'reference_id' => $internal_id,
1180
                        'description' => $description,
1181
                        'amount' => [
1182
                            'value' => number_format($amount, 2),
1183
                            'currency_code' => 'USD'
1184
                        ]
1185
                    ]],
1186
                    'application_context' => [
1187
                        'brand_name' => 'Leaders Linked',
1188
                        'locale' => 'es-UY',
1189
                        'cancel_url' => $this->url()->fromRoute('paypal/cancel', [] , ['force_canonical' => true]),
1190
                        'return_url' => $this->url()->fromRoute('paypal/success', [] , ['force_canonical' => true]),
1191
                    ]
1192
                ];
1193
 
1194
                try {
1195
                    // Call API with your client and get a response for your call
1196
                    $response = $client->execute($request);
1197
 
1198
 
1199
                    $external_id = $response->result->id;
1200
                    $approve_url = '';
1201
                    if($response->result->status == 'CREATED') {
1202
 
1203
                        $response->result->id;
1204
                        foreach($response->result->links as $link)
1205
                        {
1206
                            if($link->rel == 'approve') {
1207
                                $approve_url = $link->href;
1208
                            }
1209
                            //print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
1210
                        }
1211
 
1212
 
1213
                    }
1214
 
1215
 
1216
                    //echo json_encode($resp, JSON_PRETTY_PRINT), "\n";
1217
 
1218
 
1219
 
1220
 
1221
 
1222
                    // To toggle printing the whole response body comment/uncomment below line
1223
                    // echo json_encode($resp->result, JSON_PRETTY_PRINT), "\n";
1224
                    if($external_id && $approve_url) {
1225
 
1226
                        $transaction = new Transaction();
1227
                        $transaction->internal_id = $internal_id;
1228
                        $transaction->external_id = $external_id;
1229
                        $transaction->provider = Provider::PAYPAL;
1230
                        $transaction->user_id = $currentUser->id;
1231
                        $transaction->previous = 0;
1232
                        $transaction->amount = $amount;
1233
                        $transaction->current = 0;
1234
                        $transaction->status = Transaction::STATUS_PENDING;
1235
                        $transaction->type = Transaction::TYPE_PAYMENT;
1236
                        $transaction->description = $description;
1237
                        $transaction->request = json_encode($response, JSON_PRETTY_PRINT);
1238
 
1239
                        $requestId = Provider::PAYPAL . '-' . $external_id;
1240
 
1241
                        $this->cache->setItem($requestId, serialize($transaction));
1242
 
1243
 
1244
 
1245
 
1246
                        return new JsonModel(['success' => true, 'data' => $approve_url]);
1247
                    } else {
1248
                        return new JsonModel(['success' => false, 'data' => 'ERROR_TRANSACTION_NOT_SAVED']);
1249
                    }
1250
 
1251
 
1252
 
1253
                } catch (HttpException $ex) {
1254
 
1255
 
1256
                    return new JsonModel(['success' => false, 'data' => $ex->getMessage()]);
1257
                }
1258
 
1259
            } else {
1260
 
1261
                $message = '';;
1262
                $form_messages = (array) $form->getMessages();
1263
                foreach($form_messages  as $fieldname => $field_messages)
1264
                {
1265
                    foreach( $field_messages as $key => $value)
1266
                    {
1267
                        $message = $value;
1268
                    }
1269
                }
1270
 
1271
                $response = [
1272
                    'success'   => false,
1273
                    'data'   => $message
1274
                ];
1275
 
1276
                return new JsonModel($response);
1277
 
1278
            }
1279
 
1280
        } else {
1281
            return new JsonModel(['success' => false, 'data' => 'ERROR_METHOD_NOT_ALLOWED' ]);
1282
        }
1283
    }
1284
 
1285
    public function removeFacebookAction()
1286
    {
1287
        $request = $this->getRequest();
1288
        if($request->isPost()) {
1289
 
1290
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1291
            $currentUser = $currentUserPlugin->getUser();
1292
 
1293
 
1294
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1295
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK);
1296
 
1297
            if($userProvider) {
1298
 
1299
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_FACEBOOK)) {
1300
                    return new JsonModel([
1301
                        'success' => true,
1302
                        'data' => 'LABEL_USER_PROVIDER_FACEBOOK_REMOVED'
1303
                    ]);
1304
 
1305
                } else {
1306
                    return new JsonModel([
1307
                        'success' => false,
1308
                        'data' => $userProviderMapper->getError()
1309
                    ]);
1310
                }
1311
 
1312
 
1313
            } else {
1314
                return new JsonModel([
1315
                    'success' => false,
1316
                    'data' => 'ERROR_USER_PROVIDER_FACEBOOK_NOT_FOUND'
1317
                ]);
1318
            }
1319
 
1320
 
1321
        } else {
1322
            return new JsonModel([
1323
                'success' => false,
1324
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1325
            ]);
1326
        }
1327
    }
1328
 
1329
    public function addFacebookAction()
1330
    {
1331
        /*
1332
        $request = $this->getRequest();
1333
        if($request->isGet()) {
1334
 
1335
            try {
1336
                $app_id = $this->config['leaderslinked.facebook.app_id'];
1337
                $app_password = $this->config['leaderslinked.facebook.app_password'];
1338
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
1339
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
1340
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
1341
 
1342
 
1343
 
1344
                $fb = new \Facebook\Facebook([
1345
                    'app_id' => $app_id,
1346
                    'app_secret' => $app_password,
1347
                    'default_graph_version' => $app_graph_version,
1348
                ]);
1349
 
1350
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
1351
                $helper = $fb->getRedirectLoginHelper();
1352
                $permissions = ['email', 'public_profile']; // Optional permissions
1353
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
1354
 
1355
                return new JsonModel([
1356
                    'success' => true,
1357
                    'data' => $facebookUrl
1358
                ]);
1359
            } catch (\Throwable $e) {
1360
                return new JsonModel([
1361
                    'success' => false,
1362
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
1363
                ]);
1364
            }
1365
 
1366
        } else {
1367
            return new JsonModel([
1368
                'success' => false,
1369
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1370
            ]);
1371
        }*/
1372
    }
1373
 
1374
    public function removeTwitterAction()
1375
    {
1376
        $request = $this->getRequest();
1377
        if($request->isPost()) {
1378
 
1379
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1380
            $currentUser = $currentUserPlugin->getUser();
1381
 
1382
 
1383
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1384
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER);
1385
 
1386
            if($userProvider) {
1387
 
1388
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_TWITTER)) {
1389
                    return new JsonModel([
1390
                        'success' => true,
1391
                        'data' => 'LABEL_USER_PROVIDER_TWITTER_REMOVED'
1392
                    ]);
1393
 
1394
                } else {
1395
                    return new JsonModel([
1396
                        'success' => false,
1397
                        'data' => $userProviderMapper->getError()
1398
                    ]);
1399
                }
1400
 
1401
 
1402
            } else {
1403
                return new JsonModel([
1404
                    'success' => false,
1405
                    'data' => 'ERROR_USER_PROVIDER_TWITTER_NOT_FOUND'
1406
                ]);
1407
            }
1408
 
1409
 
1410
        } else {
1411
            return new JsonModel([
1412
                'success' => false,
1413
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1414
            ]);
1415
        }
1416
    }
1417
 
1418
    public function addTwitterAction()
1419
    {
1420
 
1421
        $request = $this->getRequest();
1422
        if($request->isGet()) {
1423
 
1424
            try {
1425
                if($this->config['leaderslinked.runmode.sandbox']) {
1426
 
1427
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
1428
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
1429
 
1430
                } else {
1431
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
1432
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
1433
                }
1434
 
1435
 
1436
 
1437
                //Twitter
1438
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
1439
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
1440
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
1441
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url ]);
1442
                $twitterUrl = $twitter->url('oauth/authorize', [ 'oauth_token' => $request_token['oauth_token'] ]);
1443
 
1444
                $twitterSession = new \Laminas\Session\Container('twitter');
1445
                $twitterSession->oauth_token = $request_token['oauth_token'];
1446
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
1447
 
1448
                return new JsonModel([
1449
                    'success' => true,
1450
                    'data' =>  $twitterUrl
1451
                ]);
1452
            } catch (\Throwable $e) {
1453
                return new JsonModel([
1454
                    'success' => false,
1455
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
1456
                ]);
1457
            }
1458
 
1459
        } else {
1460
            return new JsonModel([
1461
                'success' => false,
1462
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1463
            ]);
1464
        }
1465
 
1466
 
1467
    }
1468
 
1469
    public function removeGoogleAction()
1470
    {
1471
        $request = $this->getRequest();
1472
        if($request->isPost()) {
1473
 
1474
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1475
            $currentUser = $currentUserPlugin->getUser();
1476
 
1477
 
1478
            $userProviderMapper = UserProviderMapper::getInstance($this->adapter);
1479
            $userProvider = $userProviderMapper->fetchOneByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE);
1480
 
1481
            if($userProvider) {
1482
 
1483
                if($userProviderMapper->deleteByUserIdAndProvider($currentUser->id, UserProvider::PROVIDER_GOOGLE)) {
1484
                    return new JsonModel([
1485
                        'success' => true,
1486
                        'data' => 'LABEL_USER_PROVIDER_GOOGLE_REMOVED'
1487
                    ]);
1488
 
1489
                } else {
1490
                    return new JsonModel([
1491
                        'success' => false,
1492
                        'data' => $userProviderMapper->getError()
1493
                    ]);
1494
                }
1495
 
1496
 
1497
            } else {
1498
                return new JsonModel([
1499
                    'success' => false,
1500
                    'data' => 'ERROR_USER_PROVIDER_GOOGLE_NOT_FOUND'
1501
                ]);
1502
            }
1503
 
1504
 
1505
        } else {
1506
            return new JsonModel([
1507
                'success' => false,
1508
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1509
            ]);
1510
        }
1511
    }
1512
 
1513
    public function addGoogleAction()
1514
    {
1515
        $request = $this->getRequest();
1516
        if($request->isGet()) {
1517
 
1518
            try {
1519
 
1520
 
1521
                //Google
1522
                $google = new \Google_Client();
1523
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
1524
                $google->setAccessType("offline");        // offline access
1525
 
1526
                $google->setIncludeGrantedScopes(true);   // incremental auth
1527
 
1528
                $google->addScope('profile');
1529
                $google->addScope('email');
1530
 
1531
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
1532
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
1533
 
1534
                $google->setRedirectUri($redirect_url);
1535
                $googleUrl = $google->createAuthUrl();
1536
 
1537
                return new JsonModel([
1538
                    'success' => true,
1539
                    'data' =>  $googleUrl
1540
                ]);
1541
            } catch (\Throwable $e) {
1542
                return new JsonModel([
1543
                    'success' => false,
1544
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
1545
                ]);
1546
            }
1547
 
1548
        } else {
1549
            return new JsonModel([
1550
                'success' => false,
1551
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1552
            ]);
1553
        }
1554
    }
1555
 
1556
    public function deleteAccountAction()
1557
    {
1558
 
1559
 
1560
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1561
        $user = $currentUserPlugin->getUser();
1562
 
1563
 
1564
 
1565
        $request = $this->getRequest();
1566
 
1567
        if($request->isGet()) {
1568
 
1569
            $this->sendEmailDeleteAccountKey($user);
1570
 
1571
 
1572
            return new JsonModel([
1573
                'success' => true,
190 efrain 1574
                'data' =>  'LABEL_DELETE_ACCOUNT_WE_HAVE_SENT_A_CONFIRMATION_CODE'
1575
 
1 efrain 1576
            ]);
1577
 
1578
        } else  if($request->isPost()) {
1579
 
1580
            $code = $this->params()->fromPost('code');
1581
            if(empty($code) || $code != $user->delete_account_key) {
1582
 
1583
                $this->sendEmailDeleteAccountKey($user);
1584
 
1585
                return new JsonModel([
1586
                    'success' => false,
190 efrain 1587
                    'data' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_IS_WRONG'
1 efrain 1588
                ]);
1589
            }
1590
 
1591
            $delete_account_generated_on = strtotime($user->delete_account_generated_on);
1592
            $expiry_time = $delete_account_generated_on + $this->config['leaderslinked.security.delete_account_expired'];
1593
 
1594
 
1595
            if (time() > $expiry_time) {
1596
 
1597
                $this->sendEmailDeleteAccountKey($user) ;
1598
 
1599
                return new JsonModel([
1600
                    'success' => false,
190 efrain 1601
                    'data' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_EXPIRED'
1 efrain 1602
                ]);
1603
 
1604
 
1605
            }
1606
 
1607
            $userDeleted  = new UserDeleted();
1608
            $userDeleted->user_id = $user->id;
1609
            $userDeleted->first_name = $user->first_name;
1610
            $userDeleted->last_name = $user->last_name;
1611
            $userDeleted->email = $user->email;
1612
            $userDeleted->image = $user->image;
1613
            $userDeleted->phone = $user->phone;
1614
            $userDeleted->pending = UserDeleted::PENDING_YES;
1615
 
1616
 
1617
            $userDeletedMapper = UserDeletedMapper::getInstance($this->adapter);
1618
            if ($userDeletedMapper->insert($userDeleted)) {
1619
 
1620
                $this->sendEmailDeleteAccountCompleted($user);
1621
 
1622
                $user->first_name = 'LABEL_DELETE_ACCOUNT_FIRST_NAME';
1623
                $user->last_name = 'LABEL_DELETE_ACCOUNT_LAST_NAME';
1624
                $user->email = 'user-deleted-' . uniqid() . '@leaderslinked.com';
1625
                $user->image = '';
1626
                $user->usertype_id = UserType::USER_DELETED;
1627
                $user->status = User::STATUS_DELETED;
1628
                $user->delete_account_key = '';
1629
                $user->delete_account_generated_on = '';
1630
 
1631
                $userMapper = UserMapper::getInstance($this->adapter);
1632
                if($userMapper->update($user)) {
1633
 
1634
 
1635
 
1636
                    return new JsonModel([
1637
                        'success' => true,
190 efrain 1638
                        'data' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_STARTED_DELETING_YOUR_DATA',
1 efrain 1639
                    ]);
1640
 
1641
 
1642
                } else {
1643
                    return new JsonModel([
1644
                        'success' => false,
190 efrain 1645
                        'data' => $userDeletedMapper->getError()
1 efrain 1646
                    ]);
1647
                }
1648
 
1649
 
1650
 
1651
            } else {
1652
                return new JsonModel([
1653
                    'success' => false,
190 efrain 1654
                    'data' =>  $userDeletedMapper->getError()
1655
 
1 efrain 1656
                ]);
1657
            }
1658
 
1659
 
1660
 
1661
 
1662
 
1663
        }
1664
 
1665
 
1666
            return new JsonModel([
1667
                'success' => false,
1668
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1669
            ]);
1670
    }
1671
 
1672
 
1673
 
1674
 
1675
    private function sendEmailDeleteAccountKey($user)
1676
    {
1677
        $delete_account_key = Functions::generatePassword(8);
1678
 
1679
        $userMapper = UserMapper::getInstance($this->adapter);
1680
        $userMapper->updateDeleteAccountKey($user->id, $delete_account_key);
1681
 
1682
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1683
        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_CODE, $user->network_id);
1684
        if($emailTemplate) {
1685
            $arrayCont = [
1686
                'firstname' => $user->first_name,
1687
                'lastname'  => $user->last_name,
1688
                'code'      => $delete_account_key,
1689
                'link'      => ''
1690
            ];
1691
 
1692
            $email = new QueueEmail($this->adapter);
1693
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1694
        }
1695
    }
1696
 
1697
 
1698
    private function sendEmailDeleteAccountCompleted($user)
1699
    {
1700
 
1701
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1702
        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_COMPLETED, $user->network_id);
1703
        if($emailTemplate) {
1704
            $arrayCont = [
1705
                'firstname' => $user->first_name,
1706
                'lastname'  => $user->last_name,
1707
                'code'      => '',
1708
                'link'      => ''
1709
            ];
1710
 
1711
            $email = new QueueEmail($this->adapter);
1712
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1713
        }
1714
    }
1715
 
1716
}