Rev 7236 | Rev 16768 | Ir a la última revisión | 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\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\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Library\Image;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
use LeadersLinked\Model\CompanyMicrolearningTopic;
use LeadersLinked\Form\TopicAddForm;
use LeadersLinked\Form\TopicEditForm;
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
class MicrolearningTopicController 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()
{
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
if($request->isGet()) {
$headers = $request->getHeaders();
$isJson = false;
if($headers->has('Accept')) {
$accept = $headers->get('Accept');
$prioritized = $accept->getPrioritized();
foreach($prioritized as $key => $value) {
$raw = trim($value->getRaw());
if(!$isJson) {
$isJson = strpos($raw, 'json');
}
}
}
if($isJson) {
$search = $this->params()->fromQuery('search', []);
$search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
$records_x_page = intval($this->params()->fromQuery('length', 10), 10);
$page = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
$order = $this->params()->fromQuery('order', []);
$order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
$order_direction = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var( $order[0]['dir'], FILTER_SANITIZE_STRING));
$fields = ['name'];
$order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
if(!in_array($order_direction, ['ASC', 'DESC'])) {
$order_direction = 'ASC';
}
$acl = $this->getEvent()->getViewModel()->getVariable('acl');
$allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/edit');
$allowDelete = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/delete');
$companyMicrolearningTopicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
$paginator = $companyMicrolearningTopicMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
$records = $paginator->getCurrentItems();
$items = [];
foreach($records as $record)
{
//print_r($record);
switch($record->status) {
case CompanyMicrolearningTopic::STATUS_ACTIVE :
$status = 'LABEL_ACTIVE';
break;
case CompanyMicrolearningTopic::STATUS_INACTIVE :
$status = 'LABEL_INACTIVE';
break;
default :
$status = '';
break;
}
$item = [
'name' => $record->name,
'status' => $status,
'image' => $this->url()->fromRoute('storage', ['type' => 'microlearning-topic', 'code' => $record->uuid, 'filename' => $record->image]),
'actions' => [
'link_edit' => $allowEdit ? $this->url()->fromRoute('microlearning/content/topics/edit', ['id' => $record->uuid ]) : '',
'link_delete' => $allowDelete ? $this->url()->fromRoute('microlearning/content/topics/delete', ['id' => $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.microlearning_image_upload'];
$marketplace_size = $this->config['leaderslinked.image_sizes.marketplace'];
$formAdd = new TopicAddForm();
$formEdit = new TopicEditForm();
$this->layout()->setTemplate('layout/layout-backend.phtml');
$viewModel = new ViewModel();
$viewModel->setTemplate('leaders-linked/microlearning-topics/index.phtml');
$viewModel->setVariables([
'formAdd' => $formAdd,
'formEdit' => $formEdit,
'company_uuid' => $currentCompany->uuid,
'image_size' => $image_size,
'marketplace_size' => $marketplace_size,
]);
return $viewModel ;
}
} else {
return new JsonModel([
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
]);
}
}
public function addAction()
{
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
/* return new JsonModel([
'success' => false,
'data' => [
'name'=>$this->params()->fromPost('file_base64_name'),
'content'=>$this->params()->fromPost('file'),
]
]);*/
if($request->isPost()) {
$form = new TopicAddForm();
$dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($dataPost);
if($form->isValid()) {
$dataPost = (array) $form->getData();
$hydrator = new ObjectPropertyHydrator();
$topic = new CompanyMicrolearningTopic();
$hydrator->hydrate($dataPost, $topic);
$topic->company_id = $currentCompany->id;
$topic->image = null;
$topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
if($topicMapper->insert($topic)) {
$topic = $topicMapper->fetchOne($topic->id);
$fileBase64Content = $this->params()->fromPost('file');
try {
$fileBase64Content = base64_decode($fileBase64Content);
$target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . $topic->uuid;
$topic_filename = 'topic-' .uniqid() . '.jpg';
$topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
if(!file_exists($topic_tmp_filename)) {
mkdir($topic_tmp_filename, 0755, true);
}
$topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $topic_filename;
file_put_contents($topic_tmp_filename, $fileBase64Content);
list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
$crop_to_dimensions = false;
if(Image::uploadImage($topic_tmp_filename, $target_path, $topic_filename, $target_width, $target_height, $crop_to_dimensions )) {
$topic->image = basename($topic_filename);
$topicMapper->update($topic);
}
} catch(\Throwable $e) {
error_log($e->getTraceAsString());
}
$this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
$data = [
'success' => true,
'data' => 'LABEL_RECORD_ADDED'
];
} else {
$data = [
'success' => false,
'data' => $topicMapper->getError()
];
}
return new JsonModel($data);
} else {
$messages = [];
$form_messages = (array) $form->getMessages();
foreach($form_messages as $fieldname => $field_messages)
{
$messages[$fieldname] = array_values($field_messages);
}
return new JsonModel([
'success' => false,
'data' => $messages
]);
}
} else {
$data = [
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
];
return new JsonModel($data);
}
return new JsonModel($data);
}
/**
*
* Borrar un perfil excepto el público
* @return \Laminas\View\Model\JsonModel
*/
public function deleteAction()
{
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$id = $this->params()->fromRoute('id');
$topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
$topic = $topicMapper->fetchOneByUuid($id);
if(!$topic) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_TOPIC_NOT_FOUND'
]);
}
if($topic->company_id != $currentCompany->id) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_UNAUTHORIZED'
]);
}
if($request->isPost()) {
$capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
$count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
if($count > 0 ) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
]);
}
$result = $topicMapper->delete($topic);
if($result) {
$this->logger->info('Se borro el tópico : ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
try {
$target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . DIRECTORY_SEPARATOR . $topic->uuid;
if(file_exists($target_path)) {
Functions::rmDirRecursive($target_path);
}
} catch(\Throwable $e) {
error_log($e->getTraceAsString());
}
$data = [
'success' => true,
'data' => 'LABEL_RECORD_DELETED'
];
} else {
$data = [
'success' => false,
'data' => $topicMapper->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');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$id = $this->params()->fromRoute('id');
$topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
$topic = $topicMapper->fetchOneByUuid($id);
if(!$topic) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_TOPIC_NOT_FOUND'
]);
}
if($topic->company_id != $currentCompany->id) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_UNAUTHORIZED'
]);
}
if($request->isGet()) {
$data = [
'success' => true,
'data' => [
'name' => $topic->name,
'description' => $topic->description,
'order' => $topic->order,
'status' => $topic->status,
'image'=> $this->url()->fromRoute('storage', ['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image])
]
];
return new JsonModel($data);
}
else if($request->isPost()) {
$form = new TopicEditForm();
$dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($dataPost);
if($form->isValid()) {
$dataPost = (array) $form->getData();
$hydrator = new ObjectPropertyHydrator();
$hydrator->hydrate($dataPost, $topic);
$topic->image = null;
$topic->marketplace = null;
if($topicMapper->update($topic)) {
$topic = $topicMapper->fetchOne($topic->id);
$fileBase64Content = $this->params()->fromPost('file');
try {
$target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . $topic->uuid;
if($topic->image) {
if(!image ::delete($target_path, $topic->image)) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_THERE_WAS_AN_ERROR'
]);
}
}
$fileBase64Content = base64_decode($fileBase64Content);
$topic_filename = 'topic-' .uniqid() . '.jpg';
$topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
if(!file_exists($topic_tmp_filename)) {
mkdir($topic_tmp_filename, 0755, true);
}
$topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $topic_filename;
file_put_contents($topic_tmp_filename, $fileBase64Content);
list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
$crop_to_dimensions = false;
if(Image::uploadImage($topic_tmp_filename, $target_path, $topic_filename, $target_width, $target_height, $crop_to_dimensions )) {
$topic->image = basename($topic_filename);
$topicMapper->update($topic);
}
} catch(\Throwable $e) {
error_log($e->getTraceAsString());
}
$this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
$data = [
'success' => true,
'data' => 'LABEL_RECORD_UPDATED'
];
/*
$topic = $topicMapper->fetchOne($topic->id);
$target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . $topic->uuid;
if(!file_exists($target_path)) {
mkdir($target_path, 0755, true);
}
$files = $this->getRequest()->getFiles()->toArray();
if(isset($files['file']) && empty($files['file']['error'])) {
$tmp_filename = $files['file']['tmp_name'];
//$filename = $this->normalizeString($files['file']['name']);
try {
if($topic->image) {
if(!image ::delete($target_path, $topic->image)) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_THERE_WAS_AN_ERROR'
]);
}
}
list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
$filename = 'topic-' .uniqid() . '.png';
$crop_to_dimensions = true;
if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
$topic->image = $filename;
$topicMapper->update($topic);
}
} catch(\Throwable $e) {
error_log($e->getTraceAsString());
}
}
$this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
$data = [
'success' => true,
'data' => 'LABEL_RECORD_UPDATED'
];*/
} else {
$data = [
'success' => false,
'data' => $topicMapper->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);
}
}