Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 3916 | Rev 6849 | 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\Cache\Storage\Adapter\AbstractAdapter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;

use LeadersLinked\Mapper\UserProfileMapper;
use LeadersLinked\Mapper\CompanyFollowerMapper;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\UserLanguageMapper;
use LeadersLinked\Mapper\UserSkillMapper;

use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\UserEducationMapper;
use LeadersLinked\Mapper\DegreeMapper;
use LeadersLinked\Mapper\UserExperienceMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\CompanySizeMapper;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\UserBlockedMapper;
use LeadersLinked\Model\Connection;
use LeadersLinked\Model\Network;
use LeadersLinked\Mapper\ProfileVisitMapper;
use LeadersLinked\Model\ProfileVisit;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Model\User;
use Laminas\Db\Sql\Expression;
use LeadersLinked\Mapper\LanguageMapper;
use LeadersLinked\Mapper\SkillMapper;
use LeadersLinked\Mapper\AptitudeMapper;
use LeadersLinked\Mapper\UserAptitudeMapper;
use LeadersLinked\Mapper\HobbyAndInterestMapper;
use LeadersLinked\Mapper\UserHobbyAndInterestMapper;


class ProfileController extends AbstractActionController
{
    /**
     *
     * @var AdapterInterface
     */
    private $adapter;
    
    
    /**
     *
     * @var AbstractAdapter
     */
    private $cache;
    
    /**
     *
     * @var  LoggerInterface
     */
    private $logger;

    
    /**
     *
     * @var array
     */
    private $config;
    
    /**
     *
     * @param AdapterInterface $adapter
     * @param AbstractAdapter $cache
     * @param LoggerInterface $logger
     * @param array $config
     */
    public function __construct($adapter, $cache , $logger,  $config)
    {
        $this->adapter      = $adapter;
        $this->cache        = $cache;
        $this->logger       = $logger;
        $this->config       = $config;

    }
    
