Proyectos de Subversion LeadersLinked - Services

Rev

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