Proyectos de Subversion LeadersLinked - Services

Rev

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

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
/**
4
 *
5
 * Controlador: Mis Perfiles
6
 *
7
 */
8
 
9
declare(strict_types=1);
10
 
11
namespace LeadersLinked\Controller;
12
 
13
use Laminas\Db\Adapter\AdapterInterface;
14
 
15
use Laminas\Mvc\Controller\AbstractActionController;
16
use Laminas\Log\LoggerInterface;
17
use Laminas\View\Model\ViewModel;
18
use Laminas\View\Model\JsonModel;
19
 
20
use LeadersLinked\Form\UserProfile\SkillForm;
21
use LeadersLinked\Form\UserProfile\LanguageForm;
22
 
23
use LeadersLinked\Library\Functions;
24
use LeadersLinked\Mapper\UserProfileMapper;
25
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
26
use LeadersLinked\Model\UserProfile;
27
use LeadersLinked\Mapper\CompanyFollowerMapper;
28
use LeadersLinked\Mapper\LocationMapper;
29
use LeadersLinked\Model\UserLanguage;
30
use LeadersLinked\Mapper\UserLanguageMapper;
31
use LeadersLinked\Mapper\UserSkillMapper;
32
 
33
use LeadersLinked\Model\UserSkill;
34
use LeadersLinked\Mapper\UserMapper;
35
use LeadersLinked\Form\UserProfile\ExtendedForm;
36
use LeadersLinked\Form\UserProfile\LocationForm;
37
use LeadersLinked\Model\Location;
38
use LeadersLinked\Form\UserProfile\SocialNetworkForm;
39
use LeadersLinked\Form\UserProfile\EducationForm;
40
use LeadersLinked\Model\UserEducation;
41
use LeadersLinked\Mapper\UserEducationMapper;
42
use LeadersLinked\Mapper\DegreeMapper;
43
use LeadersLinked\Form\UserProfile\ExperienceForm;
44
use LeadersLinked\Mapper\AptitudeMapper;
45
use LeadersLinked\Mapper\LanguageMapper;
46
use LeadersLinked\Mapper\UserAptitudeMapper;
47
use LeadersLinked\Mapper\UserExperienceMapper;
48
use LeadersLinked\Mapper\IndustryMapper;
49
use LeadersLinked\Mapper\CompanySizeMapper;
50
use LeadersLinked\Model\UserExperience;
51
use LeadersLinked\Mapper\ConnectionMapper;
52
use LeadersLinked\Form\UserProfile\ImageForm;
53
use LeadersLinked\Form\UserProfile\CoverForm;
54
use LeadersLinked\Mapper\SkillMapper;
55
use LeadersLinked\Form\MyProfiles\CreateForm;
56
use LeadersLinked\Form\UserProfile\AptitudeForm;
57
use LeadersLinked\Model\UserAptitude;
58
use LeadersLinked\Form\UserProfile\HobbyAndInterestForm;
59
use LeadersLinked\Mapper\HobbyAndInterestMapper;
60
use LeadersLinked\Mapper\UserHobbyAndInterestMapper;
61
use LeadersLinked\Model\UserHobbyAndInterest;
283 www 62
use LeadersLinked\Library\Storage;
1 efrain 63
 
64
 
65
class MyProfilesController extends AbstractActionController
66
{
67
    /**
68
     *
69
     * @var \Laminas\Db\Adapter\AdapterInterface
70
     */
71
    private $adapter;
596 ariadna 72
 
1 efrain 73
    /**
74
     *
75
     * @var \LeadersLinked\Cache\CacheInterface
76
     */
77
    private $cache;
596 ariadna 78
 
79
 
1 efrain 80
    /**
81
     *
82
     * @var \Laminas\Log\LoggerInterface
83
     */
84
    private $logger;
596 ariadna 85
 
1 efrain 86
    /**
87
     *
88
     * @var array
89
     */
90
    private $config;
596 ariadna 91
 
92
 
1 efrain 93
    /**
94
     *
95
     * @var \Laminas\Mvc\I18n\Translator
96
     */
97
    private $translator;
596 ariadna 98
 
99
 
1 efrain 100
    /**
101
     *
102
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
103
     * @param \LeadersLinked\Cache\CacheInterface $cache
104
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
105
     * @param array $config
106
     * @param \Laminas\Mvc\I18n\Translator $translator
107
     */
108
    public function __construct($adapter, $cache, $logger, $config, $translator)
109
    {
110
        $this->adapter      = $adapter;
111
        $this->cache        = $cache;
112
        $this->logger       = $logger;
113
        $this->config       = $config;
114
        $this->translator   = $translator;
115
    }
116
 
117
    /**
118
     *
119
     * Generación del listado de perfiles
120
     * {@inheritDoc}
121
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
122
     */
123
    public function indexAction()
124
    {
596 ariadna 125
        // Obtener el usuario actual del sistema
1 efrain 126
        $currentUserPlugin = $this->plugin('currentUserPlugin');
127
        $currentUser = $currentUserPlugin->getUser();
128
 
596 ariadna 129
        // Obtener la petición HTTP
1 efrain 130
        $request = $this->getRequest();
131
        if ($request->isGet()) {
596 ariadna 132
            // Sanitizar el parámetro de búsqueda si existe
133
            $search = Functions::sanitizeFilterString($this->params()->fromQuery('search'));
1 efrain 134
 
596 ariadna 135
            // Obtener el control de acceso (ACL) para verificar permisos
136
            $acl = $this->getEvent()->getViewModel()->getVariable('acl');
137
            // Verificar permisos para diferentes acciones
138
            $allowView = $acl->isAllowed($currentUser->usertype_id, 'profile/view');
139
            $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'profile/my-profiles/edit');
140
            $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'profile/my-profiles/delete');
1 efrain 141
 
596 ariadna 142
            // Inicializar el sistema de almacenamiento para manejar imágenes
143
            $storage = Storage::getInstance($this->config, $this->adapter);
1 efrain 144
 
596 ariadna 145
            // Obtener el mapper de perfiles de usuario
146
            $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
147
            // Obtener todos los perfiles del usuario actual, opcionalmente filtrados por búsqueda
148
            $records  = $userProfileMapper->fetchAllByUserIdAndSearch($currentUser->id, $search);
1 efrain 149
 
596 ariadna 150
            // Preparar el array de items para la respuesta
151
            $items = [];
152
            foreach ($records as $record) {
153
                // Construir cada item con la información del perfil
154
                $item = [
155
                    'id' => $record->id,
156
                    'name' => $record->name,
157
                    'image' => $storage->getUserProfileImage($currentUser, $record),
158
                    'link_view' => $allowView ? $this->url()->fromRoute('profile/view', ['id' => $record->uuid])  : '',
159
                    'link_edit' => $allowEdit ? $this->url()->fromRoute('profile/my-profiles/edit', ['id' => $record->uuid])  : '',
160
                    'link_delete' => $allowDelete && $record->public == UserProfile::PUBLIC_NO ? $this->url()->fromRoute('profile/my-profiles/delete', ['id' => $record->uuid]) : '',
161
                ];
1 efrain 162
 
596 ariadna 163
                array_push($items, $item);
164
            }
1 efrain 165
 
596 ariadna 166
            // Preparar la respuesta exitosa con los items
167
            $response = [
168
                'success' => true,
169
                'data' => $items
170
            ];
1 efrain 171
 
596 ariadna 172
            return new JsonModel($response);
1 efrain 173
        } else {
596 ariadna 174
            // Si no es una petición GET, devolver error
1 efrain 175
            return new JsonModel([
176
                'success' => false,
177
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
178
            ]);
179
        }
180
    }
181
 
182
 
183
 
184
    /**
185
     *
186
     * Agregar un nuevo perfil
187
     * @return \Laminas\View\Model\JsonModel
188
     */
189
    public function addAction()
190
    {
191
        $request = $this->getRequest();
192
 
193
 
194
        if ($request->isPost()) {
195
            $form = new  CreateForm();
196
            $dataPost = $request->getPost()->toArray();
197
 
198
            $form->setData($dataPost);
199
 
200
            if ($form->isValid()) {
201
                $dataPost = (array) $form->getData();
202
 
203
                $hydrator = new ObjectPropertyHydrator();
204
                $userProfile = new UserProfile();
205
                $hydrator->hydrate($dataPost, $userProfile);
206
 
207
                $currentUserPlugin = $this->plugin('currentUserPlugin');
208
                $currentUser = $currentUserPlugin->getUser();
209
 
210
                $userProfile->uuid = Functions::genUUID();
211
                $userProfile->user_id = $currentUser->id;
212
                $userProfile->public = \LeadersLinked\Model\UserProfile::PUBLIC_NO;
213
 
214
                $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
215
                $result = $userProfileMapper->insert($userProfile);
216
 
217
                if ($result) {
218
                    $this->logger->info('Se agrego el perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
219
 
220
                    $data = [
221
                        'success'   => true,
222
                        'data'   => 'LABEL_RECORD_ADDED'
223
                    ];
224
                } else {
225
                    $data = [
226
                        'success'   => false,
227
                        'data'      => $userProfile->getError()
228
                    ];
229
                }
230
 
231
                return new JsonModel($data);
232
            } else {
233
                $messages = [];
234
                $form_messages = (array) $form->getMessages();
235
                foreach ($form_messages  as $fieldname => $field_messages) {
236
 
237
                    $messages[$fieldname] = array_values($field_messages);
238
                }
239
 
240
                return new JsonModel([
241
                    'success'   => false,
242
                    'data'   => $messages
243
                ]);
244
            }
245
        } else {
246
            $data = [
247
                'success' => false,
248
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
249
            ];
250
 
251
            return new JsonModel($data);
252
        }
253
 
254
        return new JsonModel($data);
255
    }
256
 
257
    /**
258
     *
259
     * Borrar un perfil excepto el público
260
     * @return \Laminas\View\Model\JsonModel
261
     */
262
    public function deleteAction()
263
    {
264
        $currentUserPlugin = $this->plugin('currentUserPlugin');
265
        $currentUser = $currentUserPlugin->getUser();
266
 
267
        $request = $this->getRequest();
268
        $id = $this->params()->fromRoute('id');
269
 
270
        if (!$id) {
553 stevensc 271
            // Use helper for consistency
272
            return $this->_createSimpleErrorResponse('ERROR_INVALID_PARAMETER');
1 efrain 273
        }
274
 
275
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
276
        $userProfile = $userProfileMapper->fetchOneByUuid($id);
277
        if (!$userProfile) {
596 ariadna 278
            // Use helper for consistency
553 stevensc 279
            return $this->_createSimpleErrorResponse('ERROR_RECORD_NOT_FOUND');
1 efrain 280
        }
281
 
553 stevensc 282
        // Authorize: Check if current user owns the profile
1 efrain 283
        if ($currentUser->id != $userProfile->user_id) {
596 ariadna 284
            // Use helper for consistency
553 stevensc 285
            return $this->_createSimpleErrorResponse('ERROR_UNAUTHORIZED');
286
        }
1 efrain 287
 
553 stevensc 288
        // Prevent deletion of the public profile
289
        if ($userProfile->public == UserProfile::PUBLIC_YES) {
290
            // Use helper for consistency
291
            return $this->_createSimpleErrorResponse('ERROR_PUBLIC_PROFILE');
1 efrain 292
        }
293
 
553 stevensc 294
        if ($request->isPost()) {
295
            $storage = Storage::getInstance($this->config, $this->adapter);
296
            $target_path = $storage->getPathUser();
297
            $user_uuid = $currentUser->uuid; // Assuming user UUID matches profile owner's UUID for path
1 efrain 298
 
553 stevensc 299
            // Attempt to delete associated files first
300
            $image_deleted = true;
301
            if ($userProfile->image) {
302
                $image_deleted = $storage->deleteFile($target_path, $user_uuid, $userProfile->image);
303
                if (!$image_deleted) {
304
                    $this->logger->err("Failed to delete profile image file: {$target_path}/{$user_uuid}/{$userProfile->image}", ['user_id' => $userProfile->user_id]);
305
                    // Decide if this is a critical error. Proceeding with DB deletion for now.
306
                }
307
            }
308
            $cover_deleted = true;
309
            if ($userProfile->cover) {
310
                $cover_deleted = $storage->deleteFile($target_path, $user_uuid, $userProfile->cover);
596 ariadna 311
                if (!$cover_deleted) {
553 stevensc 312
                    $this->logger->err("Failed to delete profile cover file: {$target_path}/{$user_uuid}/{$userProfile->cover}", ['user_id' => $userProfile->user_id]);
313
                    // Decide if this is a critical error. Proceeding with DB deletion for now.
314
                }
315
            }
1 efrain 316
 
553 stevensc 317
            // Delete the database record
1 efrain 318
            $result = $userProfileMapper->delete($userProfile);
319
            if ($result) {
320
                $this->logger->info('Se borro el perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
321
 
553 stevensc 322
                // Success response
1 efrain 323
                $data = [
324
                    'success' => true,
325
                    'data' => 'LABEL_RECORD_DELETED'
326
                ];
327
            } else {
553 stevensc 328
                // Use helper for DB error
329
                $data = $this->_createSimpleErrorResponse($userProfileMapper->getError() ?: 'ERROR_THERE_WAS_AN_ERROR');
1 efrain 330
            }
331
        } else {
553 stevensc 332
            // Use helper for method error
333
            $data = $this->_createSimpleErrorResponse('ERROR_METHOD_NOT_ALLOWED');
1 efrain 334
        }
335
 
553 stevensc 336
        // Return JsonModel for all paths
337
        return $data instanceof JsonModel ? $data : new JsonModel($data);
1 efrain 338
    }
339
 
340
    /**
596 ariadna 341
     * Presenta el perfil con las opciones de edición de cada sección.
342
     * Este método:
343
     * - Obtiene y valida el perfil del usuario
344
     * - Recopila toda la información relacionada (educación, experiencia, habilidades, etc.)
345
     * - Prepara los datos para la vista de edición
346
     * - Genera las URLs necesarias para las diferentes acciones de edición
347
     *
1 efrain 348
     * @return \Laminas\Http\Response|\Laminas\View\Model\ViewModel|\Laminas\View\Model\JsonModel
349
     */
350
    public function editAction()
351
    {
596 ariadna 352
        // Obtener el usuario actual del sistema
1 efrain 353
        $currentUserPlugin = $this->plugin('currentUserPlugin');
354
        $currentUser = $currentUserPlugin->getUser();
355
 
596 ariadna 356
        // Obtener el plugin para mensajes flash
1 efrain 357
        $flashMessenger = $this->plugin('FlashMessenger');
358
 
596 ariadna 359
        // Obtener parámetros de la petición
1 efrain 360
        $request = $this->getRequest();
361
        $id = $this->params()->fromRoute('id');
362
 
596 ariadna 363
        // Validar que se proporcionó un ID
1 efrain 364
        if (!$id) {
365
            $flashMessenger->addErrorMessage('ERROR_INVALID_PARAMETER');
366
            return $this->redirect()->toRoute('dashboard');
367
        }
368
 
596 ariadna 369
        // Obtener el perfil de usuario correspondiente
1 efrain 370
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
371
        $userProfile = $userProfileMapper->fetchOneByUuid($id);
372
 
596 ariadna 373
        // Validar que el perfil existe
1 efrain 374
        if (!$userProfile) {
375
            $flashMessenger->addErrorMessage('ERROR_RECORD_NOT_FOUND');
376
            return $this->redirect()->toRoute('dashboard');
377
        }
378
 
596 ariadna 379
        // Verificar que el usuario actual es el propietario del perfil
1 efrain 380
        if ($currentUser->id != $userProfile->user_id) {
381
            $flashMessenger->addErrorMessage('ERROR_UNAUTHORIZED');
382
            return $this->redirect()->toRoute('dashboard');
383
        }
384
 
596 ariadna 385
        // Determinar la clave de API de Google Maps según el entorno
1 efrain 386
        $sandbox = $this->config['leaderslinked.runmode.sandbox'];
387
        if ($sandbox) {
388
            $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
389
        } else {
390
            $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
391
        }
392
 
596 ariadna 393
        // Procesar solo peticiones GET
1 efrain 394
        if ($request->isGet()) {
596 ariadna 395
            // Obtener información de ubicación si existe
1 efrain 396
            if ($userProfile->location_id) {
397
                $locationMapper = LocationMapper::getInstance($this->adapter);
398
                $location = $locationMapper->fetchOne($userProfile->location_id);
399
 
400
                $formattedAddress = $location->formatted_address;
401
                $country = $location->country;
402
            } else {
403
                $formattedAddress = '';
404
                $country = '';
405
            }
406
 
596 ariadna 407
            // Obtener información del usuario
1 efrain 408
            $userMapper = UserMapper::getInstance($this->adapter);
409
            $user = $userMapper->fetchOne($userProfile->user_id);
410
 
596 ariadna 411
            // Obtener idiomas del usuario
1 efrain 412
            $userLanguages = [];
413
            $languageMapper = LanguageMapper::getInstance($this->adapter);
414
            $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
415
            $records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);
416
            foreach ($records as $record) {
417
                $language = $languageMapper->fetchOne($record->language_id);
418
                $userLanguages[$language->id] = $language->name;
419
            }
420
 
596 ariadna 421
            // Obtener educación del usuario
1 efrain 422
            $locationMapper = LocationMapper::getInstance($this->adapter);
423
            $degreeMapper = DegreeMapper::getInstance($this->adapter);
424
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);
425
            $userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);
426
 
596 ariadna 427
            // Formatear información de educación
1 efrain 428
            foreach ($userEducations  as &$userEducation) {
429
                $location = $locationMapper->fetchOne($userEducation->location_id);
430
                $degree = $degreeMapper->fetchOne($userEducation->degree_id);
431
 
432
                $userEducation = [
433
                    'university' => $userEducation->university,
434
                    'degree' => $degree->name,
435
                    'field_of_study' => $userEducation->field_of_study,
436
                    'grade_or_percentage' => $userEducation->grade_or_percentage,
437
                    'formatted_address' => $location->formatted_address,
438
                    'from_year' => $userEducation->from_year,
439
                    'to_year' => $userEducation->to_year,
440
                    'description' => $userEducation->description,
350 www 441
                    'link_edit' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_education_id' => $userEducation->uuid]),
442
                    'link_delete' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_education_id' => $userEducation->uuid]),
1 efrain 443
                ];
444
            }
445
 
596 ariadna 446
            // Obtener experiencia laboral del usuario
1 efrain 447
            $industryMapper = IndustryMapper::getInstance($this->adapter);
448
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
449
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
450
            $userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);
451
 
596 ariadna 452
            // Formatear información de experiencia laboral
1 efrain 453
            foreach ($userExperiences  as &$userExperience) {
454
                $location = $locationMapper->fetchOne($userExperience->location_id);
455
                $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
456
                $industry = $industryMapper->fetchOne($userExperience->industry_id);
457
 
458
                $userExperience = [
459
                    'company' => $userExperience->company,
460
                    'industry' => $industry->name,
461
                    'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ')',
462
                    'title' => $userExperience->title,
463
                    'formatted_address' => $location->formatted_address,
464
                    'from_year' => $userExperience->from_year,
465
                    'from_month' => $userExperience->from_month,
466
                    'to_year' => $userExperience->to_year,
467
                    'to_month' => $userExperience->to_month,
468
                    'description' => $userExperience->description,
469
                    'is_current' => $userExperience->is_current,
350 www 470
                    'link_edit' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_experience_id' => $userExperience->uuid]),
471
                    'link_delete' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_experience_id' => $userExperience->uuid])
1 efrain 472
                ];
473
            }
474
 
596 ariadna 475
            // Obtener aptitudes del usuario
1 efrain 476
            $userAptitudes = [];
477
            $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);
478
            $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
479
            $records  = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);
480
            foreach ($records as $record) {
481
                $aptitude = $aptitudeMapper->fetchOne($record->aptitude_id);
482
                if ($aptitude) {
483
                    $userAptitudes[$aptitude->uuid] = $aptitude->name;
484
                }
485
            }
486
 
596 ariadna 487
            // Obtener hobbies e intereses del usuario
1 efrain 488
            $userHobbiesAndInterests = [];
489
            $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);
490
            $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
491
            $records  = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);
492
            foreach ($records as $record) {
493
                $hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($record->hobby_and_interest_id);
494
                if ($hobbyAndInterest) {
495
                    $userHobbiesAndInterests[$hobbyAndInterest->uuid] = $hobbyAndInterest->name;
496
                }
497
            }
498
 
596 ariadna 499
            // Obtener habilidades del usuario
1 efrain 500
            $userSkills = [];
501
            $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
502
            $skillMapper = SkillMapper::getInstance($this->adapter);
503
            $records  = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
504
            foreach ($records as $record) {
505
                $skill = $skillMapper->fetchOne($record->skill_id);
506
                $userSkills[$skill->uuid] = $skill->name;
507
            }
508
 
596 ariadna 509
            // Obtener estadísticas de conexiones
1 efrain 510
            $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
511
            $following = $companyFollowerMapper->getCountFollowing($user->id);
512
 
513
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
514
            $follower = $connectionMapper->fetchTotalConnectionByUser($user->id);
515
 
596 ariadna 516
            // Obtener configuraciones de tamaño de imágenes
1 efrain 517
            $image_size_cover = $this->config['leaderslinked.image_sizes.user_cover_upload'];
518
            $image_size_profile = $this->config['leaderslinked.image_sizes.user_upload'];
519
 
596 ariadna 520
            // Inicializar el sistema de almacenamiento
333 www 521
            $storage = Storage::getInstance($this->config, $this->adapter);
1 efrain 522
 
596 ariadna 523
            // Preparar datos para la respuesta
524
            $data = [
525
                'following'         => $following,
526
                'follower'          => $follower,
527
                'user_id'           => $user->id,
528
                'user_uuid'         => $user->uuid,
529
                'full_name'         => trim($user->first_name . ' ' . $user->last_name),
530
                'user_profile_id'   => $userProfile->id,
531
                'user_profile_uuid' => $userProfile->uuid,
532
                'image'             => $storage->getUserProfileImage($currentUser, $userProfile),
533
                'cover'             => $storage->getUserProfileCover($currentUser, $userProfile),
534
                'overview'          => $userProfile->description,
535
                'facebook'          => $userProfile->facebook,
536
                'instagram'         => $userProfile->instagram,
537
                'twitter'           => $userProfile->twitter,
538
                'formatted_address' => $formattedAddress,
539
                'country'           => $country,
540
                'user_skills'       => $userSkills,
541
                'user_languages'    => $userLanguages,
542
                'user_educations'   => $userEducations,
543
                'user_experiences'  => $userExperiences,
544
                'user_aptitudes'                => $userAptitudes,
545
                'user_hobbies_and_interests'    => $userHobbiesAndInterests,
546
                'image_size_cover' =>  $image_size_cover,
547
                'image_size_profile' => $image_size_profile,
348 www 548
 
596 ariadna 549
                // Generar URLs para las diferentes acciones de edición
550
                'link_extended' => $this->url()->fromRoute('profile/my-profiles/extended', ['id' => $userProfile->uuid]),
551
                'link_image_upload' => $this->url()->fromRoute('profile/my-profiles/image', ['id' => $userProfile->uuid, 'operation' => 'upload']),
552
                'link_image_delete' => $this->url()->fromRoute('profile/my-profiles/image', ['id' => $userProfile->uuid, 'operation' => 'delete']),
553
                'link_cover_upload' => $this->url()->fromRoute('profile/my-profiles/cover', ['id' => $userProfile->uuid, 'operation' => 'upload']),
554
                'link_cover_delete' => $this->url()->fromRoute('profile/my-profiles/cover', ['id' => $userProfile->uuid, 'operation' => 'delete']),
555
                'link_experience_add' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'add']),
556
                'link_education_add' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'add']),
557
                'link_language' => $this->url()->fromRoute('profile/my-profiles/language', ['id' => $userProfile->uuid]),
558
                'link_location' => $this->url()->fromRoute('profile/my-profiles/location', ['id' => $userProfile->uuid]),
559
                'link_skill' => $this->url()->fromRoute('profile/my-profiles/skill', ['id' => $userProfile->uuid]),
560
                'link_social_network' => $this->url()->fromRoute('profile/my-profiles/social-network', ['id' => $userProfile->uuid]),
561
                'link_aptitude' => $this->url()->fromRoute('profile/my-profiles/aptitude', ['id' => $userProfile->uuid]),
562
                'link_hobby_and_interest' => $this->url()->fromRoute('profile/my-profiles/hobby-and-interest', ['id' => $userProfile->uuid]),
563
            ];
1 efrain 564
 
596 ariadna 565
            return new JsonModel($data);
1 efrain 566
        } else {
596 ariadna 567
            // Si no es una petición GET, devolver error
1 efrain 568
            $data = [
569
                'success' => false,
570
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
571
            ];
572
 
573
            return new JsonModel($data);
574
        }
575
 
576
        return new JsonModel($data);
577
    }
578
 
579
    /**
580
     * Actualización de las habilidades
581
     * @return \Laminas\View\Model\JsonModel
582
     */
583
    public function skillAction()
584
    {
585
        $currentUserPlugin = $this->plugin('currentUserPlugin');
586
        $currentUser = $currentUserPlugin->getUser();
587
 
588
        $user_profile_id = $this->params()->fromRoute('id');
589
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
590
 
591
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
592
        if (!$userProfile) {
593
            $response = [
594
                'success' => false,
595
                'data' => 'ERROR_INVALID_PARAMETER'
596
            ];
597
 
598
            return new JsonModel($response);
599
        }
600
 
601
        if ($currentUser->id != $userProfile->user_id) {
602
            $response = [
603
                'success' => false,
604
                'data' => 'ERROR_UNAUTHORIZED'
605
            ];
606
 
607
            return new JsonModel($response);
608
        }
609
 
610
 
611
 
612
        $request = $this->getRequest();
613
        if ($request->isGet()) {
614
            $skillMapper = SkillMapper::getInstance($this->adapter);
615
 
616
 
617
            $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
618
            $userSkills  = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
619
 
620
            $items = [];
621
            foreach ($userSkills as $userSkill) {
622
                $skill = $skillMapper->fetchOne($userSkill->skill_id);
623
                array_push($items, $skill->uuid);
624
            }
625
 
626
            $data = [
627
                'success' => true,
628
                'data' => $items
629
            ];
630
 
631
            return new JsonModel($data);
632
        } else if ($request->isPost()) {
633
 
634
            $form = new SkillForm($this->adapter);
635
            $dataPost = $request->getPost()->toArray();
636
 
637
            $form->setData($dataPost);
638
 
639
            if ($form->isValid()) {
640
                $this->logger->info('Se actualizaron las habilidades del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
641
 
642
                $skillMapper = SkillMapper::getInstance($this->adapter);
643
 
644
 
645
                $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
646
                $userSkillMapper->deleteByUserProfileId($userProfile->id);
647
 
648
                $dataPost = (array) $form->getData();
649
                $skills = $dataPost['skills'];
650
                foreach ($skills as $skill_uuid) {
651
 
652
                    $skill = $skillMapper->fetchOneByUuid($skill_uuid);
653
 
654
 
655
 
656
                    $userSkill = new UserSkill();
657
                    $userSkill->user_id = $userProfile->user_id;
658
                    $userSkill->user_profile_id = $userProfile->id;
659
                    $userSkill->skill_id =  $skill->id;
660
 
661
                    $userSkillMapper->insert($userSkill);
662
                }
663
 
664
                $items = [];
665
 
666
                $records = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
667
                foreach ($records as $record) {
668
                    $skill = $skillMapper->fetchOne($record->skill_id);
669
                    array_push($items,  ['value' => $skill->uuid, 'label' => $skill->name]);
670
                }
671
 
672
                return new JsonModel([
673
                    'success'   => true,
674
                    'data'   => $items
675
                ]);
676
            } else {
677
                $messages = [];
678
                $form_messages = (array) $form->getMessages();
679
                foreach ($form_messages  as $fieldname => $field_messages) {
680
                    $messages[$fieldname] = array_values($field_messages);
681
                }
682
 
683
                return new JsonModel([
684
                    'success'   => false,
685
                    'data'   => $messages
686
                ]);
687
            }
688
        }
689
 
690
 
691
        $data = [
692
            'success' => false,
693
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
694
        ];
695
 
696
 
697
        return new JsonModel($data);
698
    }
699
 
700
    /**
701
     * Actualización de los idiomas
702
     * @return \Laminas\View\Model\JsonModel
703
     */
704
    public function languageAction()
705
    {
706
 
707
        $currentUserPlugin = $this->plugin('currentUserPlugin');
708
        $currentUser = $currentUserPlugin->getUser();
709
 
710
        $user_profile_id = $this->params()->fromRoute('id');
711
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
712
 
713
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
714
        if (!$userProfile) {
715
            $response = [
716
                'success' => false,
717
                'data' => 'ERROR_INVALID_PARAMETER'
718
            ];
719
 
720
            return new JsonModel($response);
721
        }
722
 
723
 
724
        if ($currentUser->id != $userProfile->user_id) {
725
            $response = [
726
                'success' => false,
727
                'data' => 'ERROR_UNAUTHORIZED'
728
            ];
729
 
730
            return new JsonModel($response);
731
        }
732
 
733
 
734
 
735
        $request = $this->getRequest();
736
        if ($request->isGet()) {
737
            $this->logger->info('Se actualizaron los idiomas del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
738
 
739
            $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
740
            $languages  = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);
741
 
742
            $items = [];
743
            foreach ($languages as $language) {
744
                array_push($items, $language->language_id);
745
            }
746
 
747
            $data = [
748
                'success' => true,
749
                'data' => $items
750
            ];
751
 
752
            return new JsonModel($data);
753
        } else if ($request->isPost()) {
754
 
755
            $form = new LanguageForm($this->adapter);
756
            $dataPost = $request->getPost()->toArray();
757
 
758
            $form->setData($dataPost);
759
 
760
            if ($form->isValid()) {
761
 
762
                $languageMapper = LanguageMapper::getInstance($this->adapter);
763
                $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
764
                $userLanguageMapper->deleteByUserProfileId($userProfile->id);
765
 
766
                $dataPost = (array) $form->getData();
767
                $languages = $dataPost['languages'];
768
                foreach ($languages as $language_id) {
769
                    $language = $languageMapper->fetchOne($language_id);
770
 
771
                    $userLanguage = new UserLanguage();
772
                    $userLanguage->user_id = $userProfile->user_id;
773
                    $userLanguage->user_profile_id = $userProfile->id;
774
                    $userLanguage->language_id = $language->id;
775
 
776
                    $userLanguageMapper->insert($userLanguage);
777
                }
778
 
779
                $items = [];
780
                $records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);
781
                foreach ($records as $record) {
782
                    $language = $languageMapper->fetchOne($record->language_id);
783
                    array_push($items,  ['value' => $language->id, 'label' => $language->name]);
784
                }
785
 
786
                return new JsonModel([
787
                    'success'   => true,
788
                    'data'   => $items
789
                ]);
790
            } else {
791
                $messages = [];
792
                $form_messages = (array) $form->getMessages();
793
                foreach ($form_messages  as $fieldname => $field_messages) {
794
                    $messages[$fieldname] = array_values($field_messages);
795
                }
796
 
797
                return new JsonModel([
798
                    'success'   => false,
799
                    'data'   => $messages
800
                ]);
801
            }
802
        }
803
 
804
 
805
        $data = [
806
            'success' => false,
807
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
808
        ];
809
 
810
 
811
        return new JsonModel($data);
812
    }
813
 
814
    /**
815
     * Actualización de la descripción y cualquier otro campo extendido del perfil a futuro
816
     * @return \Laminas\View\Model\JsonModel
817
     */
818
    public function extendedAction()
819
    {
820
        $currentUserPlugin = $this->plugin('currentUserPlugin');
821
        $currentUser = $currentUserPlugin->getUser();
822
 
823
 
824
        $user_profile_id = $this->params()->fromRoute('id');
825
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
826
 
827
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
828
        if (!$userProfile) {
829
            $response = [
830
                'success' => false,
831
                'data' => 'ERROR_INVALID_PARAMETER'
832
            ];
833
 
834
            return new JsonModel($response);
835
        }
836
 
837
        if ($currentUser->id != $userProfile->user_id) {
838
            $response = [
839
                'success' => false,
840
                'data' => 'ERROR_UNAUTHORIZED'
841
            ];
842
 
843
            return new JsonModel($response);
844
        }
845
 
846
 
847
 
848
        $request = $this->getRequest();
849
        if ($request->isGet()) {
850
            $data = [
851
                'success' => true,
852
                'data' => [
853
                    'description' => $userProfile->description,
854
                ]
855
            ];
856
 
857
            return new JsonModel($data);
858
        } else if ($request->isPost()) {
859
 
860
 
861
            $form = new ExtendedForm();
862
            $dataPost = $request->getPost()->toArray();
863
 
864
            $form->setData($dataPost);
865
 
866
            if ($form->isValid()) {
867
                $dataPost = (array) $form->getData();
868
 
869
                $hydrator = new ObjectPropertyHydrator();
870
                $hydrator->hydrate($dataPost, $userProfile);
871
 
872
                $userProfileMapper->updateExtended($userProfile);
873
 
874
                $this->logger->info('Se actualizo las descripción del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
875
 
876
                return new JsonModel([
877
                    'success'   => true,
878
                    'data' => [
879
                        'description' => $userProfile->description,
880
                    ]
881
                ]);
882
            } else {
883
                $messages = [];
884
                $form_messages = (array) $form->getMessages();
885
                foreach ($form_messages  as $fieldname => $field_messages) {
886
                    $messages[$fieldname] = array_values($field_messages);
887
                }
888
 
889
                return new JsonModel([
890
                    'success'   => false,
891
                    'data'   => $messages
892
                ]);
893
            }
894
        }
895
 
896
 
897
        $data = [
898
            'success' => false,
899
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
900
        ];
901
 
902
 
903
        return new JsonModel($data);
904
    }
905
 
906
    /**
907
     * Actualización de la ubucación
908
     * @return \Laminas\View\Model\JsonModel
909
     */
910
    public function locationAction()
911
    {
912
        $currentUserPlugin = $this->plugin('currentUserPlugin');
913
        $currentUser = $currentUserPlugin->getUser();
914
 
915
        $user_profile_id = $this->params()->fromRoute('id');
916
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
917
 
918
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
919
        if (!$userProfile) {
920
            $response = [
921
                'success' => false,
922
                'data' => 'ERROR_INVALID_PARAMETER'
923
            ];
924
 
925
            return new JsonModel($response);
926
        }
927
 
928
 
929
        if ($currentUser->id != $userProfile->user_id) {
930
            $response = [
931
                'success' => false,
932
                'data' => 'ERROR_UNAUTHORIZED'
933
            ];
934
 
935
            return new JsonModel($response);
936
        }
937
 
938
 
939
 
940
        $request = $this->getRequest();
941
        if ($request->isPost()) {
942
 
943
            $form = new LocationForm();
944
            $dataPost = $request->getPost()->toArray();
945
 
946
            $form->setData($dataPost);
947
 
948
            if ($form->isValid()) {
949
                $this->logger->info('Se actualizaron la ubicación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
950
 
951
                $dataPost = (array) $form->getData();
952
 
953
                $location = new Location();
954
                $hydrator = new ObjectPropertyHydrator();
955
                $hydrator->hydrate($dataPost, $location);
956
 
957
                $location->id = $userProfile->location_id ? $userProfile->location_id : null;
958
 
959
 
960
 
961
                $locationMapper = LocationMapper::getInstance($this->adapter);
962
                if ($userProfile->location_id) {
963
                    $result = $locationMapper->update($location);
964
                } else {
965
                    $result = $locationMapper->insert($location);
966
 
967
                    if ($result) {
968
                        $userProfile->location_id = $location->id;
969
                        $userProfileMapper->updateLocation($userProfile);
970
                    }
971
                }
972
 
973
                if ($result) {
974
                    if ($userProfile->public == UserProfile::PUBLIC_YES) {
975
                        $currentUser->location_id = $location->id;
976
 
977
                        $userMapper = UserMapper::getInstance($this->adapter);
978
                        $userMapper->updateLocation($currentUser);
979
                    }
980
 
981
 
982
                    $response = [
983
                        'success'   => true,
984
                        'data' => [
985
                            'formatted_address' => $location->formatted_address,
986
                            'country' => $location->country,
987
                        ]
988
                    ];
989
                } else {
990
                    $response = [
991
                        'success'   => false,
992
                        'data' => 'ERROR_THERE_WAS_AN_ERROR'
993
                    ];
994
                }
995
 
996
 
997
 
998
                return new JsonModel($response);
999
            } else {
1000
                return new JsonModel([
1001
                    'success'   => false,
1002
                    'data'   =>   'ERROR_PLACED_AUTOCOMPLETE_DOES_NOT_CONTAIN_GEOMETRY'
1003
                ]);
1004
            }
1005
        }
1006
 
1007
 
1008
        $data = [
1009
            'success' => false,
1010
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1011
        ];
1012
 
1013
 
1014
        return new JsonModel($data);
1015
    }
1016
 
1017
    /**
1018
     * Actualización de las redes sociales
1019
     * @return \Laminas\View\Model\JsonModel
1020
     */
1021
    public function socialNetworkAction()
1022
    {
1023
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1024
        $currentUser = $currentUserPlugin->getUser();
1025
 
1026
        $user_profile_id = $this->params()->fromRoute('id');
1027
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
1028
 
1029
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
1030
        if (!$userProfile) {
1031
            $response = [
1032
                'success' => false,
1033
                'data' => 'ERROR_INVALID_PARAMETER'
1034
            ];
1035
 
1036
            return new JsonModel($response);
1037
        }
1038
 
1039
 
1040
        if ($currentUser->id != $userProfile->user_id) {
1041
            $response = [
1042
                'success' => false,
1043
                'data' => 'ERROR_UNAUTHORIZED'
1044
            ];
1045
 
1046
            return new JsonModel($response);
1047
        }
1048
 
1049
 
1050
 
1051
        $request = $this->getRequest();
1052
        if ($request->isGet()) {
1053
            $data = [
1054
                'success' => true,
1055
                'data' => [
1056
                    'facebook' => $userProfile->facebook,
1057
                    'instagram' => $userProfile->instagram,
1058
                    'twitter' => $userProfile->twitter
1059
                ]
1060
            ];
1061
 
1062
            return new JsonModel($data);
1063
        } else if ($request->isPost()) {
1064
 
1065
            $form = new SocialNetworkForm();
1066
            $dataPost = $request->getPost()->toArray();
1067
 
1068
            $form->setData($dataPost);
1069
 
1070
            if ($form->isValid()) {
1071
                $this->logger->info('Se actualizaron las redes sociales del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1072
 
1073
                $dataPost = (array) $form->getData();
1074
 
1075
                $hydrator = new ObjectPropertyHydrator();
1076
                $hydrator->hydrate($dataPost, $userProfile);
1077
 
1078
                $userProfileMapper->updateSocialNetwork($userProfile);
1079
                return new JsonModel([
1080
                    'success'   => true,
1081
                    'data' => [
1082
                        'facebook' => $userProfile->facebook,
1083
                        'instagram' => $userProfile->instagram,
1084
                        'twitter' => $userProfile->twitter
1085
                    ]
1086
                ]);
1087
            } else {
1088
                $messages = [];
1089
                $form_messages = (array) $form->getMessages();
1090
                foreach ($form_messages  as $fieldname => $field_messages) {
1091
                    $messages[$fieldname] = array_values($field_messages);
1092
                }
1093
 
1094
                return new JsonModel([
1095
                    'success'   => false,
1096
                    'data'   => $messages
1097
                ]);
1098
            }
1099
        }
1100
 
1101
 
1102
        $data = [
1103
            'success' => false,
1104
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1105
        ];
1106
 
1107
 
1108
        return new JsonModel($data);
1109
    }
1110
 
383 www 1111
 
1112
 
596 ariadna 1113
 
1 efrain 1114
    /**
1115
     * Actualización de los registros de estudios realizados
1116
     * @return \Laminas\View\Model\JsonModel
1117
     */
1118
    public function  educationAction()
1119
    {
1120
 
1121
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1122
        $currentUser = $currentUserPlugin->getUser();
1123
 
1124
        $user_profile_id    = $this->params()->fromRoute('id');
1125
        $user_education_id  = $this->params()->fromRoute('user_education_id');
1126
        $operation          = $this->params()->fromRoute('operation');
1127
 
1128
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
1129
 
1130
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
1131
        if (!$userProfile) {
1132
            $response = [
1133
                'success' => false,
1134
                'data' => 'ERROR_INVALID_PARAMETER'
1135
            ];
1136
 
1137
            return new JsonModel($response);
1138
        }
1139
 
1140
 
1141
        if ($currentUser->id != $userProfile->user_id) {
1142
            $response = [
1143
                'success' => false,
1144
                'data' => 'ERROR_UNAUTHORIZED'
1145
            ];
1146
 
1147
            return new JsonModel($response);
1148
        }
1149
 
1150
 
1151
 
1152
        $request = $this->getRequest();
1153
        if ($request->isPost()) {
1154
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);
1155
 
1156
            if ($operation == 'delete' || $operation == 'edit') {
1157
                $userEducation = $userEducationMapper->fetchOneByUuid($user_education_id);
1158
 
1159
 
1160
                if (!$userEducation) {
1161
 
1162
                    $response = [
1163
                        'success' => false,
1164
                        'data' => 'ERROR_RECORD_NOT_FOUND'
1165
                    ];
1166
 
1167
                    return new JsonModel($response);
1168
                } else if ($userProfile->id != $userEducation->user_profile_id) {
1169
                    $response = [
1170
                        'success' => false,
1171
                        'data' => 'ERROR_UNAUTHORIZED'
1172
                    ];
1173
 
1174
                    return new JsonModel($response);
1175
                }
1176
            } else {
1177
                $userEducation = null;
1178
            }
1179
 
1180
            $locationMapper = LocationMapper::getInstance($this->adapter);
1181
            if ($operation == 'delete') {
1182
                $this->logger->info('Se borro un registro de educación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1183
 
1184
                $result = $userEducationMapper->delete($userEducation);
1185
                if ($result) {
1186
                    $locationMapper->delete($userEducation->location_id);
1187
                }
1188
            } else {
1189
 
1190
 
1191
                $form = new EducationForm($this->adapter);
1192
                $dataPost = $request->getPost()->toArray();
1193
 
1194
                $form->setData($dataPost);
1195
 
1196
                if ($form->isValid()) {
1197
 
1198
                    if (!$userEducation) {
1199
                        $userEducation = new UserEducation();
1200
                        $userEducation->user_id = $userProfile->user_id;
1201
                        $userEducation->user_profile_id = $userProfile->id;
1202
                    }
1203
 
1204
                    $dataPost = (array) $form->getData();
1205
 
1206
                    $hydrator = new ObjectPropertyHydrator();
1207
                    $hydrator->hydrate($dataPost, $userEducation);
1208
 
1209
                    $degreeMapper = DegreeMapper::getInstance($this->adapter);
1210
                    $degree = $degreeMapper->fetchOneByUuid($dataPost['degree_id']);
1211
                    $userEducation->degree_id = $degree->id;
1212
 
1213
 
1214
 
1215
 
1216
                    if ($userEducation->location_id) {
1217
                        $location = $locationMapper->fetchOne($userEducation->location_id);
1218
                    } else {
1219
                        $location = new Location();
1220
                    }
1221
 
1222
                    $hydrator->hydrate($dataPost, $location);
1223
                    if ($userEducation->location_id) {
1224
                        $this->logger->info('Se actualizo un registro de educación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1225
 
1226
                        $result = $locationMapper->update($location);
1227
                    } else {
1228
                        $this->logger->info('Se agrego un registro de educación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1229
 
1230
                        $result = $locationMapper->insert($location);
1231
 
1232
                        if ($result) {
1233
                            $userEducation->location_id = $location->id;
1234
                        }
1235
                    }
1236
                    if ($result) {
1237
                        if ($userEducation->id) {
1238
                            $result = $userEducationMapper->update($userEducation);
1239
                        } else {
1240
                            $result =  $userEducationMapper->insert($userEducation);
1241
                        }
1242
                    }
1243
                } else {
1244
                    $messages = [];
1245
                    $form_messages = (array) $form->getMessages();
1246
                    foreach ($form_messages  as $fieldname => $field_messages) {
1247
                        $messages[$fieldname] = array_values($field_messages);
1248
                    }
1249
 
1250
                    return new JsonModel([
1251
                        'success'   => false,
1252
                        'data'   => $messages
1253
                    ]);
1254
                }
1255
            }
1256
 
1257
            if ($result) {
1258
                $degreeMapper = DegreeMapper::getInstance($this->adapter);
1259
                $userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);
1260
 
1261
                foreach ($userEducations  as &$userEducation) {
1262
                    $location = $locationMapper->fetchOne($userEducation->location_id);
1263
                    $degree = $degreeMapper->fetchOne($userEducation->degree_id);
1264
 
1265
                    $userEducation = [
1266
                        'university' => $userEducation->university,
1267
                        'degree' => $degree->name,
1268
                        'field_of_study' => $userEducation->field_of_study,
1269
                        'grade_or_percentage' => $userEducation->grade_or_percentage,
1270
                        'formatted_address' => $location->formatted_address,
1271
                        'from_year' => $userEducation->from_year,
1272
                        'to_year' => $userEducation->to_year,
1273
                        'description' => $userEducation->description,
350 www 1274
                        'link_edit' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_education_id' => $userEducation->uuid]),
1275
                        'link_delete' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_education_id' => $userEducation->uuid]),
1 efrain 1276
                    ];
1277
                }
1278
 
1279
                $response = [
1280
                    'success'   => true,
1281
                    'data' => $userEducations
1282
                ];
1283
            } else {
1284
                $response = [
1285
                    'success'   => false,
1286
                    'data' => 'ERROR_THERE_WAS_AN_ERROR'
1287
                ];
1288
            }
1289
 
1290
 
1291
 
1292
            return new JsonModel($response);
1293
        } else if ($request->isGet() && $operation == 'edit') {
1294
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);
1295
            $userEducation = $userEducationMapper->fetchOneByUuid($user_education_id);
1296
 
1297
            if (!$userEducation) {
1298
 
1299
                $response = [
1300
                    'success' => false,
1301
                    'data' => 'ERROR_RECORD_NOT_FOUND'
1302
                ];
1303
            } else if ($userProfile->id != $userEducation->user_profile_id) {
1304
                $response = [
1305
                    'success' => false,
1306
                    'data' => 'ERROR_UNAUTHORIZED'
1307
                ];
1308
            } else {
1309
                $locationMapper = LocationMapper::getInstance($this->adapter);
1310
                $location = $locationMapper->fetchOne($userEducation->location_id);
1311
 
1312
                $hydrator = new ObjectPropertyHydrator();
1313
                $education = $hydrator->extract($userEducation);
1314
 
1315
                $degree = $degreeMapper = DegreeMapper::getInstance($this->adapter);
1316
                $degree = $degreeMapper->fetchOne($education['degree_id']);
1317
                $education['degree_id'] = $degree->uuid;
1318
 
1319
                $location = [
1320
                    'address1' => $location->address1,
1321
                    'address2' => $location->address2,
1322
                    'city1' => $location->city1,
1323
                    'city2' => $location->city2,
1324
                    'country' => $location->country,
1325
                    'formatted_address' => $location->formatted_address,
1326
                    'latitude' => $location->latitude,
1327
                    'longitude' => $location->longitude,
1328
                    'postal_code' => $location->postal_code,
1329
                    'state' => $location->state,
1330
                ];
1331
 
1332
                $response = [
1333
                    'success' => true,
1334
                    'data' => [
1335
                        'location' => $location,
1336
                        'education' => $education,
1337
                    ]
1338
                ];
1339
            }
1340
 
1341
            return new JsonModel($response);
1342
        }
1343
 
1344
 
1345
 
1346
 
1347
        $data = [
1348
            'success' => false,
1349
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1350
        ];
1351
 
1352
 
1353
        return new JsonModel($data);
1354
    }
1355
 
1356
    /**
1357
     * Actualización de los registros de la experiencia laboral
1358
     * @return \Laminas\View\Model\JsonModel
1359
     */
1360
    public function  experienceAction()
1361
    {
1362
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1363
        $currentUser = $currentUserPlugin->getUser();
1364
 
1365
        $user_profile_id    = $this->params()->fromRoute('id');
1366
        $user_experience_id = $this->params()->fromRoute('user_experience_id');
1367
        $operation          = $this->params()->fromRoute('operation');
1368
 
1369
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
1370
 
1371
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
1372
        if (!$userProfile) {
1373
            $response = [
1374
                'success' => false,
1375
                'data' => 'ERROR_INVALID_PARAMETER'
1376
            ];
1377
 
1378
            return new JsonModel($response);
1379
        }
1380
 
1381
        if ($currentUser->id != $userProfile->user_id) {
1382
            $response = [
1383
                'success' => false,
1384
                'data' => 'ERROR_UNAUTHORIZED'
1385
            ];
1386
 
1387
            return new JsonModel($response);
1388
        }
1389
 
1390
 
1391
 
1392
        $request = $this->getRequest();
1393
        if ($request->isPost()) {
1394
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
1395
 
1396
            if ($operation == 'delete' || $operation == 'edit') {
1397
                $userExperience = $userExperienceMapper->fetchOneByUuid($user_experience_id);
1398
 
1399
                if (!$userExperience) {
1400
 
1401
                    $response = [
1402
                        'success' => false,
1403
                        'data' => 'ERROR_RECORD_NOT_FOUND'
1404
                    ];
1405
 
1406
                    return new JsonModel($response);
1407
                } else if ($userProfile->id != $userExperience->user_profile_id) {
1408
                    $response = [
1409
                        'success' => false,
1410
                        'data' => 'ERROR_UNAUTHORIZED'
1411
                    ];
1412
 
1413
                    return new JsonModel($response);
1414
                }
1415
            } else {
1416
                $userExperience = null;
1417
            }
1418
 
1419
            $locationMapper = LocationMapper::getInstance($this->adapter);
1420
            if ($operation == 'delete') {
1421
                $this->logger->info('Se borro un registro de experiencia del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1422
 
1423
                $result = $userExperienceMapper->delete($userExperience);
1424
                if ($result) {
1425
                    $locationMapper->delete($userExperience->location_id);
1426
                }
1427
            } else {
1428
 
1429
 
1430
                $form = new ExperienceForm($this->adapter);
1431
                $dataPost = $request->getPost()->toArray();
1432
 
1433
 
1434
                $dataPost['is_current'] = isset($dataPost['is_current']) ? $dataPost['is_current'] : UserExperience::IS_CURRENT_NO;
1435
                if ($dataPost['is_current']  == UserExperience::IS_CURRENT_YES) {
1436
                    $dataPost['to_month'] = 12;
1437
                    $dataPost['to_year'] = date('Y');
1438
                }
1439
 
1440
 
1441
                $form->setData($dataPost);
1442
 
1443
                if ($form->isValid()) {
1444
 
1445
 
1446
 
1447
 
1448
                    if (!$userExperience) {
1449
                        $userExperience = new UserExperience();
1450
                        $userExperience->user_id = $userProfile->user_id;
1451
                        $userExperience->user_profile_id = $userProfile->id;
1452
                    }
1453
 
1454
                    $dataPost = (array) $form->getData();
1455
                    $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
1456
                    $companySize = $companySizeMapper->fetchOneByUuid($dataPost['company_size_id']);
1457
 
1458
                    $industryMapper = IndustryMapper::getInstance($this->adapter);
1459
                    $industry = $industryMapper->fetchOneByUuid($dataPost['industry_id']);
1460
 
1461
                    $hydrator = new ObjectPropertyHydrator();
1462
                    $hydrator->hydrate($dataPost, $userExperience);
1463
 
1464
                    $userExperience->company_size_id = $companySize->id;
1465
                    $userExperience->industry_id = $industry->id;
1466
 
1467
                    if ($userExperience->is_current == UserExperience::IS_CURRENT_YES) {
1468
                        $userExperience->to_month = null;
1469
                        $userExperience->to_year = null;
1470
                    }
1471
 
1472
                    if ($userExperience->location_id) {
1473
                        $location = $locationMapper->fetchOne($userExperience->location_id);
1474
                    } else {
1475
                        $location = new Location();
1476
                    }
1477
                    $hydrator->hydrate($dataPost, $location);
1478
 
1479
                    if ($userExperience->location_id) {
1480
                        $this->logger->info('Se actualizo un registro de experiencia del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1481
 
1482
                        $result = $locationMapper->update($location);
1483
                    } else {
1484
                        $this->logger->info('Se agrego un registro de experiencia del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1485
 
1486
                        $result = $locationMapper->insert($location);
1487
 
1488
                        if ($result) {
1489
                            $userExperience->location_id = $location->id;
1490
                        }
1491
                    }
1492
                    if ($result) {
1493
                        if ($userExperience->id) {
1494
                            $result = $userExperienceMapper->update($userExperience);
1495
                        } else {
1496
                            $result =  $userExperienceMapper->insert($userExperience);
1497
                        }
1498
                    }
1499
                } else {
1500
                    $messages = [];
1501
                    $form_messages = (array) $form->getMessages();
1502
                    foreach ($form_messages  as $fieldname => $field_messages) {
1503
                        $messages[$fieldname] = array_values($field_messages);
1504
                    }
1505
 
1506
                    return new JsonModel([
1507
                        'success'   => false,
1508
                        'data'   => $messages,
1509
                    ]);
1510
                }
1511
            }
1512
 
1513
            if ($result) {
1514
                $industryMapper = IndustryMapper::getInstance($this->adapter);
1515
                $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
1516
                $userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);
1517
 
1518
                foreach ($userExperiences  as &$userExperience) {
1519
                    $location = $locationMapper->fetchOne($userExperience->location_id);
1520
                    $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
1521
                    $industry = $industryMapper->fetchOne($userExperience->industry_id);
1522
 
1523
                    $userExperience = [
1524
                        'company' => $userExperience->company,
1525
                        'industry' => $industry,
1526
                        'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ') ',
1527
                        'title' => $userExperience->title,
1528
                        'formatted_address' => $location->formatted_address,
1529
                        'from_year' => $userExperience->from_year,
1530
                        'from_month' => $userExperience->from_month,
1531
                        'to_year' => $userExperience->to_year,
1532
                        'to_month' => $userExperience->to_month,
1533
                        'description' => $userExperience->description,
1534
                        'is_current' => $userExperience->is_current,
350 www 1535
                        'link_edit' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_experience_id' => $userExperience->uuid]),
1536
                        'link_delete' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_experience_id' => $userExperience->uuid]),
1 efrain 1537
                    ];
1538
                }
1539
 
1540
                $response = [
1541
                    'success'   => true,
1542
                    'data' => $userExperiences
1543
                ];
1544
            } else {
1545
                $response = [
1546
                    'success'   => false,
1547
                    'data' => 'ERROR_THERE_WAS_AN_ERROR'
1548
                ];
1549
            }
1550
 
1551
            return new JsonModel($response);
1552
        } else if ($request->isGet() && $operation == 'edit') {
1553
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
1554
            $userExperience = $userExperienceMapper->fetchOneByUuid($user_experience_id);
1555
 
1556
            if (!$userExperience) {
1557
                $response = [
1558
                    'success' => false,
1559
                    'data' => 'ERROR_RECORD_NOT_FOUND'
1560
                ];
1561
            } else if ($userProfile->id != $userExperience->user_profile_id) {
1562
                $response = [
1563
                    'success' => false,
1564
                    'data' => 'ERROR_UNAUTHORIZED'
1565
                ];
1566
            } else {
1567
                $hydrator = new ObjectPropertyHydrator();
1568
                $experience = $hydrator->extract($userExperience);
1569
 
1570
 
1571
                $industryMapper = IndustryMapper::getInstance($this->adapter);
1572
                $industry = $industryMapper->fetchOne($userExperience->industry_id);
1573
 
1574
                $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
1575
                $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
1576
 
1577
                $experience['industry_id'] = $industry->uuid;
1578
                $experience['company_size_id'] = $companySize->uuid;
1579
 
1580
                $locationMapper = LocationMapper::getInstance($this->adapter);
1581
                $location = $locationMapper->fetchOne($userExperience->location_id);
1582
 
1583
                $response = [
1584
                    'success' => true,
1585
                    'data' => [
1586
                        'location' => $hydrator->extract($location),
1587
                        'experience' => $experience
1588
                    ]
1589
                ];
1590
            }
1591
            return new JsonModel($response);
1592
        }
1593
 
1594
        $data = [
1595
            'success' => false,
1596
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1597
        ];
1598
 
1599
 
1600
        return new JsonModel($data);
1601
    }
1602
 
1603
    /**
596 ariadna 1604
     * Maneja la subida y eliminación de la imagen del perfil de usuario.
1605
     * Este método permite:
1606
     * - Subir una nueva imagen de perfil
1607
     * - Eliminar la imagen existente
1608
     * - Actualizar la imagen principal del usuario si el perfil es público
1609
     *
1 efrain 1610
     * @return \Laminas\View\Model\JsonModel
1611
     */
1612
    public function imageAction()
1613
    {
596 ariadna 1614
        // Obtener el usuario actual del sistema
1 efrain 1615
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1616
        $currentUser = $currentUserPlugin->getUser();
1617
 
596 ariadna 1618
        // Obtener parámetros de la ruta: ID del perfil y operación (upload/delete)
1 efrain 1619
        $user_profile_id    = $this->params()->fromRoute('id');
1620
        $operation          = $this->params()->fromRoute('operation');
1621
 
596 ariadna 1622
        // Obtener el perfil de usuario correspondiente
1 efrain 1623
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
596 ariadna 1624
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
1 efrain 1625
 
596 ariadna 1626
        // Validar que el perfil existe
1 efrain 1627
        if (!$userProfile) {
553 stevensc 1628
            return $this->_createSimpleErrorResponse('ERROR_INVALID_PARAMETER');
1 efrain 1629
        }
1630
 
596 ariadna 1631
        // Verificar que el usuario actual es el propietario del perfil
1 efrain 1632
        if ($currentUser->id != $userProfile->user_id) {
553 stevensc 1633
            return $this->_createSimpleErrorResponse('ERROR_UNAUTHORIZED');
1 efrain 1634
        }
1635
 
596 ariadna 1636
        // Procesar solo peticiones POST
1 efrain 1637
        $request = $this->getRequest();
1638
        if ($request->isPost()) {
596 ariadna 1639
            // Inicializar el sistema de almacenamiento
346 www 1640
            $storage = Storage::getInstance($this->config, $this->adapter);
1641
            $target_path = $storage->getPathUser();
596 ariadna 1642
            $user_uuid = $currentUser->uuid;
1643
 
1644
            // Manejar la eliminación de la imagen
1 efrain 1645
            if ($operation == 'delete') {
596 ariadna 1646
                // Registrar la acción en el log
1 efrain 1647
                $this->logger->info('Se borro el image del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1648
 
596 ariadna 1649
                // Si existe una imagen, intentar eliminarla
1 efrain 1650
                if ($userProfile->image) {
553 stevensc 1651
                    if (!$storage->deleteFile($target_path, $user_uuid, $userProfile->image)) {
1652
                        return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1653
                    }
1654
                }
1655
 
596 ariadna 1656
                // Limpiar el campo de imagen y actualizar la base de datos
1 efrain 1657
                $userProfile->image = '';
1658
                if (!$userProfileMapper->updateImage($userProfile)) {
553 stevensc 1659
                    return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1660
                }
596 ariadna 1661
            } else {
1662
                // Manejar la subida de una nueva imagen
1 efrain 1663
                $form = new ImageForm($this->config);
553 stevensc 1664
                $data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
1 efrain 1665
 
1666
                $form->setData($data);
1667
 
1668
                if ($form->isValid()) {
596 ariadna 1669
                    // Configurar el archivo para procesamiento
346 www 1670
                    $storage->setFiles($request->getFiles()->toArray());
596 ariadna 1671
                    if (!$storage->setCurrentFilename('image')) {
553 stevensc 1672
                        return $this->_createSimpleErrorResponse('ERROR_UPLOAD_FILE');
1 efrain 1673
                    }
1674
 
596 ariadna 1675
                    // Obtener dimensiones objetivo para el redimensionamiento
553 stevensc 1676
                    list($target_width_str, $target_height_str) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1677
                    $target_width = (int)$target_width_str;
1678
                    $target_height = (int)$target_height_str;
596 ariadna 1679
 
1680
                    // Generar nombres de archivo únicos
346 www 1681
                    $source_filename    = $storage->getTmpFilename();
1682
                    $filename           = 'user-profile-' . uniqid() . '.png';
596 ariadna 1683
                    $target_filename    = $storage->composePathToFilename(Storage::TYPE_USER, $user_uuid, $filename);
1684
 
1685
                    // Subir y redimensionar la imagen
555 stevensc 1686
                    if (!$storage->uploadImageResize($source_filename, $target_filename, $target_width, $target_height)) {
553 stevensc 1687
                        return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1688
                    }
596 ariadna 1689
 
1690
                    // Eliminar la imagen anterior si existe
346 www 1691
                    if ($userProfile->image) {
553 stevensc 1692
                        if (!$storage->deleteFile($target_path, $user_uuid, $userProfile->image)) {
1693
                            return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
346 www 1694
                        }
1695
                    }
1 efrain 1696
 
596 ariadna 1697
                    // Actualizar el perfil con la nueva imagen
346 www 1698
                    $userProfile->image = $filename;
1 efrain 1699
                    if (!$userProfileMapper->updateImage($userProfile)) {
553 stevensc 1700
                        return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1701
                    }
1702
 
596 ariadna 1703
                    // Si es un perfil público, actualizar también la imagen principal del usuario
1 efrain 1704
                    if ($userProfile->public == UserProfile::PUBLIC_YES) {
596 ariadna 1705
                        $main_user_filename = 'user-' . uniqid() . '.png';
1706
                        $target_filename_main_user = $storage->composePathToFilename(Storage::TYPE_USER, $user_uuid, $main_user_filename);
1707
 
1708
                        // Copiar la imagen del perfil para la imagen principal
1709
                        if (!$storage->copyFile($target_filename, $target_filename_main_user)) {
1710
                            return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
283 www 1711
                        }
596 ariadna 1712
 
1713
                        // Eliminar la imagen principal anterior si existe
346 www 1714
                        if ($currentUser->image) {
553 stevensc 1715
                            if (!$storage->deleteFile($target_path, $user_uuid, $currentUser->image)) {
1716
                                return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
346 www 1717
                            }
1718
                        }
1 efrain 1719
 
596 ariadna 1720
                        // Actualizar la imagen principal del usuario
553 stevensc 1721
                        $currentUser->image = $main_user_filename;
1 efrain 1722
                        $userMapper = UserMapper::getInstance($this->adapter);
553 stevensc 1723
                        if (!$userMapper->updateImage($currentUser)) {
596 ariadna 1724
                            return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
553 stevensc 1725
                        }
1 efrain 1726
                    }
1727
 
596 ariadna 1728
                    // Registrar la actualización en el log
1 efrain 1729
                    $this->logger->info('Se actualizo el image del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1730
                } else {
596 ariadna 1731
                    // Devolver errores de validación del formulario
553 stevensc 1732
                    return $this->_createFormErrorResponse($form);
1 efrain 1733
                }
596 ariadna 1734
            }
1735
 
1736
            // Devolver respuesta exitosa con las URLs actualizadas
333 www 1737
            $storage = Storage::getInstance($this->config, $this->adapter);
1 efrain 1738
            return new JsonModel([
1739
                'success'   => true,
1740
                'data' => [
283 www 1741
                    'user' => $storage->getUserImage($currentUser),
1742
                    'profile' => $storage->getUserProfileImage($currentUser, $userProfile),
1 efrain 1743
                    'update_navbar' =>  $userProfile->public == UserProfile::PUBLIC_YES ? 1 : 0,
1744
                ]
1745
            ]);
596 ariadna 1746
        }
1 efrain 1747
 
596 ariadna 1748
        // Si no es una petición POST, devolver error
553 stevensc 1749
        return $this->_createSimpleErrorResponse('ERROR_METHOD_NOT_ALLOWED');
1 efrain 1750
    }
1751
 
1752
    /**
550 stevensc 1753
     * Handles changing the user profile's cover image.
1754
     * Supports uploading a new cover or deleting the existing one.
1755
     * @return \\Laminas\\View\\Model\\JsonModel
1 efrain 1756
     */
1757
    public function coverAction()
1758
    {
550 stevensc 1759
        // Get current user
1 efrain 1760
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1761
        $currentUser = $currentUserPlugin->getUser();
1762
 
550 stevensc 1763
        // Get parameters from route
1 efrain 1764
        $user_profile_id    = $this->params()->fromRoute('id');
550 stevensc 1765
        $operation          = $this->params()->fromRoute('operation'); // Expected: 'upload' or 'delete'
1 efrain 1766
 
550 stevensc 1767
        // Fetch user profile
1 efrain 1768
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
550 stevensc 1769
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
1 efrain 1770
 
550 stevensc 1771
        // Validate profile existence
1 efrain 1772
        if (!$userProfile) {
550 stevensc 1773
            return $this->_createSimpleErrorResponse('ERROR_INVALID_PARAMETER');
1 efrain 1774
        }
1775
 
550 stevensc 1776
        // Authorize current user against the profile: only the profile owner can modify it
1 efrain 1777
        if ($currentUser->id != $userProfile->user_id) {
550 stevensc 1778
            return $this->_createSimpleErrorResponse('ERROR_UNAUTHORIZED');
1 efrain 1779
        }
1780
 
1781
        $request = $this->getRequest();
1782
        if ($request->isPost()) {
346 www 1783
            $storage = Storage::getInstance($this->config, $this->adapter);
550 stevensc 1784
            $target_path = $storage->getPathUser(); // Base path for user-specific files
556 stevensc 1785
            $user_uuid = $currentUser->uuid;
596 ariadna 1786
 
550 stevensc 1787
            // Handle cover deletion operation
1 efrain 1788
            if ($operation == 'delete') {
1789
                if ($userProfile->cover) {
550 stevensc 1790
                    // Attempt to delete the existing cover file from storage
556 stevensc 1791
                    if (!$storage->deleteFile($target_path, $user_uuid, $userProfile->cover)) {
550 stevensc 1792
                        return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1793
                    }
1794
                }
550 stevensc 1795
                // Log the deletion action
1 efrain 1796
                $this->logger->info('Se borro el cover del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
550 stevensc 1797
                $userProfile->cover = ''; // Clear the cover field in the profile model
596 ariadna 1798
 
550 stevensc 1799
                // Persist the cleared cover information to the database
1800
                if (!$userProfileMapper->updateCover($userProfile)) {
1801
                    // Handle error if database update fails for deletion
1802
                    return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1803
                }
1804
            } else { // Handle cover upload operation
1 efrain 1805
                $form = new CoverForm($this->config);
550 stevensc 1806
                // Merge POST data and FILES data for the form
1807
                $data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
1 efrain 1808
                $form->setData($data);
1809
 
556 stevensc 1810
 
1 efrain 1811
                if ($form->isValid()) {
550 stevensc 1812
                    // Set files in storage and select the 'cover' file by its input name
346 www 1813
                    $storage->setFiles($request->getFiles()->toArray());
550 stevensc 1814
                    if (!$storage->setCurrentFilename('cover')) { // Ensure 'cover' is the correct file input name from CoverForm
1815
                        return $this->_createSimpleErrorResponse('ERROR_UPLOAD_FILE');
1 efrain 1816
                    }
553 stevensc 1817
 
550 stevensc 1818
                    // Prepare for image resize and save: Get target dimensions from config
1819
                    // Example config value: '1200x400'
1820
                    list($target_width_str, $target_height_str) = explode('x', $this->config['leaderslinked.image_sizes.user_cover_size']);
1821
                    $target_width = (int)$target_width_str;
1822
                    $target_height = (int)$target_height_str;
1 efrain 1823
 
550 stevensc 1824
                    $filename           = 'user-cover-' . uniqid() . '.png'; // Generate unique filename for the new cover
1825
                    $source_filename    = $storage->getTmpFilename(); // Temporary path of the uploaded file
556 stevensc 1826
                    $target_filename    = $storage->composePathToFilename(Storage::TYPE_USER, $user_uuid, $filename);
1 efrain 1827
 
550 stevensc 1828
                    // Upload, resize, and save the image
346 www 1829
                    if (!$storage->uploadImageResize($source_filename, $target_filename, $target_width, $target_height)) {
550 stevensc 1830
                        return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1831
                    }
596 ariadna 1832
 
550 stevensc 1833
                    // If an old cover exists, delete it from storage
346 www 1834
                    if ($userProfile->cover) {
556 stevensc 1835
                        if (!$storage->deleteFile($target_path, $user_uuid, $userProfile->cover)) {
550 stevensc 1836
                            // Decide if this is a critical error. Original code returns error.
1837
                            // Consider logging this and proceeding if deletion of old file is non-critical.
1838
                            return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
346 www 1839
                        }
1840
                    }
1 efrain 1841
 
550 stevensc 1842
                    // Update profile model with new cover filename
346 www 1843
                    $userProfile->cover = $filename;
550 stevensc 1844
                    // Persist the new cover information to the database
1 efrain 1845
                    if (!$userProfileMapper->updateCover($userProfile)) {
550 stevensc 1846
                        return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');
1 efrain 1847
                    }
1848
 
550 stevensc 1849
                    // Log successful update
1 efrain 1850
                    $this->logger->info('Se actualizo el cover del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1851
                } else {
550 stevensc 1852
                    // Form is invalid, return validation messages
1853
                    return $this->_createFormErrorResponse($form);
1 efrain 1854
                }
550 stevensc 1855
            } // End of upload/delete specific logic
596 ariadna 1856
 
550 stevensc 1857
            // Successful operation (upload or delete has been handled and persisted)
1858
            // Return success response with the current cover URL (new, or default after delete)
1859
            // The $storage instance from the beginning of the POST block is still valid.
1 efrain 1860
            return new JsonModel([
1861
                'success'   => true,
283 www 1862
                'data' => $storage->getUserProfileCover($currentUser, $userProfile)
1 efrain 1863
            ]);
550 stevensc 1864
        } // End of isPost()
1 efrain 1865
 
550 stevensc 1866
        // If not a POST request, return method not allowed error
1867
        return $this->_createSimpleErrorResponse('ERROR_METHOD_NOT_ALLOWED');
1 efrain 1868
    }
1869
 
1870
    /**
1871
     * Actualización de las habilidades
1872
     * @return \Laminas\View\Model\JsonModel
1873
     */
1874
    public function aptitudeAction()
1875
    {
1876
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1877
        $currentUser = $currentUserPlugin->getUser();
1878
 
1879
        $user_profile_id = $this->params()->fromRoute('id');
1880
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
1881
 
1882
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
1883
        if (!$userProfile) {
1884
            $response = [
1885
                'success' => false,
1886
                'data' => 'ERROR_INVALID_PARAMETER'
1887
            ];
1888
 
1889
            return new JsonModel($response);
1890
        }
1891
 
1892
        if ($currentUser->id != $userProfile->user_id) {
1893
            $response = [
1894
                'success' => false,
1895
                'data' => 'ERROR_UNAUTHORIZED'
1896
            ];
1897
 
1898
            return new JsonModel($response);
1899
        }
1900
 
1901
 
1902
 
1903
        $request = $this->getRequest();
1904
        if ($request->isGet()) {
1905
            $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);
1906
 
1907
 
1908
            $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
1909
            $userAptitudes  = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);
1910
 
1911
            $items = [];
1912
            foreach ($userAptitudes as $userAptitude) {
1913
                $aptitude = $aptitudeMapper->fetchOne($userAptitude->aptitude_id);
1914
                array_push($items, $aptitude->uuid);
1915
            }
1916
 
1917
            $data = [
1918
                'success' => true,
1919
                'data' => $items
1920
            ];
1921
 
1922
            return new JsonModel($data);
1923
        } else if ($request->isPost()) {
1924
 
1925
            $form = new AptitudeForm($this->adapter);
1926
            $dataPost = $request->getPost()->toArray();
1927
 
1928
            $form->setData($dataPost);
1929
 
1930
            if ($form->isValid()) {
1931
                $this->logger->info('Se actualizaron las habilidades del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
1932
 
1933
                $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);
1934
 
1935
 
1936
                $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
1937
                $userAptitudeMapper->deleteByUserProfileId($userProfile->id);
1938
 
1939
                $dataPost = (array) $form->getData();
1940
                $aptitudes = $dataPost['aptitudes'];
1941
                foreach ($aptitudes as $aptitude_uuid) {
1942
 
1943
                    $aptitude = $aptitudeMapper->fetchOneByUuid($aptitude_uuid);
1944
 
1945
 
1946
                    $userAptitude = new UserAptitude();
1947
                    $userAptitude->user_id = $userProfile->user_id;
1948
                    $userAptitude->user_profile_id = $userProfile->id;
1949
                    $userAptitude->aptitude_id =  $aptitude->id;
1950
 
1951
                    $userAptitudeMapper->insert($userAptitude);
1952
                }
1953
 
1954
                $items = [];
1955
 
1956
                $records = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);
1957
                foreach ($records as $record) {
1958
                    $aptitude = $aptitudeMapper->fetchOne($record->aptitude_id);
1959
                    array_push($items,  ['value' => $aptitude->uuid, 'label' => $aptitude->name]);
1960
                }
1961
 
1962
                return new JsonModel([
1963
                    'success'   => true,
1964
                    'data'   => $items
1965
                ]);
1966
            } else {
1967
                $messages = [];
1968
                $form_messages = (array) $form->getMessages();
1969
                foreach ($form_messages  as $fieldname => $field_messages) {
1970
                    $messages[$fieldname] = array_values($field_messages);
1971
                }
1972
 
1973
                return new JsonModel([
1974
                    'success'   => false,
1975
                    'data'   => $messages
1976
                ]);
1977
            }
1978
 
1979
            $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
1980
        }
1981
 
1982
 
1983
        $data = [
1984
            'success' => false,
1985
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1986
        ];
1987
 
1988
 
1989
        return new JsonModel($data);
1990
    }
1991
 
1992
    /**
1993
     * Actualización de las habilidades
1994
     * @return \Laminas\View\Model\JsonModel
1995
     */
1996
    public function hobbyAndInterestAction()
1997
    {
1998
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1999
        $currentUser = $currentUserPlugin->getUser();
2000
 
2001
        $user_profile_id = $this->params()->fromRoute('id');
2002
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
2003
 
2004
        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
2005
        if (!$userProfile) {
2006
            $response = [
2007
                'success' => false,
2008
                'data' => 'ERROR_INVALID_PARAMETER'
2009
            ];
2010
 
2011
            return new JsonModel($response);
2012
        }
2013
 
2014
        if ($currentUser->id != $userProfile->user_id) {
2015
            $response = [
2016
                'success' => false,
2017
                'data' => 'ERROR_UNAUTHORIZED'
2018
            ];
2019
 
2020
            return new JsonModel($response);
2021
        }
2022
 
2023
 
2024
 
2025
        $request = $this->getRequest();
2026
        if ($request->isGet()) {
2027
            $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);
2028
 
2029
 
2030
            $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
2031
            $userHobbyAndInterests  = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);
2032
 
2033
            $items = [];
2034
            foreach ($userHobbyAndInterests as $userHobbyAndInterest) {
2035
                $hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($userHobbyAndInterest->hobbyAndInterest_id);
2036
                array_push($items, $hobbyAndInterest->uuid);
2037
            }
2038
 
2039
            $data = [
2040
                'success' => true,
2041
                'data' => $items
2042
            ];
2043
 
2044
            return new JsonModel($data);
2045
        } else if ($request->isPost()) {
2046
 
2047
            $form = new HobbyAndInterestForm($this->adapter);
2048
            $dataPost = $request->getPost()->toArray();
2049
 
2050
 
2051
            $form->setData($dataPost);
2052
 
2053
            if ($form->isValid()) {
2054
                $this->logger->info('Se actualizaron las habilidades del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
2055
 
2056
                $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);
2057
 
2058
 
2059
                $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
2060
                $userHobbyAndInterestMapper->deleteByUserProfileId($userProfile->id);
2061
 
2062
                $dataPost = (array) $form->getData();
2063
                $hobbyAndInterests = $dataPost['hobbies_and_interests'];
2064
                foreach ($hobbyAndInterests as $hobbyAndInterest_uuid) {
2065
 
2066
                    $hobbyAndInterest = $hobbyAndInterestMapper->fetchOneByUuid($hobbyAndInterest_uuid);
2067
 
2068
 
2069
                    $userHobbyAndInterest = new UserHobbyAndInterest();
2070
                    $userHobbyAndInterest->user_id = $userProfile->user_id;
2071
                    $userHobbyAndInterest->user_profile_id = $userProfile->id;
2072
                    $userHobbyAndInterest->hobby_and_interest_id =  $hobbyAndInterest->id;
2073
 
2074
                    $userHobbyAndInterestMapper->insert($userHobbyAndInterest);
2075
                }
2076
 
2077
                $items = [];
2078
 
2079
                $records = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);
2080
                foreach ($records as $record) {
2081
                    $hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($record->hobby_and_interest_id);
2082
                    array_push($items,  ['value' => $hobbyAndInterest->uuid, 'label' => $hobbyAndInterest->name]);
2083
                }
2084
 
2085
                return new JsonModel([
2086
                    'success'   => true,
2087
                    'data'   => $items
2088
                ]);
2089
            } else {
2090
                $messages = [];
2091
                $form_messages = (array) $form->getMessages();
2092
                foreach ($form_messages  as $fieldname => $field_messages) {
2093
                    $messages[$fieldname] = array_values($field_messages);
2094
                }
2095
 
2096
                return new JsonModel([
2097
                    'success'   => false,
2098
                    'data'   => $messages
2099
                ]);
2100
            }
2101
 
2102
            $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
2103
        }
2104
 
2105
 
2106
        $data = [
2107
            'success' => false,
2108
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2109
        ];
2110
 
2111
 
2112
        return new JsonModel($data);
2113
    }
550 stevensc 2114
 
2115
    // Helper methods for creating standardized JSON responses
2116
    // These can be used across various actions in this controller
2117
 
2118
    /**
2119
     * Creates a standardized JSON error response with a simple message.
2120
     * @param string $errorMessageKey Identifier for the error message (e.g., a translation key or constant).
2121
     * @return JsonModel
2122
     */
551 stevensc 2123
    private function _createSimpleErrorResponse($errorMessageKey)
550 stevensc 2124
    {
2125
        return new JsonModel([
2126
            'success' => false,
596 ariadna 2127
            'data'    => $errorMessageKey
550 stevensc 2128
        ]);
2129
    }
2130
 
2131
    /**
2132
     * Creates a JSON response for form validation errors.
2133
     * Extracts messages from the form and structures them for the client.
551 stevensc 2134
     * @param \Laminas\Form\FormInterface $form The form instance containing validation messages.
550 stevensc 2135
     * @return JsonModel
2136
     */
551 stevensc 2137
    private function _createFormErrorResponse($form)
550 stevensc 2138
    {
2139
        $messages = [];
2140
        $form_messages = (array) $form->getMessages(); // Get all error messages from the form
2141
        foreach ($form_messages as $fieldname => $field_messages_for_field) {
2142
            // Ensure messages for each field are in a simple array format for the frontend
2143
            $messages[$fieldname] = array_values((array)$field_messages_for_field);
2144
        }
2145
        return new JsonModel([
2146
            'success' => false,
2147
            'data'    => $messages
2148
        ]);
2149
    }
1 efrain 2150
}