Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17275 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

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\Library\Functions;
use LeadersLinked\Mapper\PostMapper;
use LeadersLinked\Form\Post\PostCreateForm;
use LeadersLinked\Form\Post\PostEditForm;
use LeadersLinked\Model\Post;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Library\Storage;

class PostController 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;
    }

    public function indexAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $network = $currentNetworkPlugin->getNetwork();

        $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) {


                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);

                $page               = intval($this->params()->fromQuery('start', 1), 10);
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
                $order =  $this->params()->fromQuery('order', []);
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));

                $fields =  ['title', 'date'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'title';

                if (!in_array($order_direction, ['ASC', 'DESC'])) {
                    $order_direction = 'ASC';
                }

                $postMapper = PostMapper::getInstance($this->adapter);
                $paginator = $postMapper->fetchAllDataTable($search, $currentUser->network_id, $page, $records_x_page, $order_field, $order_direction);

                $items = [];
                $records = $paginator->getCurrentItems();
                foreach ($records as $record) {
                    $dt = \DateTime::createFromFormat('Y-m-d', $record->date);

                    $item = [
                        'title' => $record->title,
                        'active' => $record->status,
                        'date' => $dt->format('d/m/Y'),
                        'actions' => [
                            'link_edit' => $this->url()->fromRoute('publications/posts/edit', ['id' => $record->uuid]),
                            'link_delete' => $this->url()->fromRoute('publications/posts/delete', ['id' => $record->uuid]),
                            'link_view' => 'https://' . $network->main_hostname . '/post/' . $record->uuid,
                        ]
                    ];

                    array_push($items, $item);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount(),
                    ]
                ]);
            } else {
                $image_size = $this->config['leaderslinked.image_sizes.post'];

                $formAdd = new PostCreateForm();
                $formEdit = new PostEditForm();

                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/posts/index.phtml');
                $viewModel->setVariables([
                    'formAdd' => $formAdd,
                    'formEdit' => $formEdit,
                    'image_size' => $image_size,

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



    public function addAction()
    {
        try {
            $request    = $this->getRequest();
    
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
    
            if (!$request->isPost()) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
                ]);
            }
    
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
            $dataPost['status'] = empty($dataPost['status']) ? Post::STATUS_INACTIVE : $dataPost['status'];
    
            $form = new PostCreateForm();
            $form->setData($dataPost);
    
            if (!$form->isValid()) {
                $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
                ]);
            }
    
            $dataPost = (array) $form->getData();
    
            $hydrator = new ObjectPropertyHydrator();
            $post = new Post();
            $hydrator->hydrate($dataPost, $post);
    
            $dt = \DateTime::createFromFormat('d/m/Y', $post->date);
            $post->date = $dt->format('Y-m-d');
            $post->network_id = $currentUser->network_id;
            $post->image = '';
            $post->file  = '';
            $post->user_id = $currentUser->id;
    
            $postMapper = PostMapper::getInstance($this->adapter);
    
            if (!$postMapper->insert($post)) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => $postMapper->getError()
                ]);
            }
    
            $storage = Storage::getInstance($this->config, $this->adapter);
    
            $storage->setFiles($request->getFiles()->toArray());
    
            if(!$storage->setCurrentFilename('file')) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_FILE_NOT_FOUND'
                ]);
            }
    
            $tmp_filename =  $storage->getTmpFilename();
            $filename = 'post-' . uniqid() . '.' . $storage->getExtension();
            $target_filename = $storage->composePathToFilename(
                Storage::TYPE_POST,
                $post->uuid,
                $filename
            );
    
            if(!$storage->putFile($tmp_filename, $target_filename)) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_UPLOAD_FILE'
                ]);
            }
            
            if(!$storage->setCurrentFilename('image')) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_FILE_NOT_FOUND'
                ]);
            }
    
     
            $tmp_filename  = $storage->getTmpFilename();
            $filename = 'post-image-' . uniqid() . '.png';
            $target_filename = $storage->composePathToFilename(
                Storage::TYPE_POST,
                $post->uuid,
                $filename
            );
    
            $post->file = $filename;
            
            if(!$storage->uploadImageWithOutChangeSize($tmp_filename, $target_filename)) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => 'ERROR_UPLOAD_IMAGE'
                ]);
            }
            
            $post->image = $filename;
            
            if(!$postMapper->update($post)) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => $postMapper->getError()
                ]);
            }
    
            $this->logger->info('Se agrego la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
    
            return new JsonModel([
                'success' => true,
                'data'   => 'LABEL_RECORD_ADDED'
            ]);
        } catch (\Throwable $e) {
            $this->logger->error('Error al agregar la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP(), 'error' => $e->getTraceAsString()]);
            return new JsonModel([
                'success'   => false,
                'data'   => $e->getMessage()
            ]);
        }
    }

    /**
     *
     * Borrar un perfil excepto el público
     * @return \Laminas\View\Model\JsonModel
     */
    public function deleteAction()
    {
        try {
            $request    = $this->getRequest();
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $id = $this->params()->fromRoute('id');

            if (!$request->isPost()) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
                ]);
            }

            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);

            if (!$post) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ]);
            }

            $post->status = Post::STATUS_DELETE;

            $storage = Storage::getInstance($this->config, $this->adapter);
            $post_path = $storage->getPathPost();

            if($post->file) {
                $storage->deleteFile($post_path, $post->uuid, $post->file);
            }
            if($post->image) {
                $storage->deleteFile($post_path, $post->uuid, $post->image);
            }

            if(!$postMapper->update($post)) {
                return new JsonModel([
                    'success'   => false,
                    'data'   => $postMapper->getError()
                ]);
            }   

            $this->logger->info('Se borro la noticia : ' .  $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

            return new JsonModel([
                'success' => true,
                'data' => 'LABEL_POST_DELETED'
            ]);
        } catch (\Throwable $th) {
            $this->logger->error('Error al borrar la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP(), 'error' => $th->getTraceAsString()]);
            return new JsonModel([
                'success'   => false,
                'data'   => $th->getMessage()
            ]);
        }
    }


    public function editAction()
    {
        try {
            $request    = $this->getRequest();

            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $id = $this->params()->fromRoute('id');

            if (!$request->isPost() && !$request->isGet()) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
                ]);
            }

            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);

            if (!$post) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ]);
            }


            if ($request->isGet()) {
                $dt = \DateTime::createFromFormat('Y-m-d', $post->date);
                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'title' => $post->title,
                        'status' => $post->status,
                        'description' => $post->description,
                        'url' => $post->url,
                        'date' => $dt->format('d/m/Y'),
                    ]
                ]);
            } 
            
            if ($request->isPost()) {
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
                $dataPost['status'] = empty($dataPost['status']) ? Post::STATUS_INACTIVE : $dataPost['status'];

                $form = new PostEditForm();
                $form->setData($dataPost);

                if (!$form->isValid()) {
                    $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
                    ]);
                }
                
                $dataPost = (array) $form->getData();

                $post->title        = $dataPost['title'];
                $post->description  = $dataPost['description'];
                $post->url          = isset($dataPost['url']) ? $dataPost['url'] : '';
                $post->status       = isset($dataPost['status']) ? $dataPost['status'] : Post::STATUS_INACTIVE;

                $dt = \DateTime::createFromFormat('d/m/Y', $dataPost['date']);
                $post->date = $dt->format('Y-m-d');

                $storage = Storage::getInstance($this->config, $this->adapter);
                $post_path = $storage->getPathPost();

                $storage->setFiles($request->getFiles()->toArray());

                if($storage->setCurrentFilename('file')) {
                    $tmp_filename =  $storage->getTmpFilename();
                    $filename = 'post-' . uniqid() . '.' . $storage->getExtension();
                    $target_filename = $storage->composePathToFilename(
                        Storage::TYPE_POST,
                        $post->uuid,
                        $filename
                    );

                    if($post->file) {
                        $storage->deleteFile($post_path, $post->uuid, $post->file);
                    }

                    if(!$storage->putFile($tmp_filename, $target_filename)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   => 'ERROR_UPLOAD_FILE'
                        ]);
                    }

                    $post->file = $filename;
                }

                if($storage->setCurrentFilename('image')) {
                    $tmp_filename =  $storage->getTmpFilename();
                    $filename = 'post-image-' . uniqid() . '.png';
                    $target_filename = $storage->composePathToFilename(
                        Storage::TYPE_POST,
                        $post->uuid,
                        $filename
                    );

                    if ($post->image) {
                        $storage->deleteFile($post_path, $post->uuid, $post->image);
                    }

                    if(!$storage->uploadImageWithOutChangeSize($tmp_filename, $target_filename)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   => 'ERROR_UPLOAD_IMAGE'
                        ]);
                    }

                    $post->image = $filename;
                }

                if(!$postMapper->update($post)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'   => $postMapper->getError()
                    ]);
                }

                $this->logger->info('Se edito la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                return new JsonModel([
                    'success'   => true,
                    'data'   => 'LABEL_RECORD_UPDATED'
                ]);
            }
        } catch (\Throwable $th) {
            $this->logger->error('Error al editar la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP(), 'error' => $th->getTraceAsString()]);
            return new JsonModel([
                'success'   => false,
                'data'   => $th->getMessage()
            ]);
        }
    }
}