Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 5732 | Rev 5780 | 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\JsonModel;
use Laminas\View\Model\ViewModel;

use LeadersLinked\Library\Functions;
use LeadersLinked\Model\Post;
use LeadersLinked\Mapper\PostMapper;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\CommentMapper;
use LeadersLinked\Model\ContentReaction;
use LeadersLinked\Model\Comment;
use LeadersLinked\Mapper\UtilMapper;
use LeadersLinked\Form\Post\CommentForm;
use LeadersLinked\Mapper\ContentReactionMapper;



class PostController 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()
    {

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

    public function viewAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();


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

            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuid($id);

            if (!$post || $post->status != Post::STATUS_ACTIVE) {
                $flashMessenger = $this->plugin('FlashMessenger');

                if (!$id) {
                    $flashMessenger->addErrorMessage('ERROR_POST_NOT_AVAILABLE');
                    return $this->redirect()->toRoute('dashboard');
                }
            }



            $timestamp = time();

            list($usec, $sec) = explode(' ', microtime());
            $seed = intval($sec + ((float) $usec * 100000));
            mt_srand($seed, MT_RAND_MT19937);
            $rand =  mt_rand();



            $password  = md5('user-' . $currentUser->uuid . '-post-' . $post->uuid . '-timestamp-' . $timestamp . '-rand-' . $rand . '-share-key-' . $currentUser->share_key);


            $share_params = [
                'type' => 'post',
                'code' => $post->uuid,
                'user' => $currentUser->uuid,
                'timestamp' => $timestamp,
                'rand' => $rand,
                'password' => $password,
            ];



            $share_increment_external_counter_url = $this->url()->fromRoute('share/increment-external-counter', $share_params, ['force_canonical' => true]);


            $share_external_url = $this->url()->fromRoute('shorter/generate', ['code' => $post->uuid, 'type' => 'post'], ['force_canonical' => true]);

            //$contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            //$like = $contentReactionMapper->fetchOneByPostIdAndUserId($post->id, $currentUser->id);

            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $reactions = $contentReactionMapper->fetchCountContentReactionsByPostId($post->id);
            $reaction = $contentReactionMapper->fetchOneByPostIdAndUserId($post->id, $currentUser->id);
            
            
            $this->layout()->setTemplate('layout/layout.phtml');
            $viewModel = new ViewModel();
            $viewModel->setTemplate('leaders-linked/post/view.phtml');
            $viewModel->setVariables([
                'post' => $post,
                'id' => $post->id,
                'uuid' => $post->uuid,
                'title' => $post->title,
                'description' => $post->description,
                'url' => $post->url,
                'date' => $post->date,
                'status' => $post->status,
                'image' => $post->image,
                'file' => $post->file,
                'added_on' => $post->added_on,
                'share_external_url' =>  $share_external_url,
                'total_share_external' => $post->total_external_shared,
                'share_increment_external_counter_url' => $share_increment_external_counter_url,
                'comments_url' => $this->url()->fromRoute('post/comments', ['id' => $post->uuid]),
                'comments_add_url' => $this->url()->fromRoute('post/comments/add', ['id' => $post->uuid]),
                'save_reaction_recommended_url' => $this->url()->fromRoute('feed/save-reaction', ['id' => $post->uuid, 'reaction' => ContentReaction::REACTION_RECOMMENDED]),
                'save_reaction_support_url' => $this->url()->fromRoute('feed/save-reaction', ['id' => $post->uuid, 'reaction' => ContentReaction::REACTION_SUPPORT]),
                'save_reaction_love_url' => $this->url()->fromRoute('feed/save-reaction', ['id' => $post->uuid, 'reaction' => ContentReaction::REACTION_LOVE]),
                'save_reaction_interest_url' => $this->url()->fromRoute('feed/save-reaction', ['id' => $post->uuid, 'reaction' => ContentReaction::REACTION_INTEREST]),
                'save_reaction_fun_url' => $this->url()->fromRoute('feed/save-reaction', ['id' => $post->uuid, 'reaction' => ContentReaction::REACTION_FUN]),
                'delete_reaction_url' =>  $this->url()->fromRoute('feed/delete-reaction', ['id' => $post->uuid]),
                'my_reaction' => $reaction ? $reaction->reaction : '',
                'reactions' =>  $reactions,
                //'is_liked' => $like ? 1 : 0,
                //'like_url' => $this->url()->fromRoute('post/like', ['id' => $post->uuid]),
                //'unlike_url' => $this->url()->fromRoute('post/unlike', ['id' => $post->uuid]),

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

            return new JsonModel($response);
        }
    }

    public function commentsAddAction()
    {
        $id = $this->params()->fromRoute('id');

        $request = $this->getRequest();
        if ($request->isPost()) {



            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuid($id);
            if (!$post) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ];
                return new JsonModel($response);
            }

            $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->post_id = $post->id;
                $comment->relational = Comment::RELATIONAL_POST;

                $commentMapper = CommentMapper::getInstance($this->adapter);
                if ($commentMapper->insert($comment)) {

                    $total_comments = $commentMapper->fetchCountCommentByPostId($comment->post_id);

                    $post->total_comments = $total_comments;
                    $postMapper->update($post);

                    $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 commentsDeleteAction()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

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

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

            if ($post) {

                $commentMapper = CommentMapper::getInstance($this->adapter);
                $comment = $commentMapper->fetchOneByUuid($comment);

                if ($comment && $comment->post_id == $post->id && $comment->user_id == $currentUser->id) {

                    $comment->status = Comment::STATUS_DELETED;

                    if ($commentMapper->update($comment)) {

                        $total_comments = $commentMapper->fetchCountCommentByPostId($comment->post_id);


                        $postMapper = PostMapper::getInstance($this->adapter);
                        $post = $postMapper->fetchOne($comment->post_id);
                        $post->total_comments = $total_comments;
                        $postMapper->update($post);





                        $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 likeAction()
    {
        $id = $this->params()->fromRoute('id');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();


            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            if (!$post) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ];
                return new JsonModel($response);
            }

            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $like = $contentReactionMapper->fetchOneByPostIdAndUserId($post->id, $currentUser->id);

            if ($like) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_DUPLICATE_ACTION'
                ];
                return new JsonModel($response);
            }

            $like = new Like();
            $like->user_id = $currentUser->id;
            $like->post_id = $post->id;
            $like->relational = Like::RELATIONAL_POST;

            if ($contentReactionMapper->insert($like)) {

                $likes = $contentReactionMapper->fetchCountLikeByPostId($post->id);
                $response = [
                    'success' => true,
                    'data' => [
                        'likes' => $likes
                    ]
                ];
            } 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 unlikeAction()
    {
        $id = $this->params()->fromRoute('id');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            if (!$post) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ];
                return new JsonModel($response);
            }

            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $like = $contentReactionMapper->fetchOneByPostIdAndUserId($post->id, $currentUser->id);

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

            if ($contentReactionMapper->deleteByPostIdAndUserId($post->id, $currentUser->id)) {
                $likes = $contentReactionMapper->fetchCountLikeByPostId($post->id);


                $response = [
                    'success' => true,
                    'data' => [
                        'likes' => $likes
                    ]
                ];
            } 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 likeAction()
    {
        $id = $this->params()->fromRoute('id');
        $reaction  = $this->params()->fromRoute('reaction');
        
        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            
            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            if (!$post) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ];
                return new JsonModel($response);
            }
            
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $contentReaction = $contentReactionMapper->fetchOneByPostIdAndUserId($post->id, $currentUser->id);
            
            if ($contentReaction) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_DUPLICATE_ACTION'
                ];
                return new JsonModel($response);
            }
            
            $contentReaction = new ContentReaction();
            $contentReaction->user_id = $currentUser->id;
            $contentReaction->post_id = $post->id;
            $contentReaction->relational = ContentReaction::RELATIONAL_POST;
            $contentReaction->reaction = $reaction;
            
            if ($contentReactionMapper->insert($contentReaction)) {
                
                $reactions = $contentReactionMapper->fetchCountContentReactionsByPostId($post->id);
                $response = [
                    'success' => true,
                    'data' => [
                        'likes' => $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 deleteAction()
    {
        $id = $this->params()->fromRoute('id');
        
        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            if (!$post) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_POST_NOT_FOUND'
                ];
                return new JsonModel($response);
            }
            
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
            $like = $contentReactionMapper->fetchOneByPostIdAndUserId($post->id, $currentUser->id);
            
            if (!$like) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_DUPLICATE_ACTION'
                ];
                return new JsonModel($response);
            }
            
            if ($contentReactionMapper->deleteByPostIdAndUserId($post->id, $currentUser->id)) {
                $reactions = $contentReactionMapper->fetchCountContentReactionByPostId($post->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();

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


            $id = $this->params()->fromRoute('id');
            $postMapper = PostMapper::getInstance($this->adapter);
            $post = $postMapper->fetchOneByUuidAndNetworkId($id,  $currentNetwork->id);
            if (!$post) {
                $data = [
                    'success' => false,
                    'data' => 'ERROR_UNAUTHORIZED',
                ];

                return new JsonModel($data);
            }

            $commentMapper = CommentMapper::getInstance($this->adapter);
            $records = $commentMapper->fetchAllPublishedByPostId($post->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);
        }
    }



    /**
     *
     * @param int $comment_id
     * @return array
     */
    private function renderComment($comment_id, $now)
    {
        $item = [];

        $commentMapper = CommentMapper::getInstance($this->adapter);
        $record = $commentMapper->fetchOne($comment_id);

        $postMapper = PostMapper::getInstance($this->adapter);
        $post = $postMapper->fetchOne($record->post_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('post/comments/delete', ['id' => $post->uuid, 'comment' => $record->uuid]);
        }
        return $item;
    }
}