Proyectos de Subversion LeadersLinked - Services

Rev

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