Proyectos de Subversion LeadersLinked - Services

Rev

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