Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6849 | | Comparar con el anterior | Ultima modificación | Ver Log |

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