Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6001 | Rev 6069 | 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\Library\Functions;
use LeadersLinked\Library\Image;
use LeadersLinked\Mapper\KnowledgeAreaCategoryMapper;
use LeadersLinked\Mapper\KnowledgeAreaCategoryUserMapper;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Model\KnowledgeAreaCategory;
use LeadersLinked\Model\KnowledgeAreaCategoryUser;
use LeadersLinked\Form\KnowledgeArea\KnowledgeAreaCreateForm;
use LeadersLinked\Mapper\KnowledgeAreaContentMapper;
use LeadersLinked\Model\KnowledgeAreaContent;
use LeadersLinked\Form\KnowledgeArea\KnowledgeAreaEditForm;
use LeadersLinked\Mapper\CommentMapper;
use LeadersLinked\Form\KnowledgeArea\CommentForm;
use LeadersLinked\Mapper\UtilMapper;
use LeadersLinked\Model\Comment;
use LeadersLinked\Mapper\ContentReactionMapper;
use LeadersLinked\Model\ContentReaction;

class KnowledgeAreaController 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()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            $isJson = false;
            
            $headers  = $request->getHeaders();
            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) {
                
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/edit');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/delete');
                $allowView = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/view');
                
                
                
                $category_filter_id = filter_var($this->params()->fromQuery('category_id'), FILTER_SANITIZE_STRING);
                $search = filter_var($this->params()->fromQuery('search'), FILTER_SANITIZE_STRING);
                $page   = intval($this->params()->fromQuery('start', 1), 10);
         
                $order_field        = 'added_on';
                $order_direction    = 'asc';
                $records_x_page     = 12;
                

                
                $category_with_edition_ids = [];
                $category_ids = [];
                $categories = [];
                
                
                $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
                $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);
                foreach($records as $record)
                {
                    if($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
                        
                        array_push($category_with_edition_ids, $record->category_id);
                    }
                    
                    array_push($category_ids, $record->category_id);
                }
                
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
                
                if( $category_ids) {
                    $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
                    foreach($records as $record)
                    {
                        if($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
                            
                            $categories[ $record->id  ] = [
                                'uuid' => $record->uuid,
                                'name' => $record->name,
                            ];
                            
                        }
                    }
                }
                
                $records =  $knowledgeAreaCategoryMapper->fetchAllPublicByNetworkId($currentNetwork->id);
                foreach($records as $record)
                {
                    if($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
                        
                        if(!isset($categories[ $record->id ])) {
                            
                            $categories[ $record->id  ] = [
                                'uuid' => $record->uuid,
                                'name' => $record->name,
                            ];
                        }
                        
                    }
                }
                

                
                $categories = array_values($categories);
                usort($categories, function($a, $b) {
                    return $a['name'] <=> $b['name'];
                });
                
                
                if($category_filter_id) {
                    $categoryFilter = $knowledgeAreaCategoryMapper->fetchOneByUuid($category_filter_id);
                    if($categoryFilter) {
                        $category_ids = [ $categoryFilter->id ];
                    } else {
                        $category_ids = [];
                    }
                }
                
                $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
                $paginator = $knowledgeAreaContentMapper->fetchAllDataTableByCategoryIds($category_ids,  $search, $page, $records_x_page, $order_field, $order_direction);
    
              
                $items = [];
                $records = $paginator->getCurrentItems();
                foreach($records as $record)
                {
                    

                    
                    $description = strip_tags($record->description);
                    if(strlen($description) > 120) {
                        $description = substr($description, 0, 120) . '...';
                    }
                    
                    $item = [
                        'image' => $this->url()->fromRoute('storage', ['type' => 'knowledge-area', 'code' => $record->uuid,  'filename' => $record->image]),
                        'title' => $record->title,
                        'description' => $description,
                        'category' => $categories[$record->category_id]['name'],
                        'link_view' => $allowView ?  $this->url()->fromRoute('knowledge-area/view', ['id' => $record->uuid ]) : '',
                        
                    ];
                    

                    
                    if(in_array($record->category_id, $category_with_edition_ids)) {
                        $item['link_edit'] = $allowEdit ?  $this->url()->fromRoute('knowledge-area/edit', ['id' => $record->uuid ]) : '';
                        $item['link_delete'] = $allowDelete ? $this->url()->fromRoute('knowledge-area/delete', ['id' => $record->uuid ]) : '';
                    }
                    
                    array_push($items, $item);
                }
                
                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount(),
                        'page' => $paginator->getCurrentPageNumber(),
                        'total_pages' => $paginator->getPageRange()
                    ]
                ]);
            } else {
            
            
                $category_with_edition_ids = [];
                $category_ids = [];
                
                
                $categories = [];
                
                
                $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
                $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);            
                foreach($records as $record)
                {
                    if($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
                        
                        array_push($category_with_edition_ids, $record->category_id);
                    }
                    
                    array_push($category_ids, $record->category_id);
                }
                
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
                
                if( $category_ids) {
                    $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
                    foreach($records as $record)
                    {
                        if($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
                            
                            $categories[ $record->id  ] = [
                               'uuid' => $record->uuid, 
                               'name' => $record->name,
                            ];
                            
                        }
                    }
                }
                
                $records =  $knowledgeAreaCategoryMapper->fetchAllPublicByNetworkId($currentNetwork->id);
                foreach($records as $record)
                {
                    if($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
                        
                        if(!isset($categories[ $record->id ])) {
                            
                            $categories[ $record->id  ] = [
                                'uuid' => $record->uuid,
                                'name' => $record->name,
                            ];
                        }
                        
                    }
                }
                
                
                $image_size = $this->config['leaderslinked.image_sizes.knowledge_area'];
                
        
                $categories = array_values($categories);
                usort($categories, function($a, $b) {
                   return $a['name'] <=> $b['name']; 
                });
    
                
                $formAdd = new KnowledgeAreaCreateForm($this->adapter, $category_with_edition_ids);
                $formEdit = new KnowledgeAreaEditForm($this->adapter, $category_with_edition_ids);
    
    
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/knowledge-area/index.phtml');
                $viewModel->setVariables([
                    'categories' => $categories, 
                    'formAdd' => $formAdd,
                    'formEdit' => $formEdit,
                    'image_size' => $image_size,
                    'content_edit' => count($category_with_edition_ids) > 0,
                ]);
                return $viewModel ;
            }
            
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function addAction()
    {
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
        $currentUser        = $currentUserPlugin->getUser();
        
        $request            = $this->getRequest();
        
        if($request->isPost()) {
            $category_with_edition_ids = [];
            $category_ids = [];
            
            
            $categories = [];
            
            
            $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
            $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);
            foreach($records as $record)
            {
                if($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
                    
                    array_push($category_with_edition_ids, $record->category_id);
                }
                
                array_push($category_ids, $record->category_id);
            }
            
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
            
            if( $category_ids) {
                $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
                foreach($records as $record)
                {
                    if($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
                        
                        $categories[ $record->id  ] = [
                            'uuid' => $record->uuid,
                            'name' => $record->name,
                        ];
                        
                    }
                }
            }

            
            
            $categories = array_values($categories);
            usort($categories, function($a, $b) {
                return $a['name'] <=> $b['name'];
            });
                
         
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
            $form = new KnowledgeAreaCreateForm($this->adapter, $category_with_edition_ids);
            
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
                $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOneByUuid($dataPost['category_id']);
                
                
                $knowledgeAreaContent = new KnowledgeAreaContent();
                $knowledgeAreaContent->network_id = $knowledgeAreaCategory->network_id;
                $knowledgeAreaContent->company_id = $knowledgeAreaCategory->company_id;
                $knowledgeAreaContent->category_id = $knowledgeAreaCategory->id;
                $knowledgeAreaContent->user_id = $currentUser->id;
                $knowledgeAreaContent->title = $dataPost['title'];
                $knowledgeAreaContent->description = $dataPost['description'];
                $knowledgeAreaContent->link = $dataPost['link'];
                
                $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
                if($knowledgeAreaContentMapper->insert($knowledgeAreaContent)) {
                    $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOne($knowledgeAreaContent->id);
                    
                    $target_size = $this->config['leaderslinked.image_sizes.knowledge_area'];
                    list($target_width, $target_height) = explode('x', $target_size);
                    
                    
                    $target_path = $this->config['leaderslinked.fullpath.knowledge_area']  . $knowledgeAreaContent->uuid;
                    if(!file_exists($target_path)) {
                        mkdir($target_path, 0755, true);
                    }
                    
                    
                    $files = $this->getRequest()->getFiles()->toArray();
                    
                    
                    if(isset($files['image']) && empty($files['image']['error'])) {
                        $tmp_filename  = $files['image']['tmp_name'];
                        $filename      = explode('.',  $files['image']['name']);
                        $filename       = Functions::normalizeString(uniqid() . '-' . $filename[0].'.png');
                        
                        $crop_to_dimensions = true;
                        
                        
                        if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
                            $knowledgeAreaContent->image = $filename;
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
                        }
                    }
                    
                    if(isset($files['attachment']) && empty($files['attachment']['error'])) {
                        $tmp_filename   = $files['attachment']['tmp_name'];
                        $filename       = Functions::normalizeString($files['attachment']['name']);
                        $destination      = $target_path  . DIRECTORY_SEPARATOR . $filename;
                        
                        
                        if(move_uploaded_file($tmp_filename, $destination)) {
                            $knowledgeAreaContent->attachment = $filename;
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
                        }
                    }
                    
                    
                    $this->logger->info('Se agrego el contenido ' . $knowledgeAreaContent->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $knowledgeAreaContentMapper->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);
    }
    
    public function deleteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();

        
        $request    = $this->getRequest();
        $id         = $this->params()->fromRoute('id');
        
        
        
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
        if(!$knowledgeAreaContent) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        
        
        $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
        $knowledgeAreaCategoryUser = $knowledgeAreaCategoryUserMapper->fetchOneByCategoryIdAndUserId($knowledgeAreaContent->category_id, $currentUser->id);
        
        $ok = false;
        if($knowledgeAreaCategoryUser) {
            
            if($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_EDITOR) {
                $ok = $knowledgeAreaContent->user_id == $currentUser->id;
            }
            
            if($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR) {
                $ok = true;
            }
            
        }
        
        if(!$ok) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_KNOWLEDGE_AREA_YOU_DO_NOT_HAVE_PERMISSION'
            ]);
            
        }
        
        if($request->isPost()) {
            
            $result =  $knowledgeAreaContentMapper->delete($knowledgeAreaContent);
            if($result) {
                $this->logger->info('Se borro el cotenido : ' .  $knowledgeAreaContent->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                if($knowledgeAreaContent->image) {
                    
                    $target_path = $this->config['leaderslinked.fullpath.knowledge_area']  . $knowledgeAreaContent->uuid;
                    if(file_exists($target_path)) {
                        Functions::rmDirRecursive($target_path);
                    }
                    
                }
                
                $data = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {
                
                $data = [
                    'success'   => false,
                    'data'      => $knowledgeAreaContentMapper->getError()
                ];
                
                return new JsonModel($data);
            }
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    
    public function editAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        
        $request    = $this->getRequest();
        $id    = $this->params()->fromRoute('id');
        
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
        if(!$knowledgeAreaContent) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        
        
        $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
        $knowledgeAreaCategoryUser = $knowledgeAreaCategoryUserMapper->fetchOneByCategoryIdAndUserId($knowledgeAreaContent->category_id, $currentUser->id);
        
        $ok = false;
        if($knowledgeAreaCategoryUser) {
            
            if($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_EDITOR) {
                $ok = $knowledgeAreaContent->user_id == $currentUser->id;
            }
            
            if($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR) {
                $ok = true;
            }
            
        }
        
        if(!$ok) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_KNOWLEDGE_AREA_YOU_DO_NOT_HAVE_PERMISSION'
            ]);
            
        }
        
        if($request->isGet()) {
            
            
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
            $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOne( $knowledgeAreaContent->category_id );
            
            
            
            $data = [
                'success' => true,
                'data' => [
                    'category_id' => $knowledgeAreaCategory->uuid,
                    'title' => $knowledgeAreaContent->title,
                    'description' => $knowledgeAreaContent->description,
                    'link' => $knowledgeAreaContent->link,
                ]
            ];
            
            return new JsonModel($data);
        }
        else if($request->isPost()) {
            $category_with_edition_ids = [];
            $category_ids = [];
            
            
            $categories = [];
            
            
            $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
            $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);
            foreach($records as $record)
            {
                if($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
                    
                    array_push($category_with_edition_ids, $record->category_id);
                }
                
                array_push($category_ids, $record->category_id);
            }
            
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
            
            if( $category_ids) {
                $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
                foreach($records as $record)
                {
                    if($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
                        
                        $categories[ $record->id  ] = [
                            'uuid' => $record->uuid,
                            'name' => $record->name,
                        ];
                        
                    }
                }
            }
            
            
            
            $categories = array_values($categories);
            usort($categories, function($a, $b) {
                return $a['name'] <=> $b['name'];
            });
                
                
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
            $form = new KnowledgeAreaEditForm($this->adapter, $category_with_edition_ids);
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
                $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOneByUuid( $dataPost['category_id'] );
                
                
                
                $knowledgeAreaContent->category_id = $knowledgeAreaCategory->id ;
                $knowledgeAreaContent->title = $dataPost['title'];
                $knowledgeAreaContent->description = $dataPost['description'];
                

                if($knowledgeAreaContentMapper->update($knowledgeAreaContent)) {
                    
                    $target_size = $this->config['leaderslinked.image_sizes.knowledge_area'];
                    list($target_width, $target_height) = explode('x', $target_size);
                    
                    
                    $target_path = $this->config['leaderslinked.fullpath.knowledge_area']  . $knowledgeAreaContent->uuid;
                    if(!file_exists($target_path)) {
                        mkdir($target_path, 0755, true);
                    }
                    
                    
                    $files = $this->getRequest()->getFiles()->toArray();
                    
                    
                    if(isset($files['image']) && empty($files['image']['error'])) {
                        
                        if($knowledgeAreaContent->image) {
                            @unlink($target_path  . DIRECTORY_SEPARATOR . $knowledgeAreaContent->image);
                        }
                        
                        $tmp_filename  = $files['image']['tmp_name'];
                        $filename      = explode('.',  $files['image']['name']);
                        $filename       = Functions::normalizeString(uniqid() . '-' . $filename[0].'.png');
                        
                        $crop_to_dimensions = true;
                        
                        
                        if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
                            $knowledgeAreaContent->image = $filename;
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
                        }
                    }
                    
                    if(isset($files['attachment']) && empty($files['attachment']['error'])) {
                        $tmp_filename   = $files['attachment']['tmp_name'];
                        $filename       = Functions::normalizeString($files['attachment']['name']);
                        $destination      = $target_path  . DIRECTORY_SEPARATOR . $filename;
                        
                        if($knowledgeAreaContent->attachment) {
                            @unlink($target_path  . DIRECTORY_SEPARATOR . $knowledgeAreaContent->attachment);
                        }
                        
                        
                        if(move_uploaded_file($tmp_filename, $destination)) {
                            $knowledgeAreaContent->attachment = $filename;
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
                        }
                    }
                    
                    
                    $this->logger->info('Se edito el contenido ' . $knowledgeAreaContent->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $knowledgeAreaContentMapper->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);
    }
    
    
    public function viewAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        
        $request    = $this->getRequest();
        $id    = $this->params()->fromRoute('id');
        
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
        if(!$knowledgeAreaContent) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        
        
        
        if($request->isGet()) {
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
            $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOne( $knowledgeAreaContent->category_id );
            
            
            
            $ok = false;
            if($knowledgeAreaCategory->privacy == KnowledgeAreaCategory::PRIVACY_COMPANY) {
                
                $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
                $knowledgeAreaCategoryUser = $knowledgeAreaCategoryUserMapper->fetchOneByCategoryIdAndUserId($knowledgeAreaContent->category_id, $currentUser->id);
                
                
                if($knowledgeAreaCategoryUser) {
                    $ok = true;
                }
            }
            if($knowledgeAreaCategory->privacy == KnowledgeAreaCategory::PRIVACY_PUBLIC) {
                $ok = true;
            }
            
            if(!$ok) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_KNOWLEDGE_AREA_YOU_DO_NOT_HAVE_PERMISSION'
                ]);
                
            }
            
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $contentReaction = $contentReactionMapper->fetchOneByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id);
            
            
            
            $this->layout()->setTemplate('layout/layout.phtml');
            $viewModel = new ViewModel();
            $viewModel->setTemplate('leaders-linked/knowledge-area/view.phtml');
            $viewModel->setVariables([
                'category' => $knowledgeAreaCategory->name,
                'title' => $knowledgeAreaContent->title,
                'description' => $knowledgeAreaContent->description,
                'link' => $knowledgeAreaContent->link,
                'image' =>  $this->url()->fromRoute('storage', ['type' => 'knowledge-area', 'code' =>  $knowledgeAreaContent->uuid,  'filename' =>  $knowledgeAreaContent->image]),
                'attachment' =>  $knowledgeAreaContent->attachment ? $this->url()->fromRoute('storage', ['type' => 'knowledge-area', 'code' =>  $knowledgeAreaContent->uuid,  'filename' =>  $knowledgeAreaContent->attachment]) : '',
                'reaction' => $contentReaction ? $contentReaction->reaction : '',
                'routeComments' => $this->url()->fromRoute('knowledge-area/comments', ['id' => $knowledgeAreaContent->uuid]),
                'routeCommentAdd' => $this->url()->fromRoute('knowledge-area/comments/add', ['id' => $knowledgeAreaContent->uuid]),
                'routeSaveReaction' => $this->url()->fromRoute('knowledge-area/save-reaction', ['id' => $knowledgeAreaContent->uuid]),
                'routeDeleteReaction' => $this->url()->fromRoute('knowledge-area/delete-reaction', ['id' => $knowledgeAreaContent->uuid]),
            ]);
            return $viewModel ;
            


        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }

    
    public function addCommentAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        
        $id = $this->params()->fromRoute('id');
        
        $request = $this->getRequest();
        if ($request->isPost()) {
            
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
            if(!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
                ]);
            }
            
            

            
            $dataPost = $request->getPost()->toArray();
            $form = new CommentForm();
            $form->setData($dataPost);
            
            if ($form->isValid()) {
                $utilMapper = UtilMapper::getInstance($this->adapter);
                $now = $utilMapper->getDatebaseNow();
                
                $currentUserPlugin = $this->plugin('currentUserPlugin');
                $currentUser = $currentUserPlugin->getUser();
                
                $dataPost = (array) $form->getData();
                
                
                
                $comment = new Comment();
                $comment->network_id = $currentUser->network_id;
                $comment->comment = $dataPost['comment'];
                $comment->user_id = $currentUser->id;
                $comment->knowledge_area_id = $knowledgeAreaContent->id;
                $comment->relational = Comment::RELATIONAL_KNOWLEDGE_AREA;
                
                $commentMapper = CommentMapper::getInstance($this->adapter);
                if ($commentMapper->insert($comment)) {
                    
                    $total_comments = $commentMapper->fetchCountCommentByKnowledgeAreaId($comment->knowledge_area_id);
                    
                    $knowledgeAreaContent->total_comments = $total_comments;
                    $knowledgeAreaContentMapper->update($knowledgeAreaContent);
                    
                    $response = [
                        'success'   => true,
                        'data'   => $this->renderComment($comment->id, $now),
                        'total_comments' => $total_comments
                    ];
                    
                    return new JsonModel($response);
                } else {
                    
                    $response = [
                        'success'   => false,
                        'data'   => $commentMapper->getError()
                    ];
                    
                    return new JsonModel($response);
                }
            } else {
                $message = '';;
                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {
                    foreach ($field_messages as $key => $value) {
                        $message = $value;
                    }
                }
                
                $response = [
                    'success'   => false,
                    'data'   => $message
                ];
                
                return new JsonModel($response);
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($response);
        }
    }
    
    
    
    public function deleteCommentAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if ($request->isPost()) {

            $id = $this->params()->fromRoute('id');
            $comment = $this->params()->fromRoute('comment');
            
            
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);

            
            
            if($knowledgeAreaContent && $knowledgeAreaContent->network_id == $currentUser->network_id) {
                
                $commentMapper = CommentMapper::getInstance($this->adapter);
                $comment = $commentMapper->fetchOneByUuid($comment);

                
                if ($comment && $comment->knowledge_area_id == $knowledgeAreaContent->id && $comment->user_id == $currentUser->id) {
                    
                    $comment->status = Comment::STATUS_DELETED;
                    
                    if ($commentMapper->update($comment)) {
                        
                        $total_comments = $commentMapper->fetchCountCommentByKnowledgeAreaId($knowledgeAreaContent->id);
                        $knowledgeAreaContent->total_comments = $total_comments;
                        $knowledgeAreaContentMapper->update($knowledgeAreaContent);

                        $response = [
                            'success' => true,
                            'data' => 'LABEL_COMMENT_WAS_DELETED',
                            'total_comments' => $total_comments
                        ];
                    } else {
                        $response = [
                            'success' => false,
                            'data' => $commentMapper->getError()
                        ];
                    }
                } else {
                    $response = [
                        'success' => false,
                        'data' => 'ERROR_COMMENT_NOT_FOUND'
                    ];
                }
            } else {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_COMMENT_NOT_FOUND'
                ];
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }
        
        return new JsonModel($response);
    }
    
  
    
    public function saveReactionAction()
    {
        
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        
        $id = $this->params()->fromRoute('id');
        $reaction  = $this->params()->fromPost('reaction');
        
        $request = $this->getRequest();
        if ($request->isPost()) {

            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
            if(!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
                ]);
            }
            
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $contentReaction = $contentReactionMapper->fetchOneByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id);
            
            if ($contentReaction) {
                $contentReaction->reaction = $reaction;
                
                $result = $contentReactionMapper->update($contentReaction);
            } else {
                $contentReaction = new ContentReaction();
                $contentReaction->user_id = $currentUser->id;
                $contentReaction->knowledge_area_id = $knowledgeAreaContent->id;
                $contentReaction->relational = ContentReaction::RELATIONAL_KNOWLEDGE_AREA;
                $contentReaction->reaction = $reaction;
                
                $result = $contentReactionMapper->insert($contentReaction);
            }
            
            
            
            if ($result) {
                
                $reactions = $contentReactionMapper->fetchCountContentReactionsByKnowledgeAreaId($knowledgeAreaContent->id);
                $response = [
                    'success' => true,
                    'data' => [
                        'reactions' => $reactions
                    ]
                ];
            } else {
                $response = [
                    'success' => false,
                    'data' => $contentReactionMapper->getError()
                ];
            }
            return new JsonModel($response);
        }
        
        $response = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];
        return new JsonModel($response);
    }
    
    public function deleteReactionAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        
        $id = $this->params()->fromRoute('id');
        
        $request = $this->getRequest();
        if ($request->isPost()) {

            
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
            if(!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
                ]);
            }
            
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $contentReaction = $contentReactionMapper->fetchOneByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id);
            
            if (!$contentReaction) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_DUPLICATE_ACTION'
                ];
                return new JsonModel($response);
            }
            
            if ($contentReactionMapper->deleteByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id)) {
                $reactions = $contentReactionMapper->fetchCountContentReactionsByKnowledgeAreaId($knowledgeAreaContent->id);
                
                $response = [
                    'success' => true,
                    'data' => [
                        'reactions' => $reactions
                    ]
                ];
            } else {
                $response = [
                    'success' => false,
                    'data' => $contentReactionMapper->getError()
                ];
            }
            return new JsonModel($response);
        }
        
        $response = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];
        return new JsonModel($response);
    }
    
    public function commentsAction()
    {
        $id = $this->params()->fromRoute('id');
        
        $request = $this->getRequest();
        if ($request->isGet()) {
            $utilMapper = UtilMapper::getInstance($this->adapter);
            $now = $utilMapper->getDatebaseNow();
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
            if(!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
                ]);
            }
            
            $commentMapper = CommentMapper::getInstance($this->adapter);
            $records = $commentMapper->fetchAllPublishedByKnowledgeAreaId($knowledgeAreaContent->id);
            
            $comments = [];
            foreach ($records as $record) {
                $comment = $this->renderComment($record->id, $now);
                array_push($comments, $comment);
            }
            
            $response = [
                'success' => true,
                'data' => $comments
            ];
            
            return new JsonModel($response);
        } else {
            
            
            
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            
            return new JsonModel($response);
        }
    }
    
    
    

    private function renderComment($comment_id, $now)
    {
        $item = [];
        
        $commentMapper = CommentMapper::getInstance($this->adapter);
        $record = $commentMapper->fetchOne($comment_id);
        
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOne($record->knowledge_area_id);
        
        if ($record) {
            $userMapper = UserMapper::getInstance($this->adapter);
            
            $user = $userMapper->fetchOne($record->user_id);
            
            $item['unique'] = uniqid();
            $item['user_image'] = $this->url()->fromRoute('storage', ['type' => 'user',  'code' => $user->uuid, 'filename' =>  $user->image]);
            $item['user_url'] = $this->url()->fromRoute('profile/view', ['id' => $user->uuid]);
            $item['user_name'] = $user->first_name . ' ' . $user->last_name;
            $item['time_elapsed'] = Functions::timeAgo($record->added_on, $now);
            $item['comment'] = $record->comment;
            $item['link_delete'] = $this->url()->fromRoute('knowledge-area/comments/delete', ['id' => $knowledgeAreaContent->uuid, 'comment' => $record->uuid]);
        }
        return $item;
    }
    
}