Rev 557 | Rev 596 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
<?php/**** Controlador: Mis Perfiles**/declare(strict_types=1);namespace LeadersLinked\Controller;use Laminas\Db\Adapter\AdapterInterface;use Laminas\Mvc\Controller\AbstractActionController;use Laminas\Log\LoggerInterface;use Laminas\View\Model\ViewModel;use Laminas\View\Model\JsonModel;use LeadersLinked\Form\UserProfile\SkillForm;use LeadersLinked\Form\UserProfile\LanguageForm;use LeadersLinked\Library\Functions;use LeadersLinked\Mapper\UserProfileMapper;use LeadersLinked\Hydrator\ObjectPropertyHydrator;use LeadersLinked\Model\UserProfile;use LeadersLinked\Mapper\CompanyFollowerMapper;use LeadersLinked\Mapper\LocationMapper;use LeadersLinked\Model\UserLanguage;use LeadersLinked\Mapper\UserLanguageMapper;use LeadersLinked\Mapper\UserSkillMapper;use LeadersLinked\Model\UserSkill;use LeadersLinked\Mapper\UserMapper;use LeadersLinked\Form\UserProfile\ExtendedForm;use LeadersLinked\Form\UserProfile\LocationForm;use LeadersLinked\Model\Location;use LeadersLinked\Form\UserProfile\SocialNetworkForm;use LeadersLinked\Form\UserProfile\EducationForm;use LeadersLinked\Model\UserEducation;use LeadersLinked\Mapper\UserEducationMapper;use LeadersLinked\Mapper\DegreeMapper;use LeadersLinked\Form\UserProfile\ExperienceForm;use LeadersLinked\Mapper\AptitudeMapper;use LeadersLinked\Mapper\LanguageMapper;use LeadersLinked\Mapper\UserAptitudeMapper;use LeadersLinked\Mapper\UserExperienceMapper;use LeadersLinked\Mapper\IndustryMapper;use LeadersLinked\Mapper\CompanySizeMapper;use LeadersLinked\Model\UserExperience;use LeadersLinked\Mapper\ConnectionMapper;use LeadersLinked\Form\UserProfile\ImageForm;use LeadersLinked\Form\UserProfile\CoverForm;use LeadersLinked\Mapper\SkillMapper;use LeadersLinked\Form\MyProfiles\CreateForm;use LeadersLinked\Form\UserProfile\AptitudeForm;use LeadersLinked\Model\UserAptitude;use LeadersLinked\Form\UserProfile\HobbyAndInterestForm;use LeadersLinked\Mapper\HobbyAndInterestMapper;use LeadersLinked\Mapper\UserHobbyAndInterestMapper;use LeadersLinked\Model\UserHobbyAndInterest;use LeadersLinked\Library\Storage;class MyProfilesController extends AbstractActionController{/**** @var \Laminas\Db\Adapter\AdapterInterface*/private $adapter;/**** @var \LeadersLinked\Cache\CacheInterface*/private $cache;/**** @var \Laminas\Log\LoggerInterface*/private $logger;/**** @var array*/private $config;/**** @var \Laminas\Mvc\I18n\Translator*/private $translator;/**** @param \Laminas\Db\Adapter\AdapterInterface $adapter* @param \LeadersLinked\Cache\CacheInterface $cache* @param \Laminas\Log\LoggerInterface LoggerInterface $logger* @param array $config* @param \Laminas\Mvc\I18n\Translator $translator*/public function __construct($adapter, $cache, $logger, $config, $translator){$this->adapter = $adapter;$this->cache = $cache;$this->logger = $logger;$this->config = $config;$this->translator = $translator;}/**** Generación del listado de perfiles* {@inheritDoc}* @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()*/public function indexAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$request = $this->getRequest();if ($request->isGet()) {$search = Functions::sanitizeFilterString($this->params()->fromQuery('search'));$acl = $this->getEvent()->getViewModel()->getVariable('acl');$allowView = $acl->isAllowed($currentUser->usertype_id, 'profile/view');$allowEdit = $acl->isAllowed($currentUser->usertype_id, 'profile/my-profiles/edit');$allowDelete = $acl->isAllowed($currentUser->usertype_id, 'profile/my-profiles/delete');$storage = Storage::getInstance($this->config, $this->adapter);$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$records = $userProfileMapper->fetchAllByUserIdAndSearch($currentUser->id, $search);$items = [];foreach ($records as $record) {$item = ['id' => $record->id,'name' => $record->name,'image' => $storage->getUserProfileImage($currentUser, $record),'link_view' => $allowView ? $this->url()->fromRoute('profile/view', ['id' => $record->uuid]) : '','link_edit' => $allowEdit ? $this->url()->fromRoute('profile/my-profiles/edit', ['id' => $record->uuid]) : '','link_delete' => $allowDelete && $record->public == UserProfile::PUBLIC_NO ? $this->url()->fromRoute('profile/my-profiles/delete', ['id' => $record->uuid]) : '',];array_push($items, $item);}$response = ['success' => true,'data' => $items];return new JsonModel($response);} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}/**** Agregar un nuevo perfil* @return \Laminas\View\Model\JsonModel*/public function addAction(){$request = $this->getRequest();if ($request->isPost()) {$form = new CreateForm();$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$userProfile = new UserProfile();$hydrator->hydrate($dataPost, $userProfile);$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$userProfile->uuid = Functions::genUUID();$userProfile->user_id = $currentUser->id;$userProfile->public = \LeadersLinked\Model\UserProfile::PUBLIC_NO;$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$result = $userProfileMapper->insert($userProfile);if ($result) {$this->logger->info('Se agrego el perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_RECORD_ADDED'];} else {$data = ['success' => false,'data' => $userProfile->getError()];}return new JsonModel($data);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}} else {$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}return new JsonModel($data);}/**** Borrar un perfil excepto el público* @return \Laminas\View\Model\JsonModel*/public function deleteAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$request = $this->getRequest();$id = $this->params()->fromRoute('id');if (!$id) {// Use helper for consistencyreturn $this->_createSimpleErrorResponse('ERROR_INVALID_PARAMETER');}$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($id);if (!$userProfile) {// Use helper for consistencyreturn $this->_createSimpleErrorResponse('ERROR_RECORD_NOT_FOUND');}// Authorize: Check if current user owns the profileif ($currentUser->id != $userProfile->user_id) {// Use helper for consistencyreturn $this->_createSimpleErrorResponse('ERROR_UNAUTHORIZED');}// Prevent deletion of the public profileif ($userProfile->public == UserProfile::PUBLIC_YES) {// Use helper for consistencyreturn $this->_createSimpleErrorResponse('ERROR_PUBLIC_PROFILE');}if ($request->isPost()) {$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathUser();$user_uuid = $currentUser->uuid; // Assuming user UUID matches profile owner's UUID for path// Attempt to delete associated files first$image_deleted = true;if ($userProfile->image) {$image_deleted = $storage->deleteFile($target_path, $user_uuid, $userProfile->image);if (!$image_deleted) {$this->logger->err("Failed to delete profile image file: {$target_path}/{$user_uuid}/{$userProfile->image}", ['user_id' => $userProfile->user_id]);// Decide if this is a critical error. Proceeding with DB deletion for now.}}$cover_deleted = true;if ($userProfile->cover) {$cover_deleted = $storage->deleteFile($target_path, $user_uuid, $userProfile->cover);if (!$cover_deleted) {$this->logger->err("Failed to delete profile cover file: {$target_path}/{$user_uuid}/{$userProfile->cover}", ['user_id' => $userProfile->user_id]);// Decide if this is a critical error. Proceeding with DB deletion for now.}}// Delete the database record$result = $userProfileMapper->delete($userProfile);if ($result) {$this->logger->info('Se borro el perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);// Success response$data = ['success' => true,'data' => 'LABEL_RECORD_DELETED'];} else {// Use helper for DB error$data = $this->_createSimpleErrorResponse($userProfileMapper->getError() ?: 'ERROR_THERE_WAS_AN_ERROR');}} else {// Use helper for method error$data = $this->_createSimpleErrorResponse('ERROR_METHOD_NOT_ALLOWED');}// Return JsonModel for all pathsreturn $data instanceof JsonModel ? $data : new JsonModel($data);}/*** Presenta el perfil con las opciónes de edición de cada sección* @return \Laminas\Http\Response|\Laminas\View\Model\ViewModel|\Laminas\View\Model\JsonModel*/public function editAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$flashMessenger = $this->plugin('FlashMessenger');$request = $this->getRequest();$id = $this->params()->fromRoute('id');if (!$id) {$flashMessenger->addErrorMessage('ERROR_INVALID_PARAMETER');return $this->redirect()->toRoute('dashboard');}$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($id);if (!$userProfile) {$flashMessenger->addErrorMessage('ERROR_RECORD_NOT_FOUND');return $this->redirect()->toRoute('dashboard');}if ($currentUser->id != $userProfile->user_id) {$flashMessenger->addErrorMessage('ERROR_UNAUTHORIZED');return $this->redirect()->toRoute('dashboard');}$sandbox = $this->config['leaderslinked.runmode.sandbox'];if ($sandbox) {$google_map_key = $this->config['leaderslinked.google_map.sandbox_api_key'];} else {$google_map_key = $this->config['leaderslinked.google_map.production_api_key'];}if ($request->isGet()) {if ($userProfile->location_id) {$locationMapper = LocationMapper::getInstance($this->adapter);$location = $locationMapper->fetchOne($userProfile->location_id);$formattedAddress = $location->formatted_address;$country = $location->country;} else {$formattedAddress = '';$country = '';}$userMapper = UserMapper::getInstance($this->adapter);$user = $userMapper->fetchOne($userProfile->user_id);$userLanguages = [];$languageMapper = LanguageMapper::getInstance($this->adapter);$userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);$records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$language = $languageMapper->fetchOne($record->language_id);$userLanguages[$language->id] = $language->name;}$locationMapper = LocationMapper::getInstance($this->adapter);$degreeMapper = DegreeMapper::getInstance($this->adapter);$userEducationMapper = UserEducationMapper::getInstance($this->adapter);$userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);foreach ($userEducations as &$userEducation) {$location = $locationMapper->fetchOne($userEducation->location_id);$degree = $degreeMapper->fetchOne($userEducation->degree_id);$userEducation = ['university' => $userEducation->university,'degree' => $degree->name,'field_of_study' => $userEducation->field_of_study,'grade_or_percentage' => $userEducation->grade_or_percentage,'formatted_address' => $location->formatted_address,'from_year' => $userEducation->from_year,'to_year' => $userEducation->to_year,'description' => $userEducation->description,'link_edit' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_education_id' => $userEducation->uuid]),'link_delete' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_education_id' => $userEducation->uuid]),];}$industryMapper = IndustryMapper::getInstance($this->adapter);$companySizeMapper = CompanySizeMapper::getInstance($this->adapter);$userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);$userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);foreach ($userExperiences as &$userExperience) {$location = $locationMapper->fetchOne($userExperience->location_id);$companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);$industry = $industryMapper->fetchOne($userExperience->industry_id);$userExperience = ['company' => $userExperience->company,'industry' => $industry->name,'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ')','title' => $userExperience->title,'formatted_address' => $location->formatted_address,'from_year' => $userExperience->from_year,'from_month' => $userExperience->from_month,'to_year' => $userExperience->to_year,'to_month' => $userExperience->to_month,'description' => $userExperience->description,'is_current' => $userExperience->is_current,'link_edit' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_experience_id' => $userExperience->uuid]),'link_delete' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_experience_id' => $userExperience->uuid])];}$userAptitudes = [];$aptitudeMapper = AptitudeMapper::getInstance($this->adapter);$userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);$records = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$aptitude = $aptitudeMapper->fetchOne($record->aptitude_id);if ($aptitude) {$userAptitudes[$aptitude->uuid] = $aptitude->name;}}$userHobbiesAndInterests = [];$hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);$userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);$records = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($record->hobby_and_interest_id);if ($hobbyAndInterest) {$userHobbiesAndInterests[$hobbyAndInterest->uuid] = $hobbyAndInterest->name;}}$userSkills = [];$userSkillMapper = UserSkillMapper::getInstance($this->adapter);$skillMapper = SkillMapper::getInstance($this->adapter);$records = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$skill = $skillMapper->fetchOne($record->skill_id);$userSkills[$skill->uuid] = $skill->name;}$companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);$following = $companyFollowerMapper->getCountFollowing($user->id);$connectionMapper = ConnectionMapper::getInstance($this->adapter);$follower = $connectionMapper->fetchTotalConnectionByUser($user->id);$image_size_cover = $this->config['leaderslinked.image_sizes.user_cover_upload'];$image_size_profile = $this->config['leaderslinked.image_sizes.user_upload'];$storage = Storage::getInstance($this->config, $this->adapter);$data = ['following' => $following,'follower' => $follower,'user_id' => $user->id,'user_uuid' => $user->uuid,'full_name' => trim($user->first_name . ' ' . $user->last_name),'user_profile_id' => $userProfile->id,'user_profile_uuid' => $userProfile->uuid,'image' => $storage->getUserProfileImage($currentUser, $userProfile),'cover' => $storage->getUserProfileCover($currentUser, $userProfile),'overview' => $userProfile->description,'facebook' => $userProfile->facebook,'instagram' => $userProfile->instagram,'twitter' => $userProfile->twitter,'formatted_address' => $formattedAddress,'country' => $country,'user_skills' => $userSkills,'user_languages' => $userLanguages,'user_educations' => $userEducations,'user_experiences' => $userExperiences,'user_aptitudes' => $userAptitudes,'user_hobbies_and_interests' => $userHobbiesAndInterests,'image_size_cover' => $image_size_cover,'image_size_profile' => $image_size_profile,'link_extended' => $this->url()->fromRoute('profile/my-profiles/extended', ['id' => $userProfile->uuid] ),'link_image_upload' => $this->url()->fromRoute('profile/my-profiles/image', ['id' => $userProfile->uuid, 'operation' => 'upload']),'link_image_delete' => $this->url()->fromRoute('profile/my-profiles/image', ['id' => $userProfile->uuid, 'operation' => 'delete']),'link_cover_upload' => $this->url()->fromRoute('profile/my-profiles/cover', ['id' => $userProfile->uuid, 'operation' => 'upload']),'link_cover_delete' => $this->url()->fromRoute('profile/my-profiles/cover', ['id' => $userProfile->uuid, 'operation' => 'delete']),'link_experience_add' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'add']),'link_education_add' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'add']),'link_language' => $this->url()->fromRoute('profile/my-profiles/language', ['id' => $userProfile->uuid]),'link_location' => $this->url()->fromRoute('profile/my-profiles/location', ['id' => $userProfile->uuid]),'link_skill' => $this->url()->fromRoute('profile/my-profiles/skill', ['id' => $userProfile->uuid] ),'link_social_network' => $this->url()->fromRoute('profile/my-profiles/social-network', ['id' => $userProfile->uuid]),'link_aptitude' => $this->url()->fromRoute('profile/my-profiles/aptitude', ['id' => $userProfile->uuid] ),'link_hobby_and_interest' => $this->url()->fromRoute('profile/my-profiles/hobby-and-interest', ['id' => $userProfile->uuid]),];return new JsonModel($data);} else {$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}return new JsonModel($data);}/*** Actualización de las habilidades* @return \Laminas\View\Model\JsonModel*/public function skillAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isGet()) {$skillMapper = SkillMapper::getInstance($this->adapter);$userSkillMapper = UserSkillMapper::getInstance($this->adapter);$userSkills = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);$items = [];foreach ($userSkills as $userSkill) {$skill = $skillMapper->fetchOne($userSkill->skill_id);array_push($items, $skill->uuid);}$data = ['success' => true,'data' => $items];return new JsonModel($data);} else if ($request->isPost()) {$form = new SkillForm($this->adapter);$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$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()]);$skillMapper = SkillMapper::getInstance($this->adapter);$userSkillMapper = UserSkillMapper::getInstance($this->adapter);$userSkillMapper->deleteByUserProfileId($userProfile->id);$dataPost = (array) $form->getData();$skills = $dataPost['skills'];foreach ($skills as $skill_uuid) {$skill = $skillMapper->fetchOneByUuid($skill_uuid);$userSkill = new UserSkill();$userSkill->user_id = $userProfile->user_id;$userSkill->user_profile_id = $userProfile->id;$userSkill->skill_id = $skill->id;$userSkillMapper->insert($userSkill);}$items = [];$records = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$skill = $skillMapper->fetchOne($record->skill_id);array_push($items, ['value' => $skill->uuid, 'label' => $skill->name]);}return new JsonModel(['success' => true,'data' => $items]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de los idiomas* @return \Laminas\View\Model\JsonModel*/public function languageAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isGet()) {$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()]);$userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);$languages = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);$items = [];foreach ($languages as $language) {array_push($items, $language->language_id);}$data = ['success' => true,'data' => $items];return new JsonModel($data);} else if ($request->isPost()) {$form = new LanguageForm($this->adapter);$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$languageMapper = LanguageMapper::getInstance($this->adapter);$userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);$userLanguageMapper->deleteByUserProfileId($userProfile->id);$dataPost = (array) $form->getData();$languages = $dataPost['languages'];foreach ($languages as $language_id) {$language = $languageMapper->fetchOne($language_id);$userLanguage = new UserLanguage();$userLanguage->user_id = $userProfile->user_id;$userLanguage->user_profile_id = $userProfile->id;$userLanguage->language_id = $language->id;$userLanguageMapper->insert($userLanguage);}$items = [];$records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$language = $languageMapper->fetchOne($record->language_id);array_push($items, ['value' => $language->id, 'label' => $language->name]);}return new JsonModel(['success' => true,'data' => $items]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de la descripción y cualquier otro campo extendido del perfil a futuro* @return \Laminas\View\Model\JsonModel*/public function extendedAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isGet()) {$data = ['success' => true,'data' => ['description' => $userProfile->description,]];return new JsonModel($data);} else if ($request->isPost()) {$form = new ExtendedForm();$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$hydrator->hydrate($dataPost, $userProfile);$userProfileMapper->updateExtended($userProfile);$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()]);return new JsonModel(['success' => true,'data' => ['description' => $userProfile->description,]]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de la ubucación* @return \Laminas\View\Model\JsonModel*/public function locationAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isPost()) {$form = new LocationForm();$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$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()]);$dataPost = (array) $form->getData();$location = new Location();$hydrator = new ObjectPropertyHydrator();$hydrator->hydrate($dataPost, $location);$location->id = $userProfile->location_id ? $userProfile->location_id : null;$locationMapper = LocationMapper::getInstance($this->adapter);if ($userProfile->location_id) {$result = $locationMapper->update($location);} else {$result = $locationMapper->insert($location);if ($result) {$userProfile->location_id = $location->id;$userProfileMapper->updateLocation($userProfile);}}if ($result) {if ($userProfile->public == UserProfile::PUBLIC_YES) {$currentUser->location_id = $location->id;$userMapper = UserMapper::getInstance($this->adapter);$userMapper->updateLocation($currentUser);}$response = ['success' => true,'data' => ['formatted_address' => $location->formatted_address,'country' => $location->country,]];} else {$response = ['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR'];}return new JsonModel($response);} else {return new JsonModel(['success' => false,'data' => 'ERROR_PLACED_AUTOCOMPLETE_DOES_NOT_CONTAIN_GEOMETRY']);}}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de las redes sociales* @return \Laminas\View\Model\JsonModel*/public function socialNetworkAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isGet()) {$data = ['success' => true,'data' => ['facebook' => $userProfile->facebook,'instagram' => $userProfile->instagram,'twitter' => $userProfile->twitter]];return new JsonModel($data);} else if ($request->isPost()) {$form = new SocialNetworkForm();$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$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()]);$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$hydrator->hydrate($dataPost, $userProfile);$userProfileMapper->updateSocialNetwork($userProfile);return new JsonModel(['success' => true,'data' => ['facebook' => $userProfile->facebook,'instagram' => $userProfile->instagram,'twitter' => $userProfile->twitter]]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de los registros de estudios realizados* @return \Laminas\View\Model\JsonModel*/public function educationAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$user_education_id = $this->params()->fromRoute('user_education_id');$operation = $this->params()->fromRoute('operation');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isPost()) {$userEducationMapper = UserEducationMapper::getInstance($this->adapter);if ($operation == 'delete' || $operation == 'edit') {$userEducation = $userEducationMapper->fetchOneByUuid($user_education_id);if (!$userEducation) {$response = ['success' => false,'data' => 'ERROR_RECORD_NOT_FOUND'];return new JsonModel($response);} else if ($userProfile->id != $userEducation->user_profile_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}} else {$userEducation = null;}$locationMapper = LocationMapper::getInstance($this->adapter);if ($operation == 'delete') {$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()]);$result = $userEducationMapper->delete($userEducation);if ($result) {$locationMapper->delete($userEducation->location_id);}} else {$form = new EducationForm($this->adapter);$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {if (!$userEducation) {$userEducation = new UserEducation();$userEducation->user_id = $userProfile->user_id;$userEducation->user_profile_id = $userProfile->id;}$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$hydrator->hydrate($dataPost, $userEducation);$degreeMapper = DegreeMapper::getInstance($this->adapter);$degree = $degreeMapper->fetchOneByUuid($dataPost['degree_id']);$userEducation->degree_id = $degree->id;if ($userEducation->location_id) {$location = $locationMapper->fetchOne($userEducation->location_id);} else {$location = new Location();}$hydrator->hydrate($dataPost, $location);if ($userEducation->location_id) {$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()]);$result = $locationMapper->update($location);} else {$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()]);$result = $locationMapper->insert($location);if ($result) {$userEducation->location_id = $location->id;}}if ($result) {if ($userEducation->id) {$result = $userEducationMapper->update($userEducation);} else {$result = $userEducationMapper->insert($userEducation);}}} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}}if ($result) {$degreeMapper = DegreeMapper::getInstance($this->adapter);$userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);foreach ($userEducations as &$userEducation) {$location = $locationMapper->fetchOne($userEducation->location_id);$degree = $degreeMapper->fetchOne($userEducation->degree_id);$userEducation = ['university' => $userEducation->university,'degree' => $degree->name,'field_of_study' => $userEducation->field_of_study,'grade_or_percentage' => $userEducation->grade_or_percentage,'formatted_address' => $location->formatted_address,'from_year' => $userEducation->from_year,'to_year' => $userEducation->to_year,'description' => $userEducation->description,'link_edit' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_education_id' => $userEducation->uuid]),'link_delete' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_education_id' => $userEducation->uuid]),];}$response = ['success' => true,'data' => $userEducations];} else {$response = ['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR'];}return new JsonModel($response);} else if ($request->isGet() && $operation == 'edit') {$userEducationMapper = UserEducationMapper::getInstance($this->adapter);$userEducation = $userEducationMapper->fetchOneByUuid($user_education_id);if (!$userEducation) {$response = ['success' => false,'data' => 'ERROR_RECORD_NOT_FOUND'];} else if ($userProfile->id != $userEducation->user_profile_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];} else {$locationMapper = LocationMapper::getInstance($this->adapter);$location = $locationMapper->fetchOne($userEducation->location_id);$hydrator = new ObjectPropertyHydrator();$education = $hydrator->extract($userEducation);$degree = $degreeMapper = DegreeMapper::getInstance($this->adapter);$degree = $degreeMapper->fetchOne($education['degree_id']);$education['degree_id'] = $degree->uuid;$location = ['address1' => $location->address1,'address2' => $location->address2,'city1' => $location->city1,'city2' => $location->city2,'country' => $location->country,'formatted_address' => $location->formatted_address,'latitude' => $location->latitude,'longitude' => $location->longitude,'postal_code' => $location->postal_code,'state' => $location->state,];$response = ['success' => true,'data' => ['location' => $location,'education' => $education,]];}return new JsonModel($response);}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de los registros de la experiencia laboral* @return \Laminas\View\Model\JsonModel*/public function experienceAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$user_experience_id = $this->params()->fromRoute('user_experience_id');$operation = $this->params()->fromRoute('operation');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isPost()) {$userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);if ($operation == 'delete' || $operation == 'edit') {$userExperience = $userExperienceMapper->fetchOneByUuid($user_experience_id);if (!$userExperience) {$response = ['success' => false,'data' => 'ERROR_RECORD_NOT_FOUND'];return new JsonModel($response);} else if ($userProfile->id != $userExperience->user_profile_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}} else {$userExperience = null;}$locationMapper = LocationMapper::getInstance($this->adapter);if ($operation == 'delete') {$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()]);$result = $userExperienceMapper->delete($userExperience);if ($result) {$locationMapper->delete($userExperience->location_id);}} else {$form = new ExperienceForm($this->adapter);$dataPost = $request->getPost()->toArray();$dataPost['is_current'] = isset($dataPost['is_current']) ? $dataPost['is_current'] : UserExperience::IS_CURRENT_NO;if ($dataPost['is_current'] == UserExperience::IS_CURRENT_YES) {$dataPost['to_month'] = 12;$dataPost['to_year'] = date('Y');}$form->setData($dataPost);if ($form->isValid()) {if (!$userExperience) {$userExperience = new UserExperience();$userExperience->user_id = $userProfile->user_id;$userExperience->user_profile_id = $userProfile->id;}$dataPost = (array) $form->getData();$companySizeMapper = CompanySizeMapper::getInstance($this->adapter);$companySize = $companySizeMapper->fetchOneByUuid($dataPost['company_size_id']);$industryMapper = IndustryMapper::getInstance($this->adapter);$industry = $industryMapper->fetchOneByUuid($dataPost['industry_id']);$hydrator = new ObjectPropertyHydrator();$hydrator->hydrate($dataPost, $userExperience);$userExperience->company_size_id = $companySize->id;$userExperience->industry_id = $industry->id;if ($userExperience->is_current == UserExperience::IS_CURRENT_YES) {$userExperience->to_month = null;$userExperience->to_year = null;}if ($userExperience->location_id) {$location = $locationMapper->fetchOne($userExperience->location_id);} else {$location = new Location();}$hydrator->hydrate($dataPost, $location);if ($userExperience->location_id) {$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()]);$result = $locationMapper->update($location);} else {$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()]);$result = $locationMapper->insert($location);if ($result) {$userExperience->location_id = $location->id;}}if ($result) {if ($userExperience->id) {$result = $userExperienceMapper->update($userExperience);} else {$result = $userExperienceMapper->insert($userExperience);}}} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages,]);}}if ($result) {$industryMapper = IndustryMapper::getInstance($this->adapter);$companySizeMapper = CompanySizeMapper::getInstance($this->adapter);$userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);foreach ($userExperiences as &$userExperience) {$location = $locationMapper->fetchOne($userExperience->location_id);$companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);$industry = $industryMapper->fetchOne($userExperience->industry_id);$userExperience = ['company' => $userExperience->company,'industry' => $industry,'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ') ','title' => $userExperience->title,'formatted_address' => $location->formatted_address,'from_year' => $userExperience->from_year,'from_month' => $userExperience->from_month,'to_year' => $userExperience->to_year,'to_month' => $userExperience->to_month,'description' => $userExperience->description,'is_current' => $userExperience->is_current,'link_edit' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_experience_id' => $userExperience->uuid]),'link_delete' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_experience_id' => $userExperience->uuid]),];}$response = ['success' => true,'data' => $userExperiences];} else {$response = ['success' => false,'data' => 'ERROR_THERE_WAS_AN_ERROR'];}return new JsonModel($response);} else if ($request->isGet() && $operation == 'edit') {$userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);$userExperience = $userExperienceMapper->fetchOneByUuid($user_experience_id);if (!$userExperience) {$response = ['success' => false,'data' => 'ERROR_RECORD_NOT_FOUND'];} else if ($userProfile->id != $userExperience->user_profile_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];} else {$hydrator = new ObjectPropertyHydrator();$experience = $hydrator->extract($userExperience);$industryMapper = IndustryMapper::getInstance($this->adapter);$industry = $industryMapper->fetchOne($userExperience->industry_id);$companySizeMapper = CompanySizeMapper::getInstance($this->adapter);$companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);$experience['industry_id'] = $industry->uuid;$experience['company_size_id'] = $companySize->uuid;$locationMapper = LocationMapper::getInstance($this->adapter);$location = $locationMapper->fetchOne($userExperience->location_id);$response = ['success' => true,'data' => ['location' => $hydrator->extract($location),'experience' => $experience]];}return new JsonModel($response);}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Cambio de la imagen del image del perfil* @return \Laminas\View\Model\JsonModel*/public function imageAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$operation = $this->params()->fromRoute('operation');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_INVALID_PARAMETER');}// Authorize: Check if current user owns the profileif ($currentUser->id != $userProfile->user_id) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_UNAUTHORIZED');}$request = $this->getRequest();if ($request->isPost()) {$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathUser();$user_uuid = $currentUser->uuid; // Assuming user UUID for pathif ($operation == 'delete') {$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()]);if ($userProfile->image) {// Attempt deletionif (!$storage->deleteFile($target_path, $user_uuid, $userProfile->image)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}}// Clear image field and update DB$userProfile->image = '';if (!$userProfileMapper->updateImage($userProfile)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}} else { // Handle upload$form = new ImageForm($this->config);$data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());$form->setData($data);if ($form->isValid()) {$storage->setFiles($request->getFiles()->toArray());// *** FIX: Use correct input field name 'image' ***if (!$storage->setCurrentFilename('image')) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_UPLOAD_FILE');}// Prepare for resize and savelist($target_width_str, $target_height_str) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);$target_width = (int)$target_width_str;$target_height = (int)$target_height_str;$source_filename = $storage->getTmpFilename();$filename = 'user-profile-' . uniqid() . '.png';$target_filename = $storage->composePathToFilename(Storage::TYPE_USER, $user_uuid, $filename);// Upload, resize, saveif (!$storage->uploadImageResize($source_filename, $target_filename, $target_width, $target_height)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}// Delete old image if existsif ($userProfile->image) {if (!$storage->deleteFile($target_path, $user_uuid, $userProfile->image)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}}// Update profile model and DB$userProfile->image = $filename;if (!$userProfileMapper->updateImage($userProfile)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}// Special handling: If this is the PUBLIC profile, also update the main user imageif ($userProfile->public == UserProfile::PUBLIC_YES) {$main_user_filename = 'user-' . uniqid() . '.png'; // Use different name for safety?// $source_filename_for_copy = $target_filename; // The newly saved profile image$target_filename_main_user = $storage->composePathToFilename(Storage::TYPE_USER, $user_uuid, $main_user_filename);// Copy the *newly processed* profile image to be the main user imageif (!$storage->copyFile($target_filename, $target_filename_main_user)) { // Source is the *new* profile image// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}// Delete the old main user image if it existsif ($currentUser->image) {if (!$storage->deleteFile($target_path, $user_uuid, $currentUser->image)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}}// Update current user model and DB$currentUser->image = $main_user_filename;$userMapper = UserMapper::getInstance($this->adapter);if (!$userMapper->updateImage($currentUser)) {// Use helperreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}}$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()]);} else {// Use helper for form errorsreturn $this->_createFormErrorResponse($form);}} // End upload/delete logic// Success response (for both upload and delete)// Instantiate storage again just to be safe, though the instance from above should be okay$storage = Storage::getInstance($this->config, $this->adapter);return new JsonModel(['success' => true,'data' => ['user' => $storage->getUserImage($currentUser),'profile' => $storage->getUserProfileImage($currentUser, $userProfile),'update_navbar' => $userProfile->public == UserProfile::PUBLIC_YES ? 1 : 0,]]);} // End isPost()// Method not allowed if not POST// Use helperreturn $this->_createSimpleErrorResponse('ERROR_METHOD_NOT_ALLOWED');}/*** Handles changing the user profile's cover image.* Supports uploading a new cover or deleting the existing one.* @return \\Laminas\\View\\Model\\JsonModel*/public function coverAction(){// Get current user$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();// Get parameters from route$user_profile_id = $this->params()->fromRoute('id');$operation = $this->params()->fromRoute('operation'); // Expected: 'upload' or 'delete'// Fetch user profile$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);// Validate profile existenceif (!$userProfile) {return $this->_createSimpleErrorResponse('ERROR_INVALID_PARAMETER');}// Authorize current user against the profile: only the profile owner can modify itif ($currentUser->id != $userProfile->user_id) {return $this->_createSimpleErrorResponse('ERROR_UNAUTHORIZED');}$request = $this->getRequest();if ($request->isPost()) {$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathUser(); // Base path for user-specific files$user_uuid = $currentUser->uuid;// Handle cover deletion operationif ($operation == 'delete') {if ($userProfile->cover) {// Attempt to delete the existing cover file from storageif (!$storage->deleteFile($target_path, $user_uuid, $userProfile->cover)) {return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}}// Log the deletion action$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()]);$userProfile->cover = ''; // Clear the cover field in the profile model// Persist the cleared cover information to the databaseif (!$userProfileMapper->updateCover($userProfile)) {// Handle error if database update fails for deletionreturn $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}} else { // Handle cover upload operation$form = new CoverForm($this->config);// Merge POST data and FILES data for the form$data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());$form->setData($data);if ($form->isValid()) {// Set files in storage and select the 'cover' file by its input name$storage->setFiles($request->getFiles()->toArray());if (!$storage->setCurrentFilename('cover')) { // Ensure 'cover' is the correct file input name from CoverFormreturn $this->_createSimpleErrorResponse('ERROR_UPLOAD_FILE');}// Prepare for image resize and save: Get target dimensions from config// Example config value: '1200x400'list($target_width_str, $target_height_str) = explode('x', $this->config['leaderslinked.image_sizes.user_cover_size']);$target_width = (int)$target_width_str;$target_height = (int)$target_height_str;$filename = 'user-cover-' . uniqid() . '.png'; // Generate unique filename for the new cover$source_filename = $storage->getTmpFilename(); // Temporary path of the uploaded file$target_filename = $storage->composePathToFilename(Storage::TYPE_USER, $user_uuid, $filename);// Upload, resize, and save the imageif (!$storage->uploadImageResize($source_filename, $target_filename, $target_width, $target_height)) {return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}// If an old cover exists, delete it from storageif ($userProfile->cover) {if (!$storage->deleteFile($target_path, $user_uuid, $userProfile->cover)) {// Decide if this is a critical error. Original code returns error.// Consider logging this and proceeding if deletion of old file is non-critical.return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}}// Update profile model with new cover filename$userProfile->cover = $filename;// Persist the new cover information to the databaseif (!$userProfileMapper->updateCover($userProfile)) {return $this->_createSimpleErrorResponse('ERROR_THERE_WAS_AN_ERROR');}// Log successful update$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()]);} else {// Form is invalid, return validation messagesreturn $this->_createFormErrorResponse($form);}} // End of upload/delete specific logic// Successful operation (upload or delete has been handled and persisted)// Return success response with the current cover URL (new, or default after delete)// The $storage instance from the beginning of the POST block is still valid.return new JsonModel(['success' => true,'data' => $storage->getUserProfileCover($currentUser, $userProfile)]);} // End of isPost()// If not a POST request, return method not allowed errorreturn $this->_createSimpleErrorResponse('ERROR_METHOD_NOT_ALLOWED');}/*** Actualización de las habilidades* @return \Laminas\View\Model\JsonModel*/public function aptitudeAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isGet()) {$aptitudeMapper = AptitudeMapper::getInstance($this->adapter);$userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);$userAptitudes = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);$items = [];foreach ($userAptitudes as $userAptitude) {$aptitude = $aptitudeMapper->fetchOne($userAptitude->aptitude_id);array_push($items, $aptitude->uuid);}$data = ['success' => true,'data' => $items];return new JsonModel($data);} else if ($request->isPost()) {$form = new AptitudeForm($this->adapter);$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$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()]);$aptitudeMapper = AptitudeMapper::getInstance($this->adapter);$userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);$userAptitudeMapper->deleteByUserProfileId($userProfile->id);$dataPost = (array) $form->getData();$aptitudes = $dataPost['aptitudes'];foreach ($aptitudes as $aptitude_uuid) {$aptitude = $aptitudeMapper->fetchOneByUuid($aptitude_uuid);$userAptitude = new UserAptitude();$userAptitude->user_id = $userProfile->user_id;$userAptitude->user_profile_id = $userProfile->id;$userAptitude->aptitude_id = $aptitude->id;$userAptitudeMapper->insert($userAptitude);}$items = [];$records = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$aptitude = $aptitudeMapper->fetchOne($record->aptitude_id);array_push($items, ['value' => $aptitude->uuid, 'label' => $aptitude->name]);}return new JsonModel(['success' => true,'data' => $items]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}$userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}/*** Actualización de las habilidades* @return \Laminas\View\Model\JsonModel*/public function hobbyAndInterestAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$user_profile_id = $this->params()->fromRoute('id');$userProfileMapper = UserProfileMapper::getInstance($this->adapter);$userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);if (!$userProfile) {$response = ['success' => false,'data' => 'ERROR_INVALID_PARAMETER'];return new JsonModel($response);}if ($currentUser->id != $userProfile->user_id) {$response = ['success' => false,'data' => 'ERROR_UNAUTHORIZED'];return new JsonModel($response);}$request = $this->getRequest();if ($request->isGet()) {$hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);$userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);$userHobbyAndInterests = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);$items = [];foreach ($userHobbyAndInterests as $userHobbyAndInterest) {$hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($userHobbyAndInterest->hobbyAndInterest_id);array_push($items, $hobbyAndInterest->uuid);}$data = ['success' => true,'data' => $items];return new JsonModel($data);} else if ($request->isPost()) {$form = new HobbyAndInterestForm($this->adapter);$dataPost = $request->getPost()->toArray();$form->setData($dataPost);if ($form->isValid()) {$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()]);$hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);$userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);$userHobbyAndInterestMapper->deleteByUserProfileId($userProfile->id);$dataPost = (array) $form->getData();$hobbyAndInterests = $dataPost['hobbies_and_interests'];foreach ($hobbyAndInterests as $hobbyAndInterest_uuid) {$hobbyAndInterest = $hobbyAndInterestMapper->fetchOneByUuid($hobbyAndInterest_uuid);$userHobbyAndInterest = new UserHobbyAndInterest();$userHobbyAndInterest->user_id = $userProfile->user_id;$userHobbyAndInterest->user_profile_id = $userProfile->id;$userHobbyAndInterest->hobby_and_interest_id = $hobbyAndInterest->id;$userHobbyAndInterestMapper->insert($userHobbyAndInterest);}$items = [];$records = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);foreach ($records as $record) {$hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($record->hobby_and_interest_id);array_push($items, ['value' => $hobbyAndInterest->uuid, 'label' => $hobbyAndInterest->name]);}return new JsonModel(['success' => true,'data' => $items]);} else {$messages = [];$form_messages = (array) $form->getMessages();foreach ($form_messages as $fieldname => $field_messages) {$messages[$fieldname] = array_values($field_messages);}return new JsonModel(['success' => false,'data' => $messages]);}$userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);}$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}// Helper methods for creating standardized JSON responses// These can be used across various actions in this controller/*** Creates a standardized JSON error response with a simple message.* @param string $errorMessageKey Identifier for the error message (e.g., a translation key or constant).* @return JsonModel*/private function _createSimpleErrorResponse($errorMessageKey){return new JsonModel(['success' => false,'data' => $errorMessageKey]);}/*** Creates a JSON response for form validation errors.* Extracts messages from the form and structures them for the client.* @param \Laminas\Form\FormInterface $form The form instance containing validation messages.* @return JsonModel*/private function _createFormErrorResponse($form){$messages = [];$form_messages = (array) $form->getMessages(); // Get all error messages from the formforeach ($form_messages as $fieldname => $field_messages_for_field) {// Ensure messages for each field are in a simple array format for the frontend$messages[$fieldname] = array_values((array)$field_messages_for_field);}return new JsonModel(['success' => false,'data' => $messages]);}}