    /**
     * 
     * Generación del listado de perfiles
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $this->layout()->setTemplate('layout/layout.phtml');
        $viewModel = new ViewModel();
        $viewModel->setTemplate('leaders-linked/profile/index.phtml');
        return $viewModel ;
        
    }
    
   
    /**
     * 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 viewAction()
    {
        
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork= $currentNetworkPlugin->getNetwork();
        
        
        $request = $this->getRequest();
        if($request->isGet()) {
        
            
            $flashMessenger = $this->plugin('FlashMessenger');
            
    
            $id = $this->params()->fromRoute('id');
            if(!$id) {
                $flashMessenger->addErrorMessage('ERROR_INVALID_PARAMETER');
                return $this->redirect()->toRoute('dashboard');
            }
            
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            
            $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
            if($user) {
                $userProfile = $userProfileMapper->fetchOnePublicByUserId($user->id);
            } else {    
                $userProfile = $userProfileMapper->fetchOneByUuid($id);
                
                if($userProfile) {
                    $user = $userMapper->fetchOne($userProfile->user_id);
                    
                    if($user && $currentUser->network_id != $user->network_id) {
                        $response = [
                            'success' => false,
                            'data' => 'ERROR_UNAUTHORIZED'
                        ];
                        
                        return new JsonModel($response);
                    }
                }
            }
            
            if(!$userProfile) {
                $flashMessenger->addErrorMessage('ERROR_RECORD_NOT_FOUND');
                return $this->redirect()->toRoute('dashboard');
            }
            

    
            $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
            $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($userProfile->user_id, $currentUser->id);
            
            if($userBlocked) {
                $flashMessenger->addErrorMessage('ERROR_UNAUTHORIZED');
                return $this->redirect()->toRoute('dashboard');
            }
            
            if($currentUser->id != $userProfile->user_id) {
                
                $visited_on = date('Y-m-d');;
                $profileVisitMapper = ProfileVisitMapper::getInstance($this->adapter);
                $profileVisit = $profileVisitMapper->fetchOneByVisitorIdAndVisitedIdAndVisitedOn($currentUser->id, $userProfile->user_id, $visited_on);
                if(!$profileVisit) {
                    $profileVisit = new ProfileVisit();
                    $profileVisit->user_profile_id = $userProfile->id;
                    $profileVisit->visited_id = $userProfile->user_id;
                    $profileVisit->visitor_id = $currentUser->id;
                    $profileVisit->visited_on = date('Y-m-d');
                    $profileVisitMapper->insert($profileVisit);
                }
            }
    
            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 = '';
            }
            
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $userProfile->user_id);
            
            $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,
                ];
            }
               
            /*
            $industries = [];
            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $records = $industryMapper->fetchAllActive();
            foreach($records as $record)
            {
                $industries[$record->uuid] = $record->name;
            }
                
            $companySizes = [];
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
            $records = $companySizeMapper->fetchAllActive();
            foreach($records as $record)
            {
                $companySizes[$record->uuid] = $record->name . ' ('.$record->minimum_no_of_employee . '-' . $record->maximum_no_of_employee .')';
            }
            */    
            
            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
            
            
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
            $userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);
                
            foreach($userExperiences  as &$userExperience)
            {
                $industry = $industryMapper->fetchOne($userExperience->industry_id);
                $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
                
                
                $location = $locationMapper->fetchOne($userExperience->location_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,
                ];
            }
             
            $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 = [];
            $skillMapper = SkillMapper::getInstance($this->adapter);
            $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
            $records  = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
            foreach($records as $record)
            {
                $skill = $skillMapper->fetchOne($record->skill_id);
                if($skill) {
                    $userSkills[$skill->uuid] = $skill->name;
                }
            }
            
            

                
            
            if($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
            
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $total_connections = $connectionMapper->fetchTotalConnectionByUser($user->id);
        
                $request_connection = 0;
                if($connection) {
                    if($connection->status == Connection::STATUS_REJECTED || $connection->status == Connection::STATUS_CANCELLED) {
                        $request_connection = 1;
                    }
                } else {
                    $request_connection = 1;
                }
                
                
                
                $common_connection = count($connectionMapper->fetchAllCommonConnectionsUserIdByUser1ReturnIds($currentUser->id, $userProfile->user_id));
            }
            
            
            $profileVisitMapper = ProfileVisitMapper::getInstance($this->adapter);
            $views          = $profileVisitMapper->getTotalByVisitedId( $userProfile->user_id );
            

            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            
            if($isJson) {
            
                $data = [
                    'user_id'                       => $user->uuid,
                    'user_uuid'                     => ($user->uuid),
                    'full_name'                     => trim($user->first_name . ' ' . $user->last_name),
                    'user_profile_id'               => $userProfile->id,
                    'user_profile_uuid'             => $userProfile->uuid,
                    'image'                         => $this->url()->fromRoute('storage',['code' => $user->uuid, 'type' => 'user-profile', 'filename' => $user->image]),
                    'cover'                         => $this->url()->fromRoute('storage',['code' => $user->uuid, 'type' => 'user-cover', 'filename' => $userProfile->cover]),
                    '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,
                    'views'                         => $views,
                    'show_contact'                  => $user->id != $currentUser->id,
                    'link_inmail'                   => $this->url()->fromRoute('inmail',['id' => $user->uuid ]),
                ];
                
                
                if($currentNetwork->default == Network::DEFAULT_YES) {
                    
                    $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
                    $data['following'] = $companyFollowerMapper->getCountFollowing($user->id);
                    $data['view_following'] = 1;
                } else {
                    $data['following'] = 0;
                    $data['view_following'] = 0;
                }
                
                
                if($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
                    $data['total_connections']  = $total_connections;
                    $data['view_total_connections']  = 1;
                    $data['request_connection'] = $request_connection;
                    $data['common_connection']  = $common_connection;
                    $data['link_cancel']        = $connection && $connection->status == Connection::STATUS_SENT ? $this->url()->fromRoute('connection/delete',['id' => $user->uuid ]) :  $this->url()->fromRoute('connection/cancel',['id' => $user->uuid]);
                    $data['link_request']       = $request_connection ? $this->url()->fromRoute('connection/request',['id' => $user->uuid ]) : '';
                } else {
                    $data['total_connections']  = 0;
                    $data['view_total_connections']  = 0;
                    $data['request_connection'] = 0;
                    $data['common_connection']  = 0;
                    $data['link_cancel']        = '';
                    $data['link_request']       = '';
                }
                
                return new JsonModel($data);
                
            } else {
             
                if($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
                    $data = [
                        'total_connections'             => $total_connections,
                        'view_total_connections'        => 1,
                        'user_id'                       => $user->uuid,
                        'user_uuid'                     => ($user->uuid),
                        'full_name'                     => trim($user->first_name . ' ' . $user->last_name),
                        'user_profile_id'               => $userProfile->id,
                        'user_profile_uuid'             => $userProfile->uuid,
                        'image'                         => $userProfile->image,
                        'cover'                         => $userProfile->cover,
                        '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,
                        'show_contact'                  => $user->id != $currentUser->id,
                        'request_connection'            => $request_connection,
                        'link_cancel'                   => $connection && $connection->status == Connection::STATUS_SENT ? $this->url()->fromRoute('connection/delete',['id' => $user->uuid ]) :  $this->url()->fromRoute('connection/cancel',['id' => $user->uuid]),
                        'link_request'                  => $request_connection ? $this->url()->fromRoute('connection/request',['id' => $user->uuid ]) : '',
                        'link_inmail'                   => $this->url()->fromRoute('inmail',['id' => $user->uuid ]),
                    ];
                } else {
                    $data = [
                        'total_connections'             => 0,
                        'view_total_connections'        => 0,
                        'user_id'                       => $user->uuid,
                        'user_uuid'                     => ($user->uuid),
                        'full_name'                     => trim($user->first_name . ' ' . $user->last_name),
                        'user_profile_id'               => $userProfile->id,
                        'user_profile_uuid'             => $userProfile->uuid,
                        'image'                         => $userProfile->image,
                        'cover'                         => $userProfile->cover,
                        '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,
                        'show_contact'                  => $user->id != $currentUser->id,
                        'request_connection'            => 0,
                        'link_cancel'                   => '',
                        'link_request'                  => '',
                        'link_inmail'                   => $this->url()->fromRoute('inmail',['id' => $user->uuid ]),
                    ];
                }
                
                if($currentNetwork->default == Network::DEFAULT_YES) {
                    
                    $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
                    $data['following'] = $companyFollowerMapper->getCountFollowing($user->id);
                    $data['view_following'] = 1;
                } else {
                    $data['following'] = 0;
                    $data['view_following'] = 0;
                }
                
                
            
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/profile/view.phtml');
                $viewModel->setVariables($data);
                return $viewModel ;
            }
        }
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
        
        
        
    }
    
    public function peopleViewedProfileAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            if($isJson) {
                $page = (int) $this->params()->fromQuery('page');
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                $mapper = QueryMapper::getInstance($this->adapter);
                $select = $mapper->getSql()->select();
                $select->columns(['visitor_id' => new Expression('DISTINCT(visitor_id)')]);
                $select->from(['p' => ProfileVisitMapper::_TABLE]);
                $select->join(['u' => UserMapper::_TABLE], 'p.visitor_id = u.id ', ['uuid', 'first_name', 'last_name', 'image']);
                $select->where->equalTo('p.visited_id', $currentUser->id)->and->equalTo('u.status', User::STATUS_ACTIVE);
                
                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }
                $select->order('first_name','last_name');
                
                //echo $select->getSqlString($this->adapter->platform); exit;
                
                $dbSelect = new DbSelect($select, $this->adapter);
                $paginator = new Paginator($dbSelect);
                $paginator->setCurrentPageNumber($page ? $page : 1);
                $paginator->setItemCountPerPage(10);
                
                $items = [];
                $records = $paginator->getCurrentItems();
                
                foreach($records as $record)
                {
                    
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]),
                        'link_inmail'   => $this->url()->fromRoute('inmail', ['id' => $record['uuid']  ]),
                    ];
                    
                    array_push($items, $item);
                }
                
                $response = [
                    'success' => true,
                    'data' => [
                        'total' => [
                            'count' => $paginator->getTotalItemCount(),
                            'pages' => $paginator->getPages()->pageCount,
                        ],
                        'current' => [
                            'items'    => $items,
                            'page'     => $paginator->getCurrentPageNumber(),
                            'count'    => $paginator->getCurrentItemCount(),
                        ]
                    ]
                ];
                
                
                
                return new JsonModel($response);
            } else {
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/profile/people-viewed-profile.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    
}