Proyectos de Subversion LeadersLinked - Services

Rev

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