Rev 17017 | 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\Hydrator\ObjectPropertyHydrator;use LeadersLinked\Mapper\HabitContentMapper;use LeadersLinked\Form\Habit\HabitContentAddForm;use LeadersLinked\Form\Habit\HabitContentEditForm;use LeadersLinked\Model\HabitContent;use LeadersLinked\Library\Image;use LeadersLinked\Library\Storage;class HabitContentController 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(){$currentNetworkPlugin = $this->plugin('currentNetworkPlugin');$currentNetwork = $currentNetworkPlugin->getNetwork();$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$currentCompany = $currentUserPlugin->getCompany();$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' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));$fields = ['order', 'name'];$order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'order';if(!in_array($order_direction, ['ASC', 'DESC'])) {$order_direction = 'ASC';}$habitContentMapper = HabitContentMapper::getInstance($this->adapter);$paginator = $habitContentMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);$storage = Storage::getInstance($this->config, $this->adapter);$path = $storage->getPathHabitContent();$items = [];$records = $paginator->getCurrentItems();foreach($records as $record){switch($record->status){case HabitContent::STATUS_ACTIVE :$status = 'LABEL_ACTIVE';break;case HabitContent::STATUS_INACTIVE :$status = 'LABEL_INACTIVE';break;default :$status = 'LABEL_UNKNOWN';break;}$item = ['name' => $record->name,'order' => $record->order,'type' => $record->type,'file' => $record->file,'status' => $status,'actions' => ['link_edit' => $this->url()->fromRoute('habits/content/edit', ['id' => $record->uuid ]),'link_delete' => $this->url()->fromRoute('habits/content/delete', ['id' => $record->uuid ]),]];array_push($items, $item);}return new JsonModel(['success' => true,'data' => ['items' => $items,'total' => $paginator->getTotalItemCount(),]]);} else {$formAdd = new HabitContentAddForm();$formEdit = new HabitContentAddForm();$this->layout()->setTemplate('layout/layout-backend');$viewModel = new ViewModel();$viewModel->setTemplate('leaders-linked/habits/content');$viewModel->setVariables(['formAdd' => $formAdd,'formEdit' => $formEdit,]);return $viewModel ;}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);;}}public function addAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentUser = $currentUserPlugin->getUser();$currentCompany = $currentUserPlugin->getCompany();$request = $this->getRequest();if($request->isPost()) {$form = new HabitContentAddForm();$dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());$dataPost['status'] = empty($dataPost['status']) ? HabitContent::STATUS_INACTIVE : $dataPost['status'];$form->setData($dataPost);if($form->isValid()) {$dataPost = (array) $form->getData();$habitContent = new HabitContent();$habitContent->company_id = $currentCompany->id;$habitContent->name = $dataPost['name'];$habitContent->status = $dataPost['status'];$habitContent->order = $dataPost['order'];$habitContent->file = '';$habitContent->type = '';$files = $this->getRequest()->getFiles()->toArray();$type = '';$filename = '';if (isset($files['file']) && empty($files['file']['error'])) {$tmp_filename = $files['file']['tmp_name'];$filename = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);$mime_type = mime_content_type($tmp_filename);if ($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {$type = HabitContent::TYPE_IMAGE;} else if ($mime_type == 'video/quicktime' || $mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {$type = HabitContent::TYPE_VIDEO;} else if ($mime_type == 'application/pdf') {$type = HabitContent::TYPE_DOCUMENT;}}$habitContentMapper = HabitContentMapper::getInstance($this->adapter);if($habitContentMapper->insert($habitContent)) {$habitContent = $habitContentMapper->fetchOne($habitContent->id);$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathHabitContent();if ($type == HabitContent::TYPE_DOCUMENT) {if($storage->moveAndPutFile($tmp_filename, $target_path, $habitContent->uuid, $filename)) {$habitContent->file = $filename;$habitContent->type = $type;$habitContentMapper->update($habitContent);}} else if ($type == HabitContent::TYPE_IMAGE) {$image = Image::getInstance($this->config);$filename = substr($filename, 0, strrpos($filename, '.')) . '.png';$full_tmp_filename = $image->uploadProcessWithOutChangeSize($tmp_filename, $filename);if($full_tmp_filename) {if($storage->putFile($target_path, $habitContent->uuid, $full_tmp_filename)) {$habitContent->file = $filename;$habitContent->type = $type;$habitContentMapper->update($habitContent);}}}if ($type == HabitContent::TYPE_VIDEO) {try {if($storage->moveAndPutFile($tmp_filename, $target_path, $habitContent->uuid, $filename)) {$habitContent->file = $filename;$habitContent->type = $type;if($habitContentMapper->update($habitContent)) {$videoConvert = new \LeadersLinked\Model\VideoConvert();$videoConvert->uuid = $habitContent->uuid;$videoConvert->filename = $filename;$videoConvert->type = \LeadersLinked\Model\VideoConvert::TYPE_HABIT_CONTENT;$videoConvertMapper = \LeadersLinked\Mapper\VideoConvertMapper::getInstance($this->adapter);$videoConvertMapper->insert($videoConvert);}}// @unlink($full_filename);//@unlink($generate_full_filename);} catch (\Throwable $e) {error_log($e->getTraceAsString());}}$this->logger->info('Se agrego el contenido ' . $habitContent->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_RECORD_ADDED'];} else {$data = ['success' => false,'data' => $habitContentMapper->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();$currentCompany = $currentUserPlugin->getCompany();$request = $this->getRequest();$id = $this->params()->fromRoute('id');$habitContentMapper = HabitContentMapper::getInstance($this->adapter);$habitContent = $habitContentMapper->fetchOneByUuid($id);if(!$habitContent) {return new JsonModel(['success' => false,'data' => 'ERROR_RECORD_NOT_FOUND']);}if($habitContent->company_id != $currentCompany->id) {return new JsonModel(['success' => false,'data' => 'ERROR_UNAUTHORIZED']);}if($request->isPost()) {$result = $habitContentMapper->delete($habitContent);if($result) {$this->logger->info('Se borro el Content : ' . $habitContent->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);if($habitContent->file) {$storage = \LeadersLinked\Library\Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathHabitContent();$storage->deleteDirectory($target_path, $habitContent->uuid);}$data = ['success' => true,'data' => 'LABEL_RECORD_DELETED'];} else {$data = ['success' => false,'data' => $habitContentMapper->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();$currentCompany = $currentUserPlugin->getCompany();$request = $this->getRequest();$id = $this->params()->fromRoute('id');$habitContentMapper = HabitContentMapper::getInstance($this->adapter);$habitContent = $habitContentMapper->fetchOneByUuid($id);if(!$habitContent) {return new JsonModel(['success' => false,'data' => 'ERROR_RECORD_NOT_FOUND']);}if($habitContent->company_id != $currentCompany->id) {return new JsonModel(['success' => false,'data' => 'ERROR_UNAUTHORIZED']);}if($request->isGet()) {$storage = Storage::getInstance($this->config, $this->adapter);$data = ['success' => true,'data' => ['name' => $habitContent->name,'order' => $habitContent->order,'status' => $habitContent->status,]];return new JsonModel($data);}else if($request->isPost()) {$form = new HabitContentEditForm();$dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());$dataPost['status'] = empty($dataPost['status']) ? HabitContent::STATUS_INACTIVE : $dataPost['status'];$form->setData($dataPost);if($form->isValid()) {$dataPost = (array) $form->getData();$habitContent->name = $dataPost['name'];$habitContent->order = $dataPost['order'];$habitContent->code = $dataPost['code'];$habitContent->status = $dataPost['status'];if($habitContentMapper->update($habitContent)) {$this->logger->info('Se edito el Content' . $habitContent->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$data = ['success' => true,'data' => 'LABEL_RECORD_UPDATED'];} else {$data = ['success' => false,'data' => $habitContentMapper->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);}}