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\Hydrator\ObjectPropertyHydrator;use LeadersLinked\Library\Image;use LeadersLinked\Mapper\MediaFileMapper;use LeadersLinked\Model\MediaFile;use LeadersLinked\Library\Storage;use LeadersLinked\Form\Media\FileForm;use LeadersLinked\Mapper\MediaCategoryMapper;use LeadersLinked\Model\VideoConvert;use LeadersLinked\Mapper\VideoConvertMapper;class MediaFileController 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;}/**** 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');}}}// $isJson = true;if($isJson) {$category = null;$uuid = \LeadersLinked\Library\Functions::sanitizeFilterString($this->params()->fromQuery('category'));if($uuid) {$categoryMapper = \LeadersLinked\Mapper\MediaCategoryMapper::getInstance($this->adapter);$category = $categoryMapper->fetchOneByUuid($uuid);if(!$category) {if(!$category) {return new JsonModel(['success' => false,'data' => 'ERROR_MEDIA_CATEGORY_NOT_FOUND']);}if($category->company_id != $currentCompany->id) {return new JsonModel(['success' => false,'data' => 'ERROR_UNAUTHORIZED']);}}}if(!$category) {return new JsonModel(['success' => true,'data' => ['items' => [],'total' => 0,]]);}$search = $this->params()->fromQuery('search', []);$search = empty($search['value']) ? '' : Functions::sanitizeFilterString($search['value']);$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(Functions::sanitizeFilterString($order[0]['dir']));$fields = ['name'];$order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';if(!in_array($order_direction, ['ASC', 'DESC'])) {$order_direction = 'ASC';}$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathMedia();$acl = $this->getEvent()->getViewModel()->getVariable('acl');$allowDelete = $acl->isAllowed($currentUser->usertype_id, 'media/files/delete');$mediaFileMapper = MediaFileMapper::getInstance($this->adapter);$paginator = $mediaFileMapper->fetchAllDataTableByCategoryId($category->id, $search, $page, $records_x_page, $order_field, $order_direction);$records = $paginator->getCurrentItems();$items = [];foreach($records as $record){if($record->type == MediaFile::TYPE_IMAGE) {$urlFile = $storage->getGenericImage($target_path, $record->uuid, $record->file);} else {$urlFile = $storage->getGenericFile($target_path, $record->uuid, $record->file);}if($record->preview) {$urlPreview = $storage->getGenericImage($target_path, $record->uuid, $record->preview);} else {$urlPreview = '';}$item = ['name' => $record->name,'file' => ['filename' => $record->file,'url' => $urlFile,'type' => $record->type,],'preview' => ['filename' => $record->preview,'url' => $urlPreview,],'actions' => ['link_delete' => $allowDelete ? $this->url()->fromRoute('media/files/delete', ['id' => $record->uuid ]) : '',]];array_push($items, $item);}return new JsonModel(['success' => true,'data' => ['items' => $items,'total' => $paginator->getTotalItemCount(),]]);} else {$categories = [];$categoryMapper = MediaCategoryMapper::getInstance($this->adapter);$records = $categoryMapper->fetchAllByCompanyId($currentCompany->id);foreach($records as $record){$categories[ $record->uuid ] = $record->name;}$form = new FileForm();$this->layout()->setTemplate('layout/layout-backend.phtml');$viewModel = new ViewModel();$viewModel->setTemplate('leaders-linked/media/files.phtml');$viewModel->setVariables(['categories' => $categories,'form' => $form,]);return $viewModel ;}} else {return new JsonModel(['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED']);}}public function uploadAction(){$currentUserPlugin = $this->plugin('currentUserPlugin');$currentCompany = $currentUserPlugin->getCompany();$currentUser = $currentUserPlugin->getUser();$request = $this->getRequest();if($request->isPost()) {$category = null;$uuid = \LeadersLinked\Library\Functions::sanitizeFilterString($this->params()->fromPost('category'));if($uuid) {$categoryMapper = \LeadersLinked\Mapper\MediaCategoryMapper::getInstance($this->adapter);$category = $categoryMapper->fetchOneByUuid($uuid);if(!$category) {if(!$category) {return new JsonModel(['success' => false,'data' => 'ERROR_MEDIA_CATEGORY_NOT_FOUND']);}if($category->company_id != $currentCompany->id) {return new JsonModel(['success' => false,'data' => 'ERROR_UNAUTHORIZED']);}}}if(!$category) {return new JsonModel(['success' => false,'data' => 'ERROR_MEDIA_CATEGORY_NOT_FOUND']);}$form = new FileForm();$dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());$form->setData($dataPost);if($form->isValid()) {$dataPost = (array) $form->getData();$hydrator = new ObjectPropertyHydrator();$mediaFile = new MediaFile();$hydrator->hydrate($dataPost, $mediaFile);$mediaFile->category_id = $category->id;$mediaFile->company_id = $category->company_id;$mediaFile->file = 'tmp';$mediaFile->type = 'tmp';$files = $this->getRequest()->getFiles()->toArray();$media_type = '';$media_tmp_filename = '';$media_filename = '';if (isset($files['file']) && empty($files['file']['error'])) {$media_tmp_filename = $files['file']['tmp_name'];$media_filename = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);$mime_type = mime_content_type($media_tmp_filename);if ($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {$media_type = MediaFile::TYPE_IMAGE;} else if ($mime_type == 'video/quicktime' || $mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {$media_type = MediaFile::TYPE_VIDEO;} else if ($mime_type == 'audio/wav' || $mime_type == 'audio/mpeg') {$media_type = MediaFile::TYPE_AUDIO;}}if(empty($media_type)) {return new JsonModel(['success' => false,'data' => 'ERROR_MEDIA_CATEGORY_NOT_FOUND']);}$fileMapper = MediaFileMapper::getInstance($this->adapter);if($fileMapper->insert($mediaFile)) {$mediaFile = $fileMapper->fetchOne($mediaFile->id);$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathMedia();$interal_path = 'data' . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'tmp';if(!file_exists($interal_path)) {mkdir($interal_path, 0775);}if ($media_type == MediaFile::TYPE_AUDIO) {if($storage->moveAndPutFile($target_path, $mediaFile->uuid, $media_tmp_filename, $media_filename)) {$mediaFile->type = $media_type;$mediaFile->file = $media_filename;$fileMapper->update($mediaFile);}} else if ($media_type == MediaFile::TYPE_IMAGE) {$filename = substr($media_filename, 0, strrpos($media_filename, '.')). '.png';$image = Image::getInstance($this->config);$full_tmp_filename = $image->uploadProcessWithOutChangeSize($media_tmp_filename, $filename);if($full_tmp_filename) {if($storage->putFile($target_path, $mediaFile->uuid, $full_tmp_filename)) {$mediaFile->type = $media_type;$mediaFile->file = $media_filename;$fileMapper->update($mediaFile);}}} else if ($media_type == MediaFile::TYPE_VIDEO) {try {$full_filename = $interal_path . DIRECTORY_SEPARATOR. $media_filename;$poster_filename = substr($media_filename, 0, strrpos($media_filename, '.')). '.jpg';$poster_full_filename = $interal_path . DIRECTORY_SEPARATOR . $poster_filename;move_uploaded_file($media_tmp_filename, $full_filename);$cmd = "/usr/bin/ffprobe -v error -of flat=s=_ -select_streams v:0 -show_entries stream=height,width,duration $full_filename";$response = trim(shell_exec($cmd));$source_duration = 0;$lines = explode("\n", $response);foreach ($lines as $line) {$line = trim(strtolower($line));if (strpos($line, 'duration') !== false) {$values = explode('=', $line);$source_duration = intval(str_replace($values[1], '#', ''), 10);}}if ($source_duration == 0) {$second_extract = '00:00:02';} else {if ($source_duration > 10) {$second_extract = '00:00:10';} else {$second_extract = '00:00:02';}}//$imageSize = $this->config['leaderslinked.image_sizes.feed_image_size'];//$cmd = "/usr/bin/ffmpeg -y -i $full_filename -pix_fmt yuvj422p -deinterlace -an -ss $second_extract -f mjpeg -t 1 -r 1 -y -s $imageSize $generateFile";// $cmd = "/usr/bin/ffmpeg -y -i $full_filename -pix_fmt yuvj422p -an -ss $second_extract -f mjpeg -t 1 -r 1 -y -s $imageSize $generateFile";$cmd = "/usr/bin/ffmpeg -y -i $full_filename -pix_fmt yuvj422p -an -ss $second_extract -f mjpeg -t 1 -r 1 -y $poster_full_filename";exec($cmd);$ok = $storage->putFile($target_path, $mediaFile->uuid, $poster_full_filename);$ok = $ok && $storage->putFile($target_path, $mediaFile->uuid, $full_filename);if( $ok ) {$mediaFile->type = $media_type;$mediaFile->file = basename($media_filename);$mediaFile->preview = basename($poster_filename);if($fileMapper->update($mediaFile)) {$videoConvert = new VideoConvert();$videoConvert->uuid = $mediaFile->uuid;$videoConvert->filename = basename($media_filename);$videoConvert->type = VideoConvert::TYPE_MEDIA;$videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);$videoConvertMapper->insert($videoConvert);}}// @unlink($full_filename);//@unlink($generate_full_filename);} catch (\Throwable $e) {$fileMapper->delete($mediaFile);return new JsonModel(['success' => false,'data' => 'ERROR_UPLOAD_FILE']);}}$this->logger->info('Se agrego el archivo a la media library ' . $mediaFile->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);return new JsonModel(['success' => true,'data' => 'LABEL_RECORD_ADDED']);} else {$data = ['success' => false,'data' => $fileMapper->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');$fileMapper = MediaFileMapper::getInstance($this->adapter);$file = $fileMapper->fetchOneByUuid($id);if(!$file) {return new JsonModel(['success' => false,'data' => 'ERROR_MEDIA_FILE_NOT_FOUND']);}if($file->company_id != $currentCompany->id) {return new JsonModel(['success' => false,'data' => 'ERROR_UNAUTHORIZED']);}if($request->isPost()) {$result = $fileMapper->delete($file);if($result) {$this->logger->info('Se borro el el archivo de la media query : ' . $file->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);$storage = Storage::getInstance($this->config, $this->adapter);$target_path = $storage->getPathMedia();$storage->deleteFile($target_path, $file->uuid, $file->file);if($file->type == MediaFile::TYPE_VIDEO) {$videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);$videoConvertMapper->deleteByUuidAndType($file->uuid, $file->type);}$data = ['success' => true,'data' => 'LABEL_RECORD_DELETED'];} else {$data = ['success' => false,'data' => $fileMapper->getError()];return new JsonModel($data);}} else {$data = ['success' => false,'data' => 'ERROR_METHOD_NOT_ALLOWED'];return new JsonModel($data);}return new JsonModel($data);}}