Rev 16768 | Rev 17002 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
<?phpdeclare(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\PostCreateForm;use LeadersLinked\Form\PostEditForm;use LeadersLinked\Model\Post;use LeadersLinked\Hydrator\ObjectPropertyHydrator;use LeadersLinked\Library\Image;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(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$request = $this->getRequest();if ($request->isPost()) {$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()) {$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 = '';$postMapper = PostMapper::getInstance($this->adapter);if ($postMapper->insert($post)) {$post = $postMapper->fetchOne($post->id);$files = $this->getRequest()->getFiles()->toArray();$target_path = $this->config['leaderslinked.fullpath.post'] . $post->uuid;if (!file_exists($target_path)) {mkdir($target_path, 0755, true);}if (isset($files['file']) && empty($files['file']['error'])) {$tmp_filename = $files['file']['tmp_name'];$original_filename = trim(strtolower($files['file']['name']));$original_filename = Functions::normalizeString($original_filename);$parts = explode('.', $original_filename);$original_filename = $parts[0] . '.' . $parts[count($parts) - 1];try {$full_filename = $target_path . DIRECTORY_SEPARATOR . $original_filename;if (move_uploaded_file($tmp_filename, $full_filename)) {$post->file = basename($full_filename);$post->update($post);}} catch (\Throwable $e) {error_log($e->getTraceAsString());}}if (isset($files['image']) && empty($files['image']['error'])) {$tmp_filename = $files['image']['tmp_name'];try {list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.post']);$filename = 'image-' . uniqid() . '.png';// $crop_to_dimensions = true;// if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {if (Image::uploadImageWithoutCompletationSize($tmp_filename, $target_path, $filename, $target_width, $target_height)) {$post->image = $filename;$postMapper->update($post);}} catch (\Throwable $e) {error_log($e->getTraceAsString());}}$this->logger->info('Se agrego la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_RECORD_ADDED'];} else {$data = ['success' => false,'data' => $postMapper->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');$currentUser = $currentUserPlugin->getUser();$request = $this->getRequest();$id = $this->params()->fromRoute('id');$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->isPost()) {$post->status = Post::STATUS_DELETE;$result = $postMapper->update($post);if ($result) {$this->logger->info('Se borro la noticia : ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_POST_DELETED'];} else {$data = ['success' => false,'data' => $postMapper->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');$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);$data = ['success' => true,'data' => ['title' => $post->title,'status' => $post->status,'description' => $post->description,'url' => $post->url,'date' => $dt->format('d/m/Y'),]];return new JsonModel($data);} else 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()) {$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');$files = $this->getRequest()->getFiles()->toArray();$target_path = $this->config['leaderslinked.fullpath.post'] . $post->uuid;if (!file_exists($target_path)) {mkdir($target_path, 0755, true);}if (isset($files['file']) && empty($files['file']['error'])) {if ($post->file) {Functions::deleteFilename($target_path, $post->file);}$tmp_filename = $files['file']['tmp_name'];$original_filename = trim(strtolower($files['file']['name']));$original_filename = Functions::normalizeString($original_filename);$parts = explode('.', $original_filename);$original_filename = $parts[0] . '.' . $parts[count($parts) - 1];try {$full_filename = $target_path . DIRECTORY_SEPARATOR . $original_filename;if (move_uploaded_file($tmp_filename, $full_filename)) {$post->file = basename($full_filename);$post->update($post);}} catch (\Throwable $e) {error_log($e->getTraceAsString());}}if (isset($files['image']) && empty($files['image']['error'])) {if ($post->image) {Functions::deleteFilename($target_path, $post->image);}$tmp_filename = $files['image']['tmp_name'];try {list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.post']);$filename = 'image-' . uniqid() . '.png';$crop_to_dimensions = true;if (Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {$post->image = $filename;$postMapper->update($post);}} catch (\Throwable $e) {error_log($e->getTraceAsString());}}if ($postMapper->update($post)) {$this->logger->info('Se edito la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_RECORD_UPDATED'];} else {$data = ['success' => false,'data' => $postMapper->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);}}