Proyectos de Subversion LeadersLinked - Backend

Rev

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

Rev Autor Línea Nro. Línea
1 www 1
<?php
17167 ariadna 2
 
1 www 3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
8
 
9
 
16768 efrain 10
 
1 www 11
use Laminas\Mvc\Controller\AbstractActionController;
12
use Laminas\Log\LoggerInterface;
13
 
14
use Laminas\View\Model\ViewModel;
15
use Laminas\View\Model\JsonModel;
16
use LeadersLinked\Library\Functions;
17
use LeadersLinked\Mapper\UserMapper;
18
use LeadersLinked\Mapper\UserPasswordMapper;
19
 
20
use LeadersLinked\Model\User;
17171 ariadna 21
 
1 www 22
use LeadersLinked\Model\CompanyUser;
23
use LeadersLinked\Mapper\CompanyUserMapper;
24
use LeadersLinked\Mapper\CompanyUserRoleMapper;
25
use LeadersLinked\Mapper\RoleMapper;
26
use LeadersLinked\Model\UserType;
27
use LeadersLinked\Model\UserPassword;
28
use PhpOffice\PhpSpreadsheet\IOFactory;
17169 ariadna 29
use LeadersLinked\Form\User\UserUploadForm;
17170 ariadna 30
 
1 www 31
use LeadersLinked\Mapper\CompanyServiceMapper;
32
use LeadersLinked\Model\CompanyService;
33
use LeadersLinked\Model\Role;
34
use LeadersLinked\Mapper\CompanyRoleMapper;
35
use LeadersLinked\Model\CompanyUserRole;
36
use LeadersLinked\Model\Notification;
37
use LeadersLinked\Model\EmailTemplate;
38
use LeadersLinked\Mapper\NotificationMapper;
39
use LeadersLinked\Mapper\UserNotificationSettingMapper;
40
use LeadersLinked\Mapper\EmailTemplateMapper;
41
use LeadersLinked\Library\QueueEmail;
15351 efrain 42
use LeadersLinked\Mapper\NetworkMapper;
43
use LeadersLinked\Model\Network;
15460 efrain 44
use LeadersLinked\Mapper\CompanyMapper;
45
use LeadersLinked\Mapper\ConnectionMapper;
46
use LeadersLinked\Model\Connection;
47
use LeadersLinked\Mapper\CompanyFollowerMapper;
48
use LeadersLinked\Model\CompanyFollower;
49
use LeadersLinked\Mapper\CountryMapper;
50
use LeadersLinked\Mapper\LocationMapper;
51
use LeadersLinked\Model\Location;
16248 efrain 52
use LeadersLinked\Form\User\ChangeTypeForm;
17171 ariadna 53
use LeadersLinked\Form\User\ChangePasswordForm;
16299 efrain 54
use LeadersLinked\Form\User\NetworkDataForm;
16768 efrain 55
use LeadersLinked\Cache\CacheInterface;
56
use LeadersLinked\Cache\CacheImpl;
1 www 57
 
58
class UserController extends AbstractActionController
59
{
60
    /**
61
     *
16769 efrain 62
     * @var \Laminas\Db\Adapter\AdapterInterface
1 www 63
     */
64
    private $adapter;
17167 ariadna 65
 
1 www 66
    /**
67
     *
16769 efrain 68
     * @var \LeadersLinked\Cache\CacheInterface
1 www 69
     */
16769 efrain 70
    private $cache;
17167 ariadna 71
 
72
 
16769 efrain 73
    /**
74
     *
75
     * @var \Laminas\Log\LoggerInterface
76
     */
1 www 77
    private $logger;
17167 ariadna 78
 
1 www 79
    /**
80
     *
81
     * @var array
82
     */
83
    private $config;
17167 ariadna 84
 
85
 
16768 efrain 86
    /**
16769 efrain 87
     *
88
     * @var \Laminas\Mvc\I18n\Translator
16768 efrain 89
     */
16769 efrain 90
    private $translator;
17167 ariadna 91
 
92
 
1 www 93
    /**
94
     *
16769 efrain 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
16769 efrain 99
     * @param \Laminas\Mvc\I18n\Translator $translator
1 www 100
     */
16769 efrain 101
    public function __construct($adapter, $cache, $logger, $config, $translator)
1 www 102
    {
16769 efrain 103
        $this->adapter      = $adapter;
104
        $this->cache        = $cache;
105
        $this->logger       = $logger;
106
        $this->config       = $config;
107
        $this->translator   = $translator;
1 www 108
    }
17167 ariadna 109
 
1 www 110
    public function indexAction()
111
    {
112
        $currentUserPlugin = $this->plugin('currentUserPlugin');
113
        $currentUser = $currentUserPlugin->getUser();
114
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 115
 
15351 efrain 116
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
16299 efrain 117
        $currentNetwork = $currentNetworkPlugin->getNetwork();
17167 ariadna 118
 
119
 
1 www 120
        $request = $this->getRequest();
17167 ariadna 121
 
122
        if ($request->isGet())
123
 
124
 
1 www 125
            $headers  = $request->getHeaders();
17167 ariadna 126
 
127
        $isJson = false;
128
        if ($headers->has('Accept')) {
129
            $accept = $headers->get('Accept');
130
 
131
            $prioritized = $accept->getPrioritized();
132
 
133
            foreach ($prioritized as $key => $value) {
134
                $raw = trim($value->getRaw());
135
 
136
                if (!$isJson) {
137
                    $isJson = strpos($raw, 'json');
1 www 138
                }
139
            }
17167 ariadna 140
        }
141
 
142
        if ($isJson) { {
16299 efrain 143
                $network_id = $this->params()->fromQuery('network_id');
17167 ariadna 144
                if ($currentUser->is_super_user == User::IS_SUPER_USER_YES) {
145
 
16299 efrain 146
                    $networkMapper = NetworkMapper::getInstance($this->adapter);
147
                    $network = $networkMapper->fetchOneByUuid($network_id);
17167 ariadna 148
                    if (!$network) {
16299 efrain 149
                        $network = $currentNetwork;
150
                    }
151
                } else {
152
                    $network = $currentNetwork;
153
                }
15351 efrain 154
 
17167 ariadna 155
 
156
 
1 www 157
                $search = $this->params()->fromQuery('search', []);
16766 efrain 158
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
17167 ariadna 159
 
3343 efrain 160
                //$page               = intval($this->params()->fromQuery('start', 1), 10);
161
                //$records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
17167 ariadna 162
 
1 www 163
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
17167 ariadna 164
                $page               = (intval($this->params()->fromQuery('start', 1), 10) / $records_x_page) + 1;
165
 
1 www 166
                $order =  $this->params()->fromQuery('order', []);
167
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
16766 efrain 168
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
17167 ariadna 169
 
1 www 170
                $fields =  ['first_name', 'last_name', 'email'];
171
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
17167 ariadna 172
 
173
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
1 www 174
                    $order_direction = 'ASC';
175
                }
176
 
17167 ariadna 177
 
178
                if ($currentCompany) {
1 www 179
                    $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
17167 ariadna 180
 
181
                    $roles = [];
1 www 182
                    $roleMapper = RoleMapper::getInstance($this->adapter);
17167 ariadna 183
                    $records = $roleMapper->fetchAll();
184
                    foreach ($records as $record) {
185
                        $roles[$record->id] = $record->name;
1 www 186
                    }
17167 ariadna 187
 
188
 
1 www 189
                    //Usuarios cuando el nivel es empresa
17167 ariadna 190
 
1 www 191
                    $acl = $this->getEvent()->getViewModel()->getVariable('acl');
192
                    $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'users/unblock');
193
                    $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'users/change-password');
17167 ariadna 194
 
1 www 195
                    $allowAccept    = $acl->isAllowed($currentUser->usertype_id, 'users/accept') ? 1 : 0;
196
                    $allowCancel    = $acl->isAllowed($currentUser->usertype_id, 'users/cancel') ? 1 : 0;
197
                    $allowReject    = $acl->isAllowed($currentUser->usertype_id, 'users/reject') ? 1 : 0;
198
                    $allowEdit     = $acl->isAllowed($currentUser->usertype_id, 'users/edit') ? 1 : 0;
16248 efrain 199
 
17167 ariadna 200
 
201
 
16766 efrain 202
                    $status = Functions::sanitizeFilterString($this->params()->fromQuery('status'));
17167 ariadna 203
                    if (!in_array($status, [
1 www 204
                        CompanyUser::STATUS_ACCEPTED,
205
                        CompanyUser::STATUS_ADMIN_WILL_ADD,
206
                        CompanyUser::STATUS_CANCELLED,
207
                        CompanyUser::STATUS_PENDING,
208
                        CompanyUser::STATUS_REJECTED,
209
                        CompanyUser::STATUS_SENT,
17167 ariadna 210
                    ])) {
1 www 211
                        $status = '';
212
                    }
17167 ariadna 213
 
214
 
215
 
1 www 216
                    $userMapper = UserMapper::getInstance($this->adapter);
217
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
17167 ariadna 218
 
16767 efrain 219
                    $paginator = $userMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $status,   $page, $records_x_page, $order_field, $order_direction);
17167 ariadna 220
 
1 www 221
                    $items = [];
222
                    $records = $paginator->getCurrentItems();
17167 ariadna 223
 
224
                    foreach ($records as $record) {
225
 
226
                        $actions = [];
227
                        $actions['link_profile'] = 'https://' . $network->main_hostname . '/profile/view/' . $record['uuid'];
228
 
229
 
230
 
231
 
232
                        $details = [];
233
                        switch ($record['status']) {
234
 
235
                            case CompanyUser::STATUS_PENDING:
1 www 236
                                $details['status']  = 'LABEL_PENDING';
237
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
238
                                $actions['link_reject'] = $allowReject ? $this->url()->fromRoute('users/reject', ['id' => $record['uuid']]) : '';
239
                                break;
17167 ariadna 240
 
241
                            case CompanyUser::STATUS_ACCEPTED:
1 www 242
                                $details['status']  = 'LABEL_ACCEPTED';
17167 ariadna 243
                                if ($record['creator'] == CompanyUser::CREATOR_NO) {
1 www 244
                                    $actions['link_edit'] = $allowEdit ? $this->url()->fromRoute('users/edit', ['id' => $record['uuid']]) : '';
17167 ariadna 245
 
246
 
247
 
1 www 248
                                    $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('users/cancel', ['id' => $record['uuid']]) : '';
17167 ariadna 249
                                }
250
 
1 www 251
                                break;
17167 ariadna 252
 
253
                            case CompanyUser::STATUS_ADMIN_WILL_ADD:
1 www 254
                                $details['status']  = 'LABEL_ADMIN_WILL_ADD';
255
                                $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('users/cancel', ['id' => $record['uuid']]) : '';
256
                                $actions['link_edit'] = $allowEdit ? $this->url()->fromRoute('users/edit', ['id' => $record['uuid']]) : '';
17167 ariadna 257
 
1 www 258
                                break;
17167 ariadna 259
 
260
                            case CompanyUser::STATUS_SENT:
1 www 261
                                $details['status']  = 'LABEL_INVITED';
262
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
263
                                $actions['link_reject'] = $allowReject ? $this->url()->fromRoute('users/reject', ['id' => $record['uuid']]) : '';
264
                                break;
17167 ariadna 265
 
266
                            case CompanyUser::STATUS_REJECTED:
1 www 267
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
268
                                $details['status']  = 'LABEL_REJECTED';
269
                                break;
17167 ariadna 270
 
271
                            case CompanyUser::STATUS_CANCELLED:
1 www 272
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
273
                                $details['status']  = 'LABEL_CANCELLED';
274
                                break;
17167 ariadna 275
 
276
                            default:
1 www 277
                                $details['status']  = '';
278
                                break;
279
                        }
17167 ariadna 280
 
1 www 281
                        $totalOtherCompanies = $companyUserMapper->fetchCountOtherCompaniesByCompanyIdAndUserId($currentCompany->id, $record['id']);
17167 ariadna 282
                        if (!$totalOtherCompanies) {
283
 
284
                            $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('users/change-password', ['id' => $record['uuid']]) : '';
285
                            if ($record['blocked'] == User::BLOCKED_YES) {
286
                                $actions['link_unblock'] = $allowUnblock ? $this->url()->fromRoute('users/unblock', ['id' => $record['uuid']]) : '';
287
                            }
1 www 288
                        }
17167 ariadna 289
 
290
                        if ($record['blocked'] == User::BLOCKED_YES) {
1 www 291
                            $details['blocked'] = 'LABEL_YES';
17167 ariadna 292
                        } else if ($record['blocked'] == User::BLOCKED_NO) {
1 www 293
                            $details['blocked'] = 'LABEL_NO';
294
                        }
17167 ariadna 295
                        if ($record['email_verified'] == User::EMAIL_VERIFIED_YES) {
1 www 296
                            $details['email_verified'] = 'LABEL_YES';
17167 ariadna 297
                        } else if ($record['email_verified'] == User::EMAIL_VERIFIED_NO) {
1 www 298
                            $details['email_verified'] = 'LABEL_NO';
299
                        }
300
                        $details['login_attempt'] = $record['login_attempt'];
17167 ariadna 301
 
302
 
1 www 303
                        $company_user_roles = $companyUserRoleMapper->fetchAllByCompanyIdAndUserId($currentCompany->id, $record['id']);
17167 ariadna 304
 
1 www 305
                        $details['roles'] = [];
17167 ariadna 306
 
307
                        if ($record['creator'] == CompanyUser::CREATOR_YES) {
1 www 308
                            $details['roles'][] = 'LABEL_ALL_PERMITS';
17167 ariadna 309
                            $details['creator'] = 'LABEL_YES';
310
                        } else {
311
                            $details['creator'] = 'LABEL_NO';
312
                            foreach ($company_user_roles as $company_user_role) {
313
                                $role = $roles[$company_user_role->role_id];
1 www 314
                                $details['roles'][] = $role;
315
                            }
17167 ariadna 316
                        }
317
 
318
 
1 www 319
                        $details['backend'] = $record['backend'] == CompanyUser::BACKEND_YES ? 'LABEL_YES' : 'LABEL_NO';
320
 
17167 ariadna 321
 
322
 
323
 
324
 
325
 
1 www 326
                        $item = [
17167 ariadna 327
                            'first_name' => $record['first_name'],
1 www 328
                            'last_name' => $record['last_name'],
329
                            'email' => $record['email'],
330
                            'details' => $details,
17167 ariadna 331
                            'actions' =>  $actions,
332
                        ];
333
 
1 www 334
                        array_push($items, $item);
335
                    }
336
                } else {
337
                    //Usuario cuando el nivel es administrador
17167 ariadna 338
 
339
 
340
 
1 www 341
                    $acl = $this->getEvent()->getViewModel()->getVariable('acl');
342
                    $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'users/unblock');
343
                    $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'users/change-password');
16248 efrain 344
                    $allowChangeType   = $acl->isAllowed($currentUser->usertype_id, 'users/change-type') ? 1 : 0;
17167 ariadna 345
 
346
 
347
 
1 www 348
                    $userMapper = UserMapper::getInstance($this->adapter);
15455 efrain 349
                    $paginator = $userMapper->fetchAllDataTableByNetworkId($network->id, $search, $page, $records_x_page, $order_field, $order_direction);
17167 ariadna 350
 
1 www 351
                    $items = [];
352
                    $records = $paginator->getCurrentItems();
17167 ariadna 353
 
354
                    foreach ($records as $record) {
1 www 355
                        $actions = [];
17167 ariadna 356
 
357
                        if ($currentNetwork->id == $record->network_id) {
358
 
359
                            $actions['link_profile'] = 'https://' . $network->main_hostname . '/profile/view/' . $record->uuid;
16299 efrain 360
                        } else {
361
                            $actions['link_profile'] = '';
362
                        }
17167 ariadna 363
 
364
                        $details = [];
365
                        if ($record->status == User::STATUS_ACTIVE) {
1 www 366
                            $details['status'] = 'LABEL_ACTIVE';
17167 ariadna 367
                        } else if ($record->status == User::STATUS_INACTIVE) {
368
                            $details['status'] = 'LABEL_INACTIVE';
1 www 369
                        }
17167 ariadna 370
                        if ($record->blocked == User::BLOCKED_YES) {
1 www 371
                            $details['blocked'] = 'LABEL_YES';
17167 ariadna 372
                        } else if ($record->blocked == User::BLOCKED_NO) {
1 www 373
                            $details['blocked'] = 'LABEL_NO';
374
                        }
17167 ariadna 375
                        if ($record->email_verified == User::EMAIL_VERIFIED_YES) {
1 www 376
                            $details['email_verified'] = 'LABEL_YES';
17167 ariadna 377
                        } else if ($record->email_verified == User::EMAIL_VERIFIED_NO) {
1 www 378
                            $details['email_verified'] = 'LABEL_NO';
379
                        }
17167 ariadna 380
 
381
                        if ($record->usertype_id == UserType::ADMIN) {
16248 efrain 382
                            $details['user_type'] = 'LABEL_ADMINISTRATOR';
17167 ariadna 383
                        } else   if ($record->usertype_id == UserType::USER) {
16248 efrain 384
                            $details['user_type'] = 'LABEL_USER';
385
                        }
17167 ariadna 386
 
1 www 387
                        $details['login_attempt'] = $record->login_attempt;
17167 ariadna 388
 
389
 
390
                        $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('users/change-password', ['id' => $record->uuid]) : '';
391
                        $actions['link_unblock'] = $allowUnblock && $record->blocked == User::BLOCKED_YES ? $this->url()->fromRoute('users/unblock', ['id' => $record->uuid]) : '';
392
                        $actions['link_change_type'] =  $record->is_super_user == User::IS_SUPER_USER_NO && $allowChangeType ? $this->url()->fromRoute('users/change-type', ['id' => $record->uuid]) : '';
393
 
394
 
1 www 395
                        $item = [
396
                            'first_name' => $record->first_name,
397
                            'last_name' => $record->last_name,
398
                            'email' => $record->email,
399
                            'details' => $details,
400
                            'actions' => $actions
17167 ariadna 401
                        ];
402
 
1 www 403
                        array_push($items, $item);
404
                    }
405
                }
406
            }
17167 ariadna 407
 
1 www 408
            return new JsonModel([
409
                'success' => true,
410
                'data' => [
411
                    'items' => $items,
412
                    'total' => $paginator->getTotalItemCount(),
413
                ]
414
            ]);
17167 ariadna 415
        } else if ($request->isGet()) {
1 www 416
            $this->layout()->setTemplate('layout/layout-backend');
417
            $viewModel = new ViewModel();
17167 ariadna 418
 
419
 
16299 efrain 420
            $networks = [];
421
            $networkMapper = NetworkMapper::getInstance($this->adapter);
17167 ariadna 422
 
423
            if ($currentUser->is_super_user == User::IS_SUPER_USER_YES) {
16299 efrain 424
                $records = $networkMapper->fetchAll();
17167 ariadna 425
                foreach ($records as $record) {
426
                    $networks[$record->uuid] = $record->name;
16299 efrain 427
                }
428
            } else {
17167 ariadna 429
                $networks[$currentNetwork->uuid] = $currentNetwork->name;
16299 efrain 430
            }
17167 ariadna 431
 
432
 
16299 efrain 433
            $formFilter = new NetworkDataForm($networks);
15460 efrain 434
            $formUploadUsers = new UserUploadForm();
1 www 435
            $formChangePassword = new ChangePasswordForm();
16248 efrain 436
            $formChangeType = new ChangeTypeForm();
17167 ariadna 437
 
1 www 438
            $company = $currentUserPlugin->getCompany();
17167 ariadna 439
            if ($company) {
1 www 440
                $viewModel->setTemplate('leaders-linked/users/company.phtml');
17167 ariadna 441
            } else {
1 www 442
                $viewModel->setTemplate('leaders-linked/users/index.phtml');
443
            }
15460 efrain 444
            $viewModel->setVariables([
445
                'formUploadUsers' => $formUploadUsers,
446
                'formChangePassword' => $formChangePassword,
16248 efrain 447
                'formChangeType' => $formChangeType,
16299 efrain 448
                'formFilter' => $formFilter
17167 ariadna 449
            ]);
450
            return $viewModel;
1 www 451
        } else {
452
            return new JsonModel([
453
                'success' => false,
454
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
455
            ]);;
456
        }
457
    }
458
    /*
459
    public function addAction()
460
    {
461
        $currentUserPlugin = $this->plugin('currentUserPlugin');
462
        $currentUser = $currentUserPlugin->getUser();
463
 
464
        $request = $this->getRequest();
465
 
466
 
467
        if($request->isPost()) {
468
            $form = new  AddForm($this->adapter);
469
            $dataPost = $request->getPost()->toArray();
470
 
471
            $form->setData($dataPost);
472
 
473
            if($form->isValid()) {
474
                $dataPost = (array) $form->getData();
475
 
476
                $hydrator = new ObjectPropertyHydrator();
477
                $user = new User();
478
                $hydrator->hydrate($dataPost, $user);
479
 
480
 
481
                $userMapper = UserMapper::getInstance($this->adapter);
482
                $result = $userMapper->insert($user);
483
 
484
                if($result) {
485
                    $this->logger->info('Se agrego el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
486
 
487
                    $data = [
488
                        'success'   => true,
489
                        'data'   => 'LABEL_RECORD_ADDED'
490
                    ];
491
                } else {
492
                    $data = [
493
                        'success'   => false,
494
                        'data'      => $userMapper->getError()
495
                    ];
496
 
497
                }
498
 
499
                return new JsonModel($data);
500
 
501
            } else {
502
                $messages = [];
503
                $form_messages = (array) $form->getMessages();
504
                foreach($form_messages  as $fieldname => $field_messages)
505
                {
506
 
507
                    $messages[$fieldname] = array_values($field_messages);
508
                }
509
 
510
                return new JsonModel([
511
                    'success'   => false,
512
                    'data'   => $messages
513
                ]);
514
            }
515
 
516
        } else {
517
            $data = [
518
                'success' => false,
519
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
520
            ];
521
 
522
            return new JsonModel($data);
523
        }
524
 
525
        return new JsonModel($data);
526
    }
527
 
528
    public function editAction()
529
    {
530
        $currentUserPlugin = $this->plugin('currentUserPlugin');
531
        $currentUser = $currentUserPlugin->getUser();
532
 
533
        $request = $this->getRequest();
534
        $id = $this->params()->fromRoute('id');
535
 
536
 
537
        if(!$id) {
538
            $data = [
539
                'success'   => false,
540
                'data'   => 'ERROR_INVALID_PARAMETER'
541
            ];
542
 
543
            return new JsonModel($data);
544
        }
545
 
546
        $userMapper = UserMapper::getInstance($this->adapter);
547
        $user = $userMapper->fetchOne($id);
548
        if(!$user) {
549
            $data = [
550
                'success'   => false,
551
                'data'   => 'ERROR_RECORD_NOT_FOUND'
552
            ];
553
 
554
            return new JsonModel($data);
555
        }
556
 
557
        if($request->isPost()) {
558
            $form = new  EditForm($this->adapter);
559
            $dataPost = $request->getPost()->toArray();
560
 
561
            $form->setData($dataPost);
562
 
563
            if($form->isValid()) {
564
                $dataPost = (array) $form->getData();
565
 
566
                $hydrator = new ObjectPropertyHydrator();
567
                $hydrator->hydrate($dataPost, $user);
568
                $result = $userMapper->update($user);
569
 
570
                if($result) {
571
                    $this->logger->info('Se actualizo el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
572
 
573
                    $data = [
574
                        'success' => true,
575
                        'data' => 'LABEL_RECORD_UPDATED'
576
                    ];
577
                } else {
578
                    $data = [
579
                        'success'   => false,
580
                        'data'      => $userMapper->getError()
581
                    ];
582
                }
583
 
584
                return new JsonModel($data);
585
 
586
            } else {
587
                $messages = [];
588
                $form_messages = (array) $form->getMessages();
589
                foreach($form_messages  as $fieldname => $field_messages)
590
                {
591
                    $messages[$fieldname] = array_values($field_messages);
592
                }
593
 
594
                return new JsonModel([
595
                    'success'   => false,
596
                    'data'   => $messages
597
                ]);
598
            }
599
        } else if ($request->isGet()) {
600
            $hydrator = new ObjectPropertyHydrator();
601
 
602
            $data = [
603
                'success' => true,
604
                'data' => $hydrator->extract($user)
605
            ];
606
 
607
            return new JsonModel($data);
608
        } else {
609
            $data = [
610
                'success' => false,
611
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
612
            ];
613
 
614
            return new JsonModel($data);
615
        }
616
 
617
        return new JsonModel($data);
618
    }
619
 
620
    public function deleteAction()
621
    {
622
        $currentUserPlugin = $this->plugin('currentUserPlugin');
623
        $currentUser = $currentUserPlugin->getUser();
624
 
625
        $request = $this->getRequest();
626
        $id = $this->params()->fromRoute('id');
627
 
628
        if(!$id) {
629
            $data = [
630
                'success'   => false,
631
                'data'   => 'ERROR_INVALID_PARAMETER'
632
            ];
633
 
634
            return new JsonModel($data);
635
        }
636
 
637
 
638
        $userMapper = UserMapper::getInstance($this->adapter);
639
        $user = $userMapper->fetchOne($id);
640
        if(!$user) {
641
            $data = [
642
                'success'   => false,
643
                'data'   => 'ERROR_RECORD_NOT_FOUND'
644
            ];
645
 
646
            return new JsonModel($data);
647
        }
648
 
649
        if($request->isPost()) {
650
            $result = $userMapper->delete($user);
651
            if($result) {
652
                $this->logger->info('Se borro el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
653
 
654
                $data = [
655
                    'success' => true,
656
                    'data' => 'LABEL_RECORD_DELETED'
657
                ];
658
            } else {
659
 
660
                $data = [
661
                    'success'   => false,
662
                    'data'      => $userMapper->getError()
663
                ];
664
 
665
                return new JsonModel($data);
666
            }
667
 
668
        } else {
669
            $data = [
670
                'success' => false,
671
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
672
            ];
673
 
674
            return new JsonModel($data);
675
        }
676
 
677
        return new JsonModel($data);
678
    }*/
17167 ariadna 679
 
1 www 680
    public function unblockAction()
681
    {
682
        $currentUserPlugin = $this->plugin('currentUserPlugin');
683
        $currentUser = $currentUserPlugin->getUser();
684
        $request = $this->getRequest();
685
 
17167 ariadna 686
 
687
        if ($request->isPost()) {
688
 
1 www 689
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 690
            if (!$uuid) {
1 www 691
                return new JsonModel([
692
                    'success'   => false,
693
                    'data'      => 'ERROR_INVALID_PARAMETER'
694
                ]);
695
            }
17167 ariadna 696
 
1 www 697
            $userMapper = UserMapper::getInstance($this->adapter);
698
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 699
 
700
            if (!$user) {
1 www 701
                return new JsonModel([
702
                    'success'   => false,
703
                    'data'      => 'ERROR_USER_NOT_FOUND'
704
                ]);
705
            }
17167 ariadna 706
 
707
            if ($user->blocked == User::BLOCKED_NO) {
1 www 708
                return new JsonModel([
709
                    'success'   => false,
710
                    'data'      => 'ERROR_USER_IS_NOT_BLOCKED'
711
                ]);
712
            }
713
 
714
 
17167 ariadna 715
 
1 www 716
            $result = $userMapper->unblock($user);
17167 ariadna 717
            if ($result) {
1 www 718
                $this->logger->info('El usuario : ' . $user->email . ' ha sido desbloqueado ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 719
 
1 www 720
                return new JsonModel([
721
                    'success'   => true,
722
                    'data'      => 'LABEL_USER_HAS_BEEN_UNBLOCKED',
723
                ]);
17167 ariadna 724
            } else {
725
 
1 www 726
                return new JsonModel([
727
                    'success'   => false,
728
                    'data'      => $userMapper->getError()
729
                ]);
730
            }
731
        }
17167 ariadna 732
 
733
 
734
 
1 www 735
        return new JsonModel([
736
            'success' => false,
737
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
738
        ]);
739
    }
17167 ariadna 740
 
129 efrain 741
    public function emailVerifyAction()
742
    {
743
        $currentUserPlugin = $this->plugin('currentUserPlugin');
744
        $currentUser = $currentUserPlugin->getUser();
745
        $request = $this->getRequest();
17167 ariadna 746
 
747
 
748
        if ($request->isPost()) {
749
 
129 efrain 750
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 751
            if (!$uuid) {
129 efrain 752
                return new JsonModel([
753
                    'success'   => false,
754
                    'data'      => 'ERROR_INVALID_PARAMETER'
755
                ]);
756
            }
17167 ariadna 757
 
129 efrain 758
            $userMapper = UserMapper::getInstance($this->adapter);
759
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 760
 
761
            if (!$user) {
129 efrain 762
                return new JsonModel([
763
                    'success'   => false,
764
                    'data'      => 'ERROR_USER_NOT_FOUND'
765
                ]);
766
            }
17167 ariadna 767
 
768
            if ($user->blocked == User::BLOCKED_NO) {
129 efrain 769
                return new JsonModel([
770
                    'success'   => false,
771
                    'data'      => 'ERROR_USER_IS_NOT_PENDING_FOR_EMAIL_VERIFY'
772
                ]);
773
            }
17167 ariadna 774
 
775
 
776
 
129 efrain 777
            $result = $userMapper->emailVerifyAndActive($user);
17167 ariadna 778
            if ($result) {
129 efrain 779
                $this->logger->info('El usuario : ' . $user->email . ' ha sido desbloqueado ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 780
 
129 efrain 781
                return new JsonModel([
782
                    'success'   => true,
783
                    'data'      => 'LABEL_USER_HAS_BEEN_UNBLOCKED',
784
                ]);
17167 ariadna 785
            } else {
786
 
129 efrain 787
                return new JsonModel([
788
                    'success'   => false,
789
                    'data'      => $userMapper->getError()
790
                ]);
791
            }
792
        }
17167 ariadna 793
 
794
 
795
 
129 efrain 796
        return new JsonModel([
797
            'success' => false,
798
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
799
        ]);
800
    }
17167 ariadna 801
 
1 www 802
    public function changePasswordAction()
803
    {
804
        $currentUserPlugin = $this->plugin('currentUserPlugin');
805
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 806
 
1 www 807
        $request = $this->getRequest();
808
 
17167 ariadna 809
        if ($request->isGet()) {
1 www 810
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 811
            if (!$uuid) {
1 www 812
                return new JsonModel([
813
                    'success'   => false,
814
                    'data'      => 'ERROR_INVALID_PARAMETER'
815
                ]);
816
            }
17167 ariadna 817
 
1 www 818
            $userMapper = UserMapper::getInstance($this->adapter);
819
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 820
 
821
 
822
 
823
            if ($user) {
1 www 824
                return new JsonModel([
825
                    'success'   => true,
826
                    'data'      => [
827
                        'first_name' => $user->first_name,
828
                        'last_name' => $user->last_name,
829
                        'email' => $user->email,
830
                    ]
831
                ]);
832
            } else {
833
                return new JsonModel([
834
                    'success'   => false,
835
                    'data'      => 'ERROR_USER_NOT_FOUND'
836
                ]);
837
            }
838
        }
17167 ariadna 839
 
840
        if ($request->isPost()) {
841
 
1 www 842
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 843
            if (!$uuid) {
1 www 844
                return new JsonModel([
845
                    'success'   => false,
846
                    'data'      => 'ERROR_INVALID_PARAMETER'
847
                ]);
848
            }
17167 ariadna 849
 
1 www 850
            $userMapper = UserMapper::getInstance($this->adapter);
851
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 852
 
853
            if (!$user) {
1 www 854
                return new JsonModel([
855
                    'success'   => false,
856
                    'data'      => 'ERROR_USER_NOT_FOUND'
857
                ]);
858
            }
17167 ariadna 859
 
860
 
1 www 861
            $dataPost = $request->getPost()->toArray();
862
            $form = new ChangePasswordForm();
863
            $form->setData($dataPost);
17167 ariadna 864
 
865
            if ($form->isValid()) {
866
 
867
 
868
 
1 www 869
                $data = (array) $form->getData();
870
                $password = $data['password'];
871
 
17167 ariadna 872
 
873
 
1 www 874
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
875
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
17167 ariadna 876
 
1 www 877
                $oldPassword = false;
17167 ariadna 878
                foreach ($userPasswords as $userPassword) {
879
                    if (password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password)) {
1 www 880
                        $oldPassword = true;
881
                        break;
882
                    }
883
                }
17167 ariadna 884
 
885
                if ($oldPassword) {
1 www 886
                    $this->logger->err('Cambio de contraseña del usuario - error contraseña ya utilizada anteriormente', ['user_id' =>  $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 887
 
1 www 888
                    return new JsonModel([
889
                        'success'   => false,
890
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
17167 ariadna 891
 
1 www 892
                    ]);
893
                } else {
894
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
17167 ariadna 895
 
896
 
1 www 897
                    $result = $userMapper->updatePassword($user, $password_hash);
17167 ariadna 898
                    if ($result) {
1 www 899
                        $this->logger->info('Cambio de contraseña del usuario realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 900
 
901
 
1 www 902
                        return new JsonModel([
903
                            'success'   => true,
904
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
17167 ariadna 905
 
1 www 906
                        ]);
907
                    } else {
908
                        $this->logger->err('Cambio de contraseña del usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 909
 
1 www 910
                        return new JsonModel([
911
                            'success'   => true,
912
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
17167 ariadna 913
 
1 www 914
                        ]);
915
                    }
916
                }
917
            } else {
918
                $messages = [];
17167 ariadna 919
 
1 www 920
                $form_messages = (array) $form->getMessages();
17167 ariadna 921
                foreach ($form_messages  as $fieldname => $field_messages) {
1 www 922
                    $messages[$fieldname] = array_values($field_messages);
923
                }
17167 ariadna 924
 
1 www 925
                return new JsonModel([
926
                    'success'   => false,
927
                    'data'   => $messages
928
                ]);
929
            }
930
        }
17167 ariadna 931
 
932
 
933
 
1 www 934
        return new JsonModel([
935
            'success' => false,
936
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
937
        ]);
938
    }
17167 ariadna 939
 
1 www 940
    public function cancelAction()
941
    {
942
        $currentUserPlugin = $this->plugin('currentUserPlugin');
943
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 944
 
945
        $currentCompany = $currentUserPlugin->getCompany();
946
 
1 www 947
        $request = $this->getRequest();
17167 ariadna 948
 
949
 
950
        if ($request->isPost()) {
951
 
1 www 952
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 953
            if (!$uuid) {
1 www 954
                return new JsonModel([
955
                    'success'   => false,
956
                    'data'      => 'ERROR_INVALID_PARAMETER'
957
                ]);
958
            }
17167 ariadna 959
 
1 www 960
            $userMapper = UserMapper::getInstance($this->adapter);
961
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 962
 
963
            if (!$user) {
1 www 964
                return new JsonModel([
965
                    'success'   => false,
966
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
967
                ]);
968
            }
17167 ariadna 969
 
1 www 970
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
17167 ariadna 971
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
972
 
973
            if (!$companyUser) {
1 www 974
                return new JsonModel([
975
                    'success'   => false,
976
                    'data'      => 'ERROR_USER_NOT_FOUND'
977
                ]);
978
            }
17167 ariadna 979
 
980
 
981
            if (!in_array($companyUser->status, [CompanyUser::STATUS_ADMIN_WILL_ADD, CompanyUser::STATUS_ACCEPTED])) {
1 www 982
                return new JsonModel([
983
                    'success'   => false,
984
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
985
                ]);
986
            }
17167 ariadna 987
 
1 www 988
            $companyUser->status = CompanyUser::STATUS_CANCELLED;
989
            $result = $companyUserMapper->update($companyUser);
17167 ariadna 990
            if ($result) {
1 www 991
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido cancelada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 992
 
1 www 993
                return new JsonModel([
994
                    'success'   => true,
995
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_CANCELLED',
996
                ]);
17167 ariadna 997
            } else {
998
 
1 www 999
                return new JsonModel([
1000
                    'success'   => false,
1001
                    'data'      => $userMapper->getError()
1002
                ]);
1003
            }
1004
        }
17167 ariadna 1005
 
1006
 
1007
 
1 www 1008
        return new JsonModel([
1009
            'success' => false,
1010
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1011
        ]);
1012
    }
17167 ariadna 1013
 
1 www 1014
    public function acceptAction()
1015
    {
1016
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1017
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 1018
 
1 www 1019
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 1020
 
1 www 1021
        $request = $this->getRequest();
17167 ariadna 1022
 
1023
 
1024
        if ($request->isPost()) {
1025
 
1 www 1026
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 1027
            if (!$uuid) {
1 www 1028
                return new JsonModel([
1029
                    'success'   => false,
1030
                    'data'      => 'ERROR_INVALID_PARAMETER'
1031
                ]);
1032
            }
17167 ariadna 1033
 
1 www 1034
            $userMapper = UserMapper::getInstance($this->adapter);
1035
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 1036
 
1037
            if (!$user) {
1 www 1038
                return new JsonModel([
1039
                    'success'   => false,
1040
                    'data'      => 'ERROR_USER_NOT_FOUND'
1041
                ]);
1042
            }
17167 ariadna 1043
 
1 www 1044
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1045
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17167 ariadna 1046
 
1047
            if (!$companyUser) {
1 www 1048
                return new JsonModel([
1049
                    'success'   => false,
1050
                    'data'      => 'ERROR_USER_NOT_FOUND'
1051
                ]);
1052
            }
17167 ariadna 1053
 
1054
            if (
1055
                $companyUser->status != CompanyUser::STATUS_PENDING
1 www 1056
                && $companyUser->status != CompanyUser::STATUS_SENT
1057
                && $companyUser->status != CompanyUser::STATUS_CANCELLED
17167 ariadna 1058
                && $companyUser->status != CompanyUser::STATUS_REJECTED
1059
            ) {
1 www 1060
                return new JsonModel([
1061
                    'success'   => false,
1062
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
1063
                ]);
1064
            }
17167 ariadna 1065
 
1 www 1066
            $companyUser->status = CompanyUser::STATUS_ACCEPTED;
1067
            $result = $companyUserMapper->update($companyUser);
17167 ariadna 1068
            if ($result) {
1 www 1069
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido aceptada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 1070
 
1 www 1071
                return new JsonModel([
1072
                    'success'   => true,
1073
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_ACCEPTED'
1074
                ]);
17167 ariadna 1075
            } else {
1076
 
1 www 1077
                return new JsonModel([
1078
                    'success'   => false,
1079
                    'data'      => $userMapper->getError()
1080
                ]);
1081
            }
1082
        }
17167 ariadna 1083
 
1084
 
1085
 
1 www 1086
        return new JsonModel([
1087
            'success' => false,
1088
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1089
        ]);
1090
    }
17167 ariadna 1091
 
1 www 1092
    public function rejectAction()
1093
    {
1094
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1095
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 1096
 
1 www 1097
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 1098
 
1 www 1099
        $request = $this->getRequest();
17167 ariadna 1100
 
1101
 
1102
        if ($request->isPost()) {
1103
 
1 www 1104
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 1105
            if (!$uuid) {
1 www 1106
                return new JsonModel([
1107
                    'success'   => false,
1108
                    'data'      => 'ERROR_INVALID_PARAMETER'
1109
                ]);
1110
            }
17167 ariadna 1111
 
1 www 1112
            $userMapper = UserMapper::getInstance($this->adapter);
1113
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 1114
 
1115
            if (!$user) {
1 www 1116
                return new JsonModel([
1117
                    'success'   => false,
1118
                    'data'      => 'ERROR_USER_NOT_FOUND'
1119
                ]);
1120
            }
17167 ariadna 1121
 
1 www 1122
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1123
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17167 ariadna 1124
 
1125
            if (!$companyUser) {
1 www 1126
                return new JsonModel([
1127
                    'success'   => false,
1128
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
1129
                ]);
1130
            }
17167 ariadna 1131
 
1132
            if (
1133
                $companyUser->status != CompanyUser::STATUS_PENDING
1134
                && $companyUser->status != CompanyUser::STATUS_SENT
1135
            ) {
1 www 1136
                return new JsonModel([
1137
                    'success'   => false,
1138
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
1139
                ]);
1140
            }
17167 ariadna 1141
 
1 www 1142
            $companyUser->status = CompanyUser::STATUS_REJECTED;
1143
            $result = $companyUserMapper->update($companyUser);
17167 ariadna 1144
            if ($result) {
1 www 1145
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido rechazada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 1146
 
1 www 1147
                return new JsonModel([
1148
                    'success'   => true,
1149
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_REJECTED',
1150
                ]);
17167 ariadna 1151
            } else {
1152
 
1 www 1153
                return new JsonModel([
1154
                    'success'   => false,
1155
                    'data'      => $userMapper->getError()
1156
                ]);
1157
            }
1158
        }
17167 ariadna 1159
 
1160
 
1161
 
1 www 1162
        return new JsonModel([
1163
            'success' => false,
1164
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1165
        ]);
1166
    }
17167 ariadna 1167
 
1 www 1168
    public function inviteAction()
1169
    {
1170
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1171
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 1172
 
1173
 
1174
 
1 www 1175
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 1176
 
1 www 1177
        $request = $this->getRequest();
17167 ariadna 1178
 
1179
        if ($request->isGet()) {
1180
 
1181
            $search = Functions::sanitizeFilterString($this->params()->fromQuery('search'));
1182
            if (strlen($search) >= 3) {
1183
 
1 www 1184
                $userMapper = UserMapper::getInstance($this->adapter);
1185
                $records  = $userMapper->fetchAllSuggestForInvitationByCompanyId($currentCompany->id, $search);
17167 ariadna 1186
 
1187
                $users = [];
1188
                foreach ($records as $record) {
1 www 1189
                    array_push($users, [
17167 ariadna 1190
                        'value' => $record->uuid,
1191
                        'text' => trim($record->first_name . ' ' . $record->last_name) . ' (' . $record->email . ')'
1192
 
1 www 1193
                    ]);
1194
                }
17167 ariadna 1195
 
1 www 1196
                return new JsonModel([
1197
                    'success' => true,
1198
                    'data' => $users
1199
                ]);
1200
            } else {
1201
                return new JsonModel([
1202
                    'success' => true,
17167 ariadna 1203
                    'data' => []
1204
                ]);
1205
            }
1206
        } else if ($request->isPost()) {
1207
 
1 www 1208
            $uuid = $this->params()->fromPost('id');
17167 ariadna 1209
            if (!$uuid) {
1 www 1210
                return new JsonModel([
1211
                    'success'   => false,
1212
                    'data'      => 'ERROR_INVALID_PARAMETER'
1213
                ]);
1214
            }
17167 ariadna 1215
 
1 www 1216
            $userMapper = UserMapper::getInstance($this->adapter);
1217
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 1218
 
1219
            if (!$user) {
1 www 1220
                return new JsonModel([
1221
                    'success'   => false,
1222
                    'data'      => 'ERROR_USER_NOT_FOUND'
1223
                ]);
1224
            }
17167 ariadna 1225
 
1226
            if ($user->status != User::STATUS_ACTIVE) {
1 www 1227
                return new JsonModel([
1228
                    'success'   => false,
1229
                    'data'      => 'ERROR_USER_IS_INACTIVE'
1230
                ]);
1231
            }
17167 ariadna 1232
 
1233
 
1234
 
1235
 
1236
 
1 www 1237
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1238
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17167 ariadna 1239
 
1240
            if ($companyUser && $companyUser->status == CompanyUser::STATUS_ACCEPTED) {
1 www 1241
                return new JsonModel([
1242
                    'success'   => false,
1243
                    'data'      => 'ERROR_USER_COMPANY_FOUND'
1244
                ]);
1245
            }
15351 efrain 1246
            $networkMapper = NetworkMapper::getInstance($this->adapter);
1247
            $network = $networkMapper->fetchOne($currentUser->network_id);
1 www 1248
 
17167 ariadna 1249
 
1250
            if ($companyUser) {
1251
 
1252
 
1253
                if ($network->default == Network::DEFAULT_YES) {
15351 efrain 1254
                    $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1255
                } else {
1256
                    $companyUser->status = CompanyUser::STATUS_ACCEPTED;
1257
                }
1 www 1258
                $result = $companyUserMapper->update($companyUser);
1259
            } else {
15351 efrain 1260
 
17167 ariadna 1261
 
1 www 1262
                $companyUser = new CompanyUser();
1263
                $companyUser->company_id = $currentCompany->id;
1264
                $companyUser->backend = CompanyUser::BACKEND_NO;
1265
                $companyUser->creator = CompanyUser::CREATOR_NO;
1266
                $companyUser->owner = CompanyUser::OWNER_NO;
17167 ariadna 1267
 
1268
                if ($network->default == Network::DEFAULT_YES) {
15351 efrain 1269
                    $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1270
                } else {
1271
                    $companyUser->status = CompanyUser::STATUS_ACCEPTED;
1272
                }
17167 ariadna 1273
 
1274
 
1 www 1275
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1276
                $companyUser->user_id = $user->id;
17167 ariadna 1277
 
1278
 
1279
 
1 www 1280
                $result = $companyUserMapper->insert($companyUser);
1281
            }
1282
 
17167 ariadna 1283
 
1284
 
1285
            if ($result) {
1286
 
1287
 
1 www 1288
                $notification = new Notification();
1289
                $notification->type     = Notification::TYPE_RECEIVE_INVITATION_COMPANY;
1290
                $notification->read     = Notification::NO;
1291
                $notification->user_id  = $user->id;
1292
                $notification->company_id = $currentCompany->id;
1293
                $notification->message  = 'LABEL_NOTIFICATION_RECEIVE_INVITATION_COMPANY';
1294
                $notification->url      = 'company/view/' . $currentCompany->uuid;
17167 ariadna 1295
 
1 www 1296
                $notificationMapper = NotificationMapper::getInstance($this->adapter);
1297
                $notificationMapper->insert($notification);
17167 ariadna 1298
 
1 www 1299
                $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
1300
                $userNotification = $userNotificationMapper->fetchOne($user->id);
17167 ariadna 1301
 
1302
                if ($userNotification && $userNotification->receive_invitation_company) {
1 www 1303
                    $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
15351 efrain 1304
                    $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RECEIVE_INVITATION_COMPANY, $currentUser->network_id);
17167 ariadna 1305
 
1306
                    if ($emailTemplate) {
1307
                        $company_profile_url = 'https://' . $network->main_hostname . '/company/view/' . $currentCompany->uuid;
1308
 
1309
 
1 www 1310
                        $arrayCont = [
1311
                            'firstname'             => $currentUser->first_name,
1312
                            'lastname'              => $currentUser->last_name,
1313
                            'other_user_firstname'  => $user->first_name,
1314
                            'other_user_lastname'   => $user->last_name,
1315
                            'company_name'          => $currentCompany->name,
1316
                            'group_name'            => '',
1317
                            'content'               => '',
1318
                            'code'                  => '',
1319
                            'link'                  => $company_profile_url,
1320
                        ];
17167 ariadna 1321
 
1 www 1322
                        $email = new QueueEmail($this->adapter);
1323
                        $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1324
                    }
1325
                }
17167 ariadna 1326
 
1327
 
1 www 1328
                $this->logger->info('La empresa : ' . $currentCompany->name . ' envio al usuario : ' . $user->email . ' una invitación ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 1329
 
1330
                if ($network->default == Network::DEFAULT_YES) {
15351 efrain 1331
                    return new JsonModel([
1332
                        'success'   => true,
1333
                        'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_CREATED',
1334
                    ]);
1335
                } else {
1336
                    return new JsonModel([
1337
                        'success'   => true,
1338
                        'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_INVITED_SENT',
1339
                    ]);
1340
                }
17167 ariadna 1341
            } else {
1342
 
1 www 1343
                return new JsonModel([
1344
                    'success'   => false,
1345
                    'data'      => $userMapper->getError()
1346
                ]);
1347
            }
1348
        }
17167 ariadna 1349
 
1350
 
1351
 
1 www 1352
        return new JsonModel([
1353
            'success' => false,
1354
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1355
        ]);
1356
    }
17167 ariadna 1357
 
1358
 
1 www 1359
    public function deleteAction()
1360
    {
1361
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1362
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 1363
 
1 www 1364
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 1365
 
1 www 1366
        $request = $this->getRequest();
17167 ariadna 1367
 
1368
 
1369
        if ($request->isPost()) {
1370
 
1 www 1371
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 1372
            if (!$uuid) {
1 www 1373
                return new JsonModel([
1374
                    'success'   => false,
1375
                    'data'      => 'ERROR_INVALID_PARAMETER'
1376
                ]);
1377
            }
17167 ariadna 1378
 
1 www 1379
            $userMapper = UserMapper::getInstance($this->adapter);
1380
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 1381
 
1382
            if (!$user) {
1 www 1383
                return new JsonModel([
1384
                    'success'   => false,
1385
                    'data'      => 'ERROR_USER_NOT_FOUND'
17167 ariadna 1386
 
1 www 1387
                ]);
1388
            }
17167 ariadna 1389
 
1 www 1390
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1391
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17167 ariadna 1392
 
1393
            if ($companyUser) {
1 www 1394
                return new JsonModel([
1395
                    'success'   => false,
1396
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
1397
                ]);
1398
            }
17167 ariadna 1399
 
1400
 
1401
            if (!$currentCompany->internal) {
1 www 1402
                return new JsonModel([
1403
                    'success'   => false,
1404
                    'data'      => 'ERROR_INTERNAL_COMPANY_ONLY'
1405
                ]);
1406
            }
1407
 
1408
 
17167 ariadna 1409
 
1 www 1410
            $result = $companyUserMapper->delete($companyUser->id);
17167 ariadna 1411
            if ($result) {
1 www 1412
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido eliminada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 1413
 
1 www 1414
                return new JsonModel([
1415
                    'success'   => true,
1416
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_DELETED',
1417
                ]);
17167 ariadna 1418
            } else {
1419
 
1 www 1420
                return new JsonModel([
1421
                    'success'   => false,
1422
                    'data'      => $userMapper->getError()
1423
                ]);
1424
            }
1425
        }
17167 ariadna 1426
 
1427
 
1428
 
1 www 1429
        return new JsonModel([
1430
            'success' => false,
1431
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1432
        ]);
1433
    }
17167 ariadna 1434
 
1435
 
1 www 1436
    public function uploadAction()
1437
    {
1438
        $request = $this->getRequest();
17167 ariadna 1439
 
15459 efrain 1440
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1441
        $currentNetwork    = $currentNetworkPlugin->getNetwork();
17167 ariadna 1442
 
1 www 1443
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1444
        $currentUser    = $currentUserPlugin->getUser();
1445
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 1446
 
1 www 1447
        $request    = $this->getRequest();
1448
 
17167 ariadna 1449
        if ($request->isPost()) {
1450
 
16766 efrain 1451
            $step = Functions::sanitizeFilterString($this->params()->fromPost('step'));
17167 ariadna 1452
            if ($step == 'validation') {
1 www 1453
                $userMapper = UserMapper::getInstance($this->adapter);
1454
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
17167 ariadna 1455
 
1 www 1456
                $form = new  UserUploadForm();
1457
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
17167 ariadna 1458
 
1 www 1459
                $form->setData($dataPost);
17167 ariadna 1460
 
1461
                if ($form->isValid()) {
1462
 
1 www 1463
                    $file = $_FILES['file'];
1464
                    $tmp_filename = $file['tmp_name'];
1465
                    $final_filename =  'data/' . $file['name'];
17167 ariadna 1466
 
1467
                    if (!move_uploaded_file($tmp_filename, $final_filename)) {
1 www 1468
                        return new JsonModel([
1469
                            'success' => false,
1470
                            'data' => 'ERROR_UPLOAD_FILE'
1471
                        ]);
1472
                    }
17167 ariadna 1473
 
1474
 
1 www 1475
                    $users = [];
17167 ariadna 1476
 
1477
 
1 www 1478
                    $spreadsheet = IOFactory::load($final_filename);
1479
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
17167 ariadna 1480
 
1 www 1481
                    $emails = [];
17167 ariadna 1482
 
1483
                    foreach ($records as $record) {
1 www 1484
                        //A = Nombre 	B = Apellidos	C = Email 	D = contraseña
17167 ariadna 1485
 
1486
 
16766 efrain 1487
                        $first_name = Functions::sanitizeFilterString($record['A']);
1488
                        $last_name = Functions::sanitizeFilterString($record['B']);
15460 efrain 1489
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));
17167 ariadna 1490
 
16766 efrain 1491
                        $password = Functions::sanitizeFilterString($record['D']);
1492
                        $isAdult = strtolower(Functions::sanitizeFilterString($record['E']));
1493
                        $country = strtolower(Functions::sanitizeFilterString($record['F']));
15460 efrain 1494
 
17167 ariadna 1495
 
1496
                        if (empty($first_name) || empty($last_name) || !filter_var($email, FILTER_VALIDATE_EMAIL) ||  empty($password)) {
1 www 1497
                            continue;
1498
                        }
17167 ariadna 1499
 
1500
                        if (!in_array($email, $emails)) {
1501
 
1 www 1502
                            $user = $userMapper->fetchOneByEmail($email);
17167 ariadna 1503
 
1 www 1504
                            array_push($emails, $email);
1505
                            array_push($users, [
1506
                                'first_name' => $first_name,
1507
                                'last_name' => $last_name,
1508
                                'password'  => $password,
1509
                                'email' => $email,
15460 efrain 1510
                                'is_adult' => $isAdult,
1511
                                'country' => $country,
1512
 
1 www 1513
                            ]);
1514
                        }
1515
                    }
17167 ariadna 1516
 
1 www 1517
                    $key = md5($currentUser->id . '-' . microtime(true));
1518
                    $this->cache->setItem($key, serialize($users));
17167 ariadna 1519
 
1 www 1520
                    return new JsonModel([
1521
                        'success' => true,
1522
                        'data' => [
1523
                            'key' => $key,
1524
                            'items' => $users,
1525
                        ]
1526
                    ]);
17167 ariadna 1527
 
16954 efrain 1528
                    @unlink($final_filename);
1 www 1529
                } else {
1530
                    $messages = [];
1531
                    $form_messages = (array) $form->getMessages();
17167 ariadna 1532
                    foreach ($form_messages  as $fieldname => $field_messages) {
1533
 
1 www 1534
                        $messages[$fieldname] = array_values($field_messages);
1535
                    }
17167 ariadna 1536
 
1 www 1537
                    return new JsonModel([
1538
                        'success'   => false,
1539
                        'data'   => $messages
1540
                    ]);
1541
                }
17167 ariadna 1542
            } else if ($step == 'process') {
1543
 
16766 efrain 1544
                $key = Functions::sanitizeFilterString($this->params()->fromPost('key'));
17167 ariadna 1545
                if (!$key) {
1 www 1546
                    return new JsonModel([
1547
                        'success' => false,
1548
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
1549
                    ]);
1550
                }
17167 ariadna 1551
 
1 www 1552
                $value = $this->cache->getItem($key);
17167 ariadna 1553
                if (!$value) {
1554
 
1 www 1555
                    return new JsonModel([
1556
                        'success' => false,
1557
                        'data' => 'ERROR_CACHE_NOT_FOUND'
1558
                    ]);
1559
                }
17167 ariadna 1560
 
1 www 1561
                $records = unserialize($value);
17167 ariadna 1562
                if (!$records) {
1 www 1563
                    return new JsonModel([
1564
                        'success' => false,
1565
                        'data' => 'ERROR_CACHE_INVALID'
1566
                    ]);
1567
                }
17167 ariadna 1568
 
15460 efrain 1569
                $locationMapper = LocationMapper::getInstance($this->adapter);
1570
                $countryMapper = CountryMapper::getInstance($this->adapter);
17167 ariadna 1571
 
1572
 
15460 efrain 1573
                $networkMapper = NetworkMapper::getInstance($this->adapter);
1574
                $networkDefault = $networkMapper->fetchOneByDefault();
17167 ariadna 1575
 
1 www 1576
                $userMapper = UserMapper::getInstance($this->adapter);
1577
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1578
 
17167 ariadna 1579
 
15460 efrain 1580
                $user_ids_in_default_network = [];
17167 ariadna 1581
 
1582
 
1 www 1583
                $users_created = 0;
1584
                $user_ids = [];
17167 ariadna 1585
                foreach ($records as $record) {
1 www 1586
                    $first_name = $record['first_name'];
1587
                    $last_name = $record['last_name'];
1588
                    $password = $record['password'];
1589
                    $email = $record['email'];
17167 ariadna 1590
 
1591
 
16286 efrain 1592
                    $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
17167 ariadna 1593
                    if (!$user) {
1 www 1594
                        $password_hash = password_hash($password, PASSWORD_DEFAULT);
17167 ariadna 1595
 
1 www 1596
                        $user = new User();
15459 efrain 1597
                        $user->network_id = $currentNetwork->id;
1 www 1598
                        $user->blocked = User::BLOCKED_NO;
1599
                        $user->email_verified = User::EMAIL_VERIFIED_YES;
1600
                        $user->email = $email;
1601
                        $user->first_name = $first_name;
1602
                        $user->last_name = $last_name;
1603
                        $user->password = $password_hash;
1604
                        $user->login_attempt = 0;
1605
                        $user->usertype_id = UserType::USER;
1606
                        $user->status = User::STATUS_ACTIVE;
15460 efrain 1607
                        $user->is_adult = $record['is_adult'] == 'y' ? User::IS_ADULT_YES : User::IS_ADULT_NO;
17167 ariadna 1608
 
1 www 1609
                        $result = $userMapper->insert($user);
17167 ariadna 1610
                        if ($result) {
15460 efrain 1611
                            $users_created++;
17167 ariadna 1612
 
16286 efrain 1613
                            $country_code = trim($record['country']);
17167 ariadna 1614
 
1615
                            if ($country_code) {
16286 efrain 1616
                                $country = $countryMapper->fetchOneByCodeOrCountry($record['country']);
17167 ariadna 1617
                                if ($country) {
1618
 
16286 efrain 1619
                                    $location = new Location();
1620
                                    $location->formatted_address = $country->country;
1621
                                    $location->country = $country->country;
17167 ariadna 1622
                                    if ($locationMapper->insert($location)) {
1623
 
16286 efrain 1624
                                        $user->location_id = $location->id;
1625
                                        $userMapper->updateLocation($user);
1626
                                    }
15460 efrain 1627
                                }
16286 efrain 1628
                            } else {
1629
                                $country_code = '';
15460 efrain 1630
                            }
17167 ariadna 1631
 
1 www 1632
                            $userPassword = new UserPassword();
1633
                            $userPassword->user_id = $user->id;
1634
                            $userPassword->password = $password_hash;
1635
                            $userPasswordMapper->insert($userPassword);
17167 ariadna 1636
 
1637
 
1638
                            if ($currentNetwork->default == Network::DEFAULT_YES) {
15460 efrain 1639
                                array_push($user_ids_in_default_network, $user->id);
1640
                            } else {
17167 ariadna 1641
 
1642
 
1643
 
1644
                                if ($user->is_adult == User::IS_ADULT_YES) {
1645
 
15460 efrain 1646
                                    $userInDefaultNetwork = $userMapper->fetchOneByEmailAndNetworkId($user->email, $networkDefault->id);
17167 ariadna 1647
                                    if ($userInDefaultNetwork) {
1648
 
15460 efrain 1649
                                        array_push($user_ids_in_default_network, $userInDefaultNetwork->id);
17167 ariadna 1650
 
1651
                                        if ($userInDefaultNetwork->email_verified == User::EMAIL_VERIFIED_NO || $userInDefaultNetwork->status != User::STATUS_ACTIVE) {
15460 efrain 1652
                                            $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
1653
                                            $userInDefaultNetwork->status != User::STATUS_ACTIVE;
17167 ariadna 1654
 
1655
                                            if (!$userMapper->update($userInDefaultNetwork)) {
15460 efrain 1656
                                                continue;
1657
                                            }
1658
                                        }
1659
                                    } else {
1660
                                        $userInDefaultNetwork = new User();
1661
                                        $userInDefaultNetwork->network_id = $networkDefault->id;
1662
                                        $userInDefaultNetwork->blocked = User::BLOCKED_NO;
1663
                                        $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
1664
                                        $userInDefaultNetwork->email = $email;
1665
                                        $userInDefaultNetwork->first_name = $first_name;
1666
                                        $userInDefaultNetwork->last_name = $last_name;
1667
                                        $userInDefaultNetwork->password = $password_hash;
1668
                                        $userInDefaultNetwork->login_attempt = 0;
1669
                                        $userInDefaultNetwork->usertype_id = UserType::USER;
1670
                                        $userInDefaultNetwork->status = User::STATUS_ACTIVE;
1671
                                        $userInDefaultNetwork->is_adult = User::IS_ADULT_YES;
1672
                                        $result = $userMapper->insert($userInDefaultNetwork);
17167 ariadna 1673
                                        if ($result) {
15460 efrain 1674
                                            array_push($user_ids_in_default_network, $userInDefaultNetwork->id);
17167 ariadna 1675
 
1676
                                            if ($country) {
1677
 
15460 efrain 1678
                                                $location = new Location();
1679
                                                $location->formatted_address = $country->country;
1680
                                                $location->country = $country->country;
17167 ariadna 1681
                                                if ($locationMapper->insert($location)) {
1682
 
15460 efrain 1683
                                                    $userInDefaultNetwork->location_id = $location->id;
1684
                                                    $userMapper->updateLocation($userInDefaultNetwork);
1685
                                                }
1686
                                            }
17167 ariadna 1687
 
1688
 
15460 efrain 1689
                                            $userPassword = new UserPassword();
1690
                                            $userPassword->user_id = $userInDefaultNetwork->id;
1691
                                            $userPassword->password = $password_hash;
1692
                                            $userPasswordMapper->insert($userPassword);
1693
                                        }
1694
                                    }
1695
                                }
1696
                            }
1 www 1697
                        } else {
1698
                            continue;
1699
                        }
129 efrain 1700
                    } else {
17167 ariadna 1701
                        if ($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
129 efrain 1702
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
1703
                            $user->status != User::STATUS_ACTIVE;
17167 ariadna 1704
 
1705
                            if (!$userMapper->update($user)) {
129 efrain 1706
                                continue;
1707
                            }
1708
                        }
1 www 1709
                    }
17167 ariadna 1710
 
15460 efrain 1711
                    array_push($user_ids, $user->id);
1712
                }
17167 ariadna 1713
 
1714
                if ($currentCompany) {
1715
 
15460 efrain 1716
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
17167 ariadna 1717
 
15460 efrain 1718
                    $company_users_created = 0;
17167 ariadna 1719
 
1720
                    foreach ($user_ids as $user_id) {
15460 efrain 1721
                        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user_id);
17167 ariadna 1722
                        if (!$companyUser) {
1723
 
1724
                            $companyUser = new CompanyUser();
1725
                            $companyUser->company_id = $currentCompany->id;
1726
                            $companyUser->user_id = $user_id;
15460 efrain 1727
                            $companyUser->backend = CompanyUser::BACKEND_NO;
1728
                            $companyUser->creator = CompanyUser::CREATOR_NO;
17167 ariadna 1729
                            $companyUser->owner = CompanyUser::OWNER_NO;
1730
 
1731
                            if ($currentNetwork->default == Network::DEFAULT_YES) {
15460 efrain 1732
                                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1733
                            } else {
1734
                                $companyUser->status = CompanyUser::STATUS_ACCEPTED;
1735
                            }
17167 ariadna 1736
 
1737
                            if ($companyUserMapper->insert($companyUser)) {
15460 efrain 1738
                                $company_users_created++;
1739
                            }
1740
                        }
1 www 1741
                    }
17167 ariadna 1742
 
15460 efrain 1743
                    $this->logger->info('Se agregaron ' . $users_created . '  usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1744
                } else {
17167 ariadna 1745
 
15460 efrain 1746
                    $this->logger->info('Se agregaron ' . $users_created . ' usuarios a la red', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 www 1747
                }
17167 ariadna 1748
 
1749
                if ($user_ids_in_default_network) {
15460 efrain 1750
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
1751
                    $companyToFollower = $companyMapper->fetchOneDefaultForFollowers();
17167 ariadna 1752
 
15460 efrain 1753
                    $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
17167 ariadna 1754
 
15460 efrain 1755
                    $userToConnection = $userMapper->fetchOneDefaultForConnection();
17167 ariadna 1756
 
1757
 
15460 efrain 1758
                    $connectionMapper = ConnectionMapper::getInstance($this->adapter);
17167 ariadna 1759
 
1760
                    foreach ($user_ids_in_default_network as $user_id) {
1761
                        if ($userToConnection) {
15460 efrain 1762
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user_id, $userToConnection->id);
17167 ariadna 1763
                            if (!$connection) {
15460 efrain 1764
                                $connection = new Connection();
1765
                                $connection->request_from = $user_id;
1766
                                $connection->request_to = $userToConnection->id;
1767
                                $connection->status = Connection::STATUS_ACCEPTED;
17167 ariadna 1768
 
15460 efrain 1769
                                $connectionMapper->insert($connection);
1770
                            } else {
17167 ariadna 1771
                                if ($connection->status == Connection::STATUS_SENT) {
15460 efrain 1772
                                    $connectionMapper->approve($connection);
1773
                                }
1774
                            }
1775
                        }
17167 ariadna 1776
 
1777
                        if ($companyToFollower) {
15460 efrain 1778
                            $companyFollower = $companyFollowerMapper->fetchOneByCompanyIdAndUserId($companyToFollower->id, $user_id);
17167 ariadna 1779
                            if (!$companyFollower) {
15460 efrain 1780
                                $companyFollower = new CompanyFollower();
17167 ariadna 1781
                                $companyFollower->company_id = $companyToFollower->id;
15460 efrain 1782
                                $companyFollower->follower_id = $user_id;
17167 ariadna 1783
 
15460 efrain 1784
                                $companyFollowerMapper->insert($companyFollower);
1785
                            }
1 www 1786
                        }
1787
                    }
1788
                }
17167 ariadna 1789
 
1790
 
1791
 
1 www 1792
                return new JsonModel([
1793
                    'success' => true,
1794
                    'data' => [
1795
                        'users_created' => $users_created
1796
                    ]
1797
                ]);
1798
            } else {
1799
                return new JsonModel([
1800
                    'success' => false,
1801
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1802
                ]);
1803
            }
1804
        }
17167 ariadna 1805
 
1 www 1806
        return new JsonModel([
1807
            'success' => false,
1808
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1809
        ]);
1810
    }
17167 ariadna 1811
 
1812
 
1 www 1813
    public function editAction()
1814
    {
1815
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1816
        $currentUser = $currentUserPlugin->getUser();
1817
        $currentCompany = $currentUserPlugin->getCompany();
17167 ariadna 1818
 
1 www 1819
        $request = $this->getRequest();
1820
        $uuid = $this->params()->fromRoute('id');
17167 ariadna 1821
 
1822
 
1823
        if (!$uuid) {
1 www 1824
            $data = [
1825
                'success'   => false,
1826
                'data'   => 'ERROR_INVALID_PARAMETER'
1827
            ];
17167 ariadna 1828
 
1 www 1829
            return new JsonModel($data);
1830
        }
17167 ariadna 1831
 
1 www 1832
        $userMapper = UserMapper::getInstance($this->adapter);
1833
        $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 1834
        if (!$user) {
1 www 1835
            $data = [
1836
                'success'   => false,
1837
                'data'   => 'ERROR_COMPANY_NOT_FOUND'
1838
            ];
17167 ariadna 1839
 
1 www 1840
            return new JsonModel($data);
1841
        }
17167 ariadna 1842
 
1 www 1843
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1844
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17167 ariadna 1845
        if (!$companyUser) {
1 www 1846
            return new JsonModel([
1847
                'success'   => false,
1848
                'data'   => 'ERROR_COMPANY_USER_NOT_FOUND'
1849
            ]);
1850
        }
17167 ariadna 1851
 
1852
        if ($companyUser->status != CompanyUser::STATUS_ACCEPTED && $companyUser->status != CompanyUser::STATUS_ADMIN_WILL_ADD) {
1 www 1853
            return new JsonModel([
1854
                'success'   => false,
1855
                'data'   => 'ERROR_COMPANY_USER_IS_NOT_ACTIVE'
1856
            ]);
1857
        }
17167 ariadna 1858
 
1859
 
1860
 
1861
 
1862
        if ($request->isPost()) {
1863
 
1 www 1864
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1865
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1866
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
17167 ariadna 1867
 
1868
            $backend = Functions::sanitizeFilterString($this->params()->fromPost('backend'));
1869
            $companyUser->backend = $backend == CompanyUser::BACKEND_YES ? CompanyUser::BACKEND_YES : CompanyUser::BACKEND_NO;
1 www 1870
            $companyUserMapper->update($companyUser);
17167 ariadna 1871
 
1872
 
1 www 1873
            $roleMapper = RoleMapper::getInstance($this->adapter);
1874
            $roles = $roleMapper->fetchAll();
17167 ariadna 1875
 
1876
 
1877
            foreach ($roles as $role) {
1 www 1878
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $role->id);
17167 ariadna 1879
                if (!$companyRole) {
1880
                    $companyUserRoleMapper->deleteByCompanyIdAndRoleId($currentCompany->id, $role->id);
1 www 1881
                    continue;
17167 ariadna 1882
                }
1883
 
1884
                $checked     = filter_var($this->params()->fromPost('checked' . $role->id), FILTER_SANITIZE_NUMBER_INT);
1885
 
1886
 
1887
 
1888
                if ($checked) {
1889
 
1 www 1890
                    $companyUserRole = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
17167 ariadna 1891
                    if (!$companyUserRole) {
1892
 
1893
                        $companyUserRole = new CompanyUserRole();
1 www 1894
                        $companyUserRole->company_id = $currentCompany->id;
1895
                        $companyUserRole->role_id = $role->id;
1896
                        $companyUserRole->user_id = $user->id;
17167 ariadna 1897
 
1 www 1898
                        $companyUserRoleMapper->insert($companyUserRole);
1899
                    }
1900
                } else {
17167 ariadna 1901
 
1 www 1902
                    $companyUserRoleMapper->deleteByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
17167 ariadna 1903
                }
1 www 1904
            }
17167 ariadna 1905
 
1 www 1906
            $this->logger->info('Se actualizo los roles del usuario : ' . $user->email . ' en la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 1907
 
1 www 1908
            return new JsonModel([
1909
                'success' => true,
1910
                'data' => 'LABEL_RECORD_UPDATED'
1911
            ]);
1912
        } else if ($request->isGet()) {
1913
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
17167 ariadna 1914
 
1 www 1915
            $roleMapper = RoleMapper::getInstance($this->adapter);
1916
            $records = $roleMapper->fetchAll();
4 efrain 1917
 
17167 ariadna 1918
 
1919
 
1 www 1920
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1921
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
17167 ariadna 1922
 
1 www 1923
            $roles = [];
17167 ariadna 1924
            foreach ($records as $record) {
1925
                if ($record->creator == Role::CREATOR_YES) {
1 www 1926
                    continue;
1927
                }
17167 ariadna 1928
 
1929
                if ($record->service_id) {
1 www 1930
                    $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($currentCompany->id, $record->service_id);
17167 ariadna 1931
                    if (!$companyService || $companyService->status == CompanyService::INACTIVE) {
1 www 1932
                        continue;
1933
                    }
1934
                }
17167 ariadna 1935
 
1936
 
1937
 
1 www 1938
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $record->id);
17167 ariadna 1939
                if (!$companyRole) {
1 www 1940
                    continue;
1941
                }
17167 ariadna 1942
 
1 www 1943
                $companyUserRole  = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $record->id);
17167 ariadna 1944
 
1945
 
1946
                $roles[$record->id] = [
1 www 1947
                    'id' => $record->id,
1948
                    'name' => $record->name,
1949
                    'fixed' => $record->creator == Role::CREATOR_YES ? true : false,
1950
                    'checked' => $companyUserRole ? true : false,
1951
                ];
1952
            }
1953
 
17167 ariadna 1954
 
1955
 
1 www 1956
            $data = [
1957
                'success' => true,
1958
                'data' => [
17167 ariadna 1959
                    'backend' => $companyUser->backend == CompanyUser::BACKEND_YES ? 1 : 0,
1960
                    'roles' => $roles,
1961
                ],
1 www 1962
            ];
17167 ariadna 1963
 
1964
 
1965
 
1 www 1966
            return new JsonModel($data);
1967
        } else {
1968
            $data = [
1969
                'success' => false,
1970
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1971
            ];
17167 ariadna 1972
 
1 www 1973
            return new JsonModel($data);
1974
        }
17167 ariadna 1975
 
1 www 1976
        return new JsonModel($data);
1977
    }
17167 ariadna 1978
 
1979
 
17172 ariadna 1980
    /**
17174 ariadna 1981
     * Handles the change of user type.
17172 ariadna 1982
     *
1983
     * This action supports both GET and POST requests:
17174 ariadna 1984
     * - GET: Retrieves the current user type for a given user UUID.
1985
     * - POST: Updates the user type based on the provided data.
17172 ariadna 1986
     *
1987
     * @return JsonModel
1988
     */
17174 ariadna 1989
    public function changeTypeAction()
16248 efrain 1990
    {
17172 ariadna 1991
        // Retrieve the current user and request objects
16248 efrain 1992
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1993
        $currentUser = $currentUserPlugin->getUser();
17167 ariadna 1994
 
16248 efrain 1995
        $request = $this->getRequest();
17167 ariadna 1996
 
17174 ariadna 1997
        // Handle GET request to fetch current user type and additional fields
17167 ariadna 1998
        if ($request->isGet()) {
16248 efrain 1999
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 2000
            if (!$uuid) {
16248 efrain 2001
                return new JsonModel([
2002
                    'success'   => false,
2003
                    'data'      => 'ERROR_INVALID_PARAMETER'
2004
                ]);
2005
            }
17167 ariadna 2006
 
16248 efrain 2007
            $userMapper = UserMapper::getInstance($this->adapter);
2008
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 2009
 
2010
            if ($user) {
16248 efrain 2011
                return new JsonModel([
2012
                    'success'   => true,
2013
                    'data'      => [
2014
                        'usertype_id' => $user->usertype_id,
17179 ariadna 2015
                        'email_verified' => $user->email_verified,
2016
                        'blocked' => $user->blocked,
17172 ariadna 2017
                        'status' => $user->status,
16248 efrain 2018
                    ]
2019
                ]);
2020
            } else {
2021
                return new JsonModel([
2022
                    'success'   => false,
2023
                    'data'      => 'ERROR_USER_NOT_FOUND'
2024
                ]);
2025
            }
2026
        }
17167 ariadna 2027
 
17174 ariadna 2028
        // Handle POST request to update user type and additional fields
17167 ariadna 2029
        if ($request->isPost()) {
16248 efrain 2030
            $uuid = $this->params()->fromRoute('id');
17167 ariadna 2031
            if (!$uuid) {
16248 efrain 2032
                return new JsonModel([
2033
                    'success'   => false,
2034
                    'data'      => 'ERROR_INVALID_PARAMETER'
2035
                ]);
2036
            }
17167 ariadna 2037
 
16248 efrain 2038
            $userMapper = UserMapper::getInstance($this->adapter);
2039
            $user = $userMapper->fetchOneByUuid($uuid);
17167 ariadna 2040
 
2041
            if (!$user) {
16248 efrain 2042
                return new JsonModel([
2043
                    'success'   => false,
2044
                    'data'      => 'ERROR_USER_NOT_FOUND'
2045
                ]);
2046
            }
17167 ariadna 2047
 
17172 ariadna 2048
            // Validate and process form data
16248 efrain 2049
            $dataPost = $request->getPost()->toArray();
17174 ariadna 2050
            $form = new ChangeTypeForm();
16248 efrain 2051
            $form->setData($dataPost);
17167 ariadna 2052
 
2053
            if ($form->isValid()) {
16248 efrain 2054
                $dataPost = (array) $form->getData();
17167 ariadna 2055
 
17174 ariadna 2056
                // Update the user type and additional fields in the database
17213 ariadna 2057
                $result = $userMapper->updateUserFieldsAdmin($user, $dataPost['email_verified'], $dataPost['blocked'], $dataPost['status'], $dataPost['usertype_id']);
17172 ariadna 2058
 
17167 ariadna 2059
                if ($result) {
17174 ariadna 2060
                    $this->logger->info('Cambio del tipo de usuario y otros campos realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 2061
 
16248 efrain 2062
                    return new JsonModel([
2063
                        'success'   => true,
17174 ariadna 2064
                        'data'      => 'LABEL_USER_CHANGE_TYPE_HAS_BEEN_UPDATED'
16248 efrain 2065
                    ]);
2066
                } else {
17174 ariadna 2067
                    $this->logger->err('Cambio del tipo de usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17167 ariadna 2068
 
16248 efrain 2069
                    return new JsonModel([
17174 ariadna 2070
                        'success'   => true,
16248 efrain 2071
                        'data'      => 'ERROR_THERE_WAS_AN_ERROR'
2072
                    ]);
2073
                }
2074
            } else {
17172 ariadna 2075
                // Handle form validation errors
16248 efrain 2076
                $messages = [];
17167 ariadna 2077
 
16248 efrain 2078
                $form_messages = (array) $form->getMessages();
17167 ariadna 2079
                foreach ($form_messages  as $fieldname => $field_messages) {
16248 efrain 2080
                    $messages[$fieldname] = array_values($field_messages);
2081
                }
17167 ariadna 2082
 
16248 efrain 2083
                return new JsonModel([
2084
                    'success'   => false,
2085
                    'data'   => $messages
2086
                ]);
2087
            }
2088
        }
17167 ariadna 2089
 
17172 ariadna 2090
        // Return error for unsupported request methods
16248 efrain 2091
        return new JsonModel([
2092
            'success' => false,
2093
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2094
        ]);
2095
    }
1 www 2096
}