From 03ae689191af2b7843e8c3f2a4f9b7755b2c2035 Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Fri, 6 Jul 2018 17:15:53 +0200 Subject: [PATCH 01/10] Add wav in AudioFilter and tif in ImageFilter --- src/FileUploadControl.php | 1234 ++++++++++++++++++------------------ src/Filter/AudioFilter.php | 54 +- src/Filter/ImageFilter.php | 55 +- 3 files changed, 673 insertions(+), 670 deletions(-) diff --git a/src/FileUploadControl.php b/src/FileUploadControl.php index fadfbde..615a828 100644 --- a/src/FileUploadControl.php +++ b/src/FileUploadControl.php @@ -1,617 +1,617 @@ - - * @package Zet\FileUpload - */ -class FileUploadControl extends \Nette\Forms\Controls\UploadControl { - - # -------------------------------------------------------------------- - # Registration - # -------------------------------------------------------------------- - /** - * @static - * @param $systemContainer - * @param array $configuration - */ - public static function register(\Nette\DI\Container $systemContainer, $configuration = []) { - $class = __CLASS__; - \Nette\Forms\Container::extensionMethod("addFileUpload", function( - \Nette\Forms\Container $container, $name, $maxFiles = null, $maxFileSize = null - ) use ($class, $systemContainer, $configuration) { - $maxFiles = is_null($maxFiles) ? $configuration["maxFiles"] : $maxFiles; - $maxFileSize = is_null($maxFileSize) ? $configuration["maxFileSize"] : $maxFileSize; - - /** @var FileUploadControl $component */ - $component = new $class($name, $maxFiles, $maxFileSize); - $component->setContainer($systemContainer); - $component->setUploadModel($configuration["uploadModel"]); - $component->setFileFilter($configuration["fileFilter"]); - $component->setRenderer($configuration["renderer"]); - - if($configuration["translator"] === null) { - $translator = $systemContainer->getByType(ITranslator::class, FALSE); - $component->setTranslator($translator); - } else { - $component->setTranslator($configuration["translator"]); - } - - $component->setAutoTranslate($configuration["autoTranslate"]); - $component->setMessages($configuration["messages"]); - $component->setUploadSettings($configuration["uploadSettings"]); - - $container->addComponent($component, $name); - - return $component; - }); - } - - /** - * Vloží CSS do stránky. - * - * @static - * @param string $basePath - */ - public static function getHead($basePath) { - echo ''; - } - - /** - * Vloží skripty do stránky. - * - * @static - * @param string $basePath - */ - public static function getScripts($basePath) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - - # -------------------------------------------------------------------- - # Control definition - # -------------------------------------------------------------------- - /** - * Povolí nahrávat pouze obrázky png, jpeg, jpg, gif. - * - * @var string - */ - const FILTER_IMAGES = 'Zet\FileUpload\Filter\ImageFilter'; - - /** - * Povolí nahrávat pouze dokumenty typu txt, doc, docx, xls, xlsx, ppt, pptx, pdf. - * - * @var string - */ - const FILTER_DOCUMENTS = 'Zet\FileUpload\Filter\DocumentFilter'; - - /** - * Povolí nahrávat soubory zip, tar, rar, 7z. - * - * @var string - */ - const FILTER_ARCHIVE = 'Zet\FileUpload\Filter\ArchiveFilter'; - - /** - * Povolí nahrávat pouze soubory mp3, ogg, aiff. - * - * @var string - */ - const FILTER_AUDIO = 'Zet\FileUpload\Filter\AudioFilter'; - - /** - * @var \Nette\DI\Container - */ - private $container; - - /** - * @var \Nette\Caching\Cache - */ - private $cache; - - /** - * @var int - */ - private $maxFiles; - - /** - * @var int - */ - private $maxFileSize; - - /** - * @var string - */ - private $fileSizeString; - - /** - * @var \Zet\FileUpload\Model\UploadController - */ - private $controller; - - /** - * @var string - */ - private $uploadModel; - - /** - * Třída pro filtrování nahrávaných souborů. - * - * @var string - */ - private $fileFilter; - - /** - * Pole vlastních definovaných parametrů. - * - * @var array - */ - private $params = []; - - /** - * @var string - */ - private $renderer; - - /** - * @var string - */ - private $token; - - /** - * @var DefaultFile[] - */ - private $defaultFiles = []; - - /** - * Seznam chybových hlášek. - * Chyby uploaderu: - * - maxFiles - * - maxSize - * - fileTypes - * - * Chyby v PHP: - * - fileSize - * - partialUpload - * - noFile - * - tmpFolder - * - cannotWrite - * - stopped - * - * @var string[] - */ - private $messages = []; - - /** - * Automaticky překládat všechny chybové zprávy? - * - * @var bool - */ - private $autoTranslate = false; - - /** - * Pole vlastních hodnot pro konfiguraci uploaderu. - * - * @var array - */ - private $uploadSettings = []; - - /** - * FileUploadControl constructor. - * - * @param string $name Název inputu. - * @param int $maxFiles Maximální počet souborů. - * @param string $maxFileSize Maximální velikosti souboru. - */ - public function __construct($name, $maxFiles, $maxFileSize = null) { - parent::__construct($name); - $this->maxFiles = $maxFiles; - if(is_null($maxFileSize)) { - $this->fileSizeString = ini_get("upload_max_filesize") . "B"; - $this->maxFileSize = $this->parseIniSize(ini_get("upload_max_filesize")); - } else { - $this->fileSizeString = $maxFileSize . "B"; - $this->maxFileSize = $this->parseIniSize($maxFileSize); - } - $this->controller = new Model\UploadController($this); - $this->token = uniqid(); - } - - /** - * Ověření nastavených direktiv, zda nepřekročují nastavení serveru. - * - * @throws \Zet\FileUpload\InvalidValueException - */ - private function checkSettings() { - $postMaxSize = $this->parseIniSize($postMaxSizeString = ini_get("post_max_size")); - $iniMaxFileSize = $this->parseIniSize($iniMaxFileSizeString = ini_get("upload_max_filesize")); - - if($this->maxFileSize > $postMaxSize) { - throw new InvalidValueException( - sprintf( - "Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `post_max_size` (%s).", - $postMaxSizeString - ) - ); - } else if($this->maxFileSize > $iniMaxFileSize) { - throw new InvalidValueException( - sprintf( - "Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `upload_max_filesize` (%s).", - $iniMaxFileSizeString - ) - ); - } - } - - /** - * @param Form $form - */ - protected function attached($form) { - parent::attached($form); - $this->form->addComponent($this->controller, "uploadController" . ucfirst($this->name)); - } - - # -------------------------------------------------------------------- - # Setters \ Getters - # -------------------------------------------------------------------- - /** - * @param \Nette\DI\Container $container - * @internal - */ - public function setContainer($container) { - $this->container = $container; - /** @noinspection PhpParamsInspection */ - $this->cache = new \Nette\Caching\Cache($this->container->getByType('Nette\Caching\IStorage')); - /** @noinspection PhpParamsInspection */ - $this->controller->setRequest($container->getByType('\Nette\Http\Request')); - } - - /** - * @return \Nette\DI\Container - * @internal - */ - public function getContainer() { - return $this->container; - } - - /** - * @return int - * @internal - */ - public function getMaxFiles() { - return $this->maxFiles; - } - - /** - * @param int $maxFiles - * @return $this - */ - public function setMaxFiles($maxFiles) { - $this->maxFiles = $maxFiles; - - return $this; - } - - /** - * @return Model\IUploadModel - * @internal - */ - public function getUploadModel() { - if(is_null($this->uploadModel)) { - return new Model\BaseUploadModel(); - } else { - $model = $this->container->getByType($this->uploadModel); - if($model instanceof Model\IUploadModel) { - return $model; - } else { - throw new \Nette\InvalidStateException( - "Předaný model není instancí \\Zet\\FileUpload\\Model\\IUploadModel." - ); - } - } - } - - /** - * @param string $uploadModel - * @return $this - */ - public function setUploadModel($uploadModel) { - $this->uploadModel = $uploadModel; - - return $this; - } - - /** - * @return int - * @internal - */ - public function getMaxFileSize() { - return $this->maxFileSize; - } - - /** - * @param int $maxFileSize - * @return $this - */ - public function setMaxFileSize($maxFileSize) { - $this->maxFileSize = $this->parseIniSize($maxFileSize); - - return $this; - } - - /** - * @return \Nette\Caching\Cache - */ - public function getCache() { - return $this->cache; - } - - /** - * @return string - * @internal - */ - public function getFileSizeString() { - return $this->fileSizeString; - } - - /** - * @return string - * @internal - */ - public function getFileFilter() { - return $this->fileFilter; - } - - /** - * Nastaví třídu pro filtrování nahrávaných souborů. - * - * @param string $fileFilter - * @return $this - */ - public function setFileFilter($fileFilter) { - $this->fileFilter = $fileFilter; - - return $this; - } - - /** - * Vrátí název pro frontu s tokenem. - * - * @param string $token - * @return string - * @internal - */ - public function getTokenizedCacheName($token) { - return $this->getHtmlId() . "-" . $token; - } - - /** - * Vrátí identifikační token. - * - * @return string - * @internal - */ - public function getToken() { - return $this->token; - } - - /** - * Nastavení vlastních parametrů k uploadovanému souboru. - * - * @param array $params - * @return FileUploadControl - */ - public function setParams(array $params) { - $this->params = $params; - - return $this; - } - - /** - * @return array - */ - public function getParams() { - return $this->params; - } - - /** - * @param string $renderer - * @return FileUploadControl - */ - public function setRenderer($renderer) { - $this->renderer = $renderer; - - return $this; - } - - /** - * @return string - */ - public function getRenderer() { - return $this->renderer; - } - - /** - * @return DefaultFile[] - */ - public function getDefaultFiles() { - return $this->defaultFiles; - } - - /** - * @param DefaultFile[] $defaultFiles - * @return FileUploadControl - */ - public function setDefaultFiles($defaultFiles) { - $this->defaultFiles = $defaultFiles; - - return $this; - } - - /** - * @param DefaultFile $defaultFile - * @return FileUploadControl - */ - public function addDefaultFile($defaultFile) { - $this->defaultFiles[] = $defaultFile; - - return $this; - } - - /** - * @param string[] $messages - * @return FileUploadControl - */ - public function setMessages(array $messages) { - $this->messages = $messages; - - return $this; - } - - /** - * @param string $index - * @param string $message - * @return FileUploadControl - */ - public function setMessage($index, $message) { - $this->messages[ $index ] = $message; - - return $this; - } - - /** - * @return string[] - */ - public function getMessages() { - return $this->messages; - } - - /** - * @return bool - */ - public function isAutoTranslate() { - return $this->autoTranslate; - } - - /** - * @param bool $autoTranslate - * @return FileUploadControl - */ - public function setAutoTranslate($autoTranslate) { - $this->autoTranslate = $autoTranslate; - - return $this; - } - - /** - * @return array - */ - public function getUploadSettings() { - return $this->uploadSettings; - } - - /** - * @param array $uploadSettings - * @return FileUploadControl - */ - public function setUploadSettings($uploadSettings) { - $this->uploadSettings = $uploadSettings; - - return $this; - } - - /** - * @param string $name - * @param mixed $value - * @return FileUploadControl - */ - public function addUploadSettings($name, $value) { - $this->uploadSettings[ $name ] = $value; - - return $this; - } - - # -------------------------------------------------------------------- - # Methods - # -------------------------------------------------------------------- - /** - * Získání identifikačního tokenu. - */ - public function loadHttpData() { - parent::loadHttpData(); - - /** @var \Nette\Http\Request $request */ - $request = $this->getContainer()->getByType('\Nette\Http\Request'); - $this->token = $request->getPost($this->getHtmlName() . "-token"); - } - - /** - * @return \Nette\Utils\Html - * @throws InvalidValueException - */ - public function getControl() { - $this->checkSettings(); - - $this->setOption("rendered", true); - - $container = \Nette\Utils\Html::el("div class='zet-fileupload-container'"); - $container->id = $this->getHtmlId() . "-container"; - - $token = \Nette\Utils\Html::el("input type='hidden' value='" . $this->token . "'"); - $token->addAttributes(["name" => $this->getHtmlName() . "-token"]); - - $container->addHtml($token); - $container->addHtml($this->controller->getJavaScriptTemplate()); - $container->addHtml($this->controller->getControlTemplate()); - - return $container; - } - - /** - * Vrátí nacachované hodnoty z controlleru. - * - * @return mixed|NULL - */ - public function getValue() { - $files = $this->cache->load($this->getTokenizedCacheName($this->token)); - - return $files; - } - - /** - * Delete cache - */ - public function __destruct() { - $this->cache->remove($this->getTokenizedCacheName($this->token)); - } - - /** - * Parses ini size - * - * @param string $value - * @return int - */ - private function parseIniSize($value) { - $units = ['k' => 1024, 'm' => 1048576, 'g' => 1073741824]; - $unit = strtolower(substr($value, -1)); - if(is_numeric($unit) || !isset($units[ $unit ])) { - return $value; - } - - return ((int)$value) * $units[ $unit ]; - } - -} + + * @package Zet\FileUpload + */ +class FileUploadControl extends \Nette\Forms\Controls\UploadControl { + + # -------------------------------------------------------------------- + # Registration + # -------------------------------------------------------------------- + /** + * @static + * @param $systemContainer + * @param array $configuration + */ + public static function register(\Nette\DI\Container $systemContainer, $configuration = []) { + $class = __CLASS__; + \Nette\Forms\Container::extensionMethod("addFileUpload", function( + \Nette\Forms\Container $container, $name, $maxFiles = null, $maxFileSize = null + ) use ($class, $systemContainer, $configuration) { + $maxFiles = is_null($maxFiles) ? $configuration["maxFiles"] : $maxFiles; + $maxFileSize = is_null($maxFileSize) ? $configuration["maxFileSize"] : $maxFileSize; + + /** @var FileUploadControl $component */ + $component = new $class($name, $maxFiles, $maxFileSize); + $component->setContainer($systemContainer); + $component->setUploadModel($configuration["uploadModel"]); + $component->setFileFilter($configuration["fileFilter"]); + $component->setRenderer($configuration["renderer"]); + + if($configuration["translator"] === null) { + $translator = $systemContainer->getByType(ITranslator::class, FALSE); + $component->setTranslator($translator); + } else { + $component->setTranslator($configuration["translator"]); + } + + $component->setAutoTranslate($configuration["autoTranslate"]); + $component->setMessages($configuration["messages"]); + $component->setUploadSettings($configuration["uploadSettings"]); + + $container->addComponent($component, $name); + + return $component; + }); + } + + /** + * Vloží CSS do stránky. + * + * @static + * @param string $basePath + */ + public static function getHead($basePath) { + echo ''; + } + + /** + * Vloží skripty do stránky. + * + * @static + * @param string $basePath + */ + public static function getScripts($basePath) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + + # -------------------------------------------------------------------- + # Control definition + # -------------------------------------------------------------------- + /** + * Povolí nahrávat pouze obrázky png, jpeg, jpg, gif, tif. + * + * @var string + */ + const FILTER_IMAGES = 'Zet\FileUpload\Filter\ImageFilter'; + + /** + * Povolí nahrávat pouze dokumenty typu txt, doc, docx, xls, xlsx, ppt, pptx, pdf. + * + * @var string + */ + const FILTER_DOCUMENTS = 'Zet\FileUpload\Filter\DocumentFilter'; + + /** + * Povolí nahrávat soubory zip, tar, rar, 7z. + * + * @var string + */ + const FILTER_ARCHIVE = 'Zet\FileUpload\Filter\ArchiveFilter'; + + /** + * Povolí nahrávat pouze soubory mp3, ogg, aiff, wav. + * + * @var string + */ + const FILTER_AUDIO = 'Zet\FileUpload\Filter\AudioFilter'; + + /** + * @var \Nette\DI\Container + */ + private $container; + + /** + * @var \Nette\Caching\Cache + */ + private $cache; + + /** + * @var int + */ + private $maxFiles; + + /** + * @var int + */ + private $maxFileSize; + + /** + * @var string + */ + private $fileSizeString; + + /** + * @var \Zet\FileUpload\Model\UploadController + */ + private $controller; + + /** + * @var string + */ + private $uploadModel; + + /** + * Třída pro filtrování nahrávaných souborů. + * + * @var string + */ + private $fileFilter; + + /** + * Pole vlastních definovaných parametrů. + * + * @var array + */ + private $params = []; + + /** + * @var string + */ + private $renderer; + + /** + * @var string + */ + private $token; + + /** + * @var DefaultFile[] + */ + private $defaultFiles = []; + + /** + * Seznam chybových hlášek. + * Chyby uploaderu: + * - maxFiles + * - maxSize + * - fileTypes + * + * Chyby v PHP: + * - fileSize + * - partialUpload + * - noFile + * - tmpFolder + * - cannotWrite + * - stopped + * + * @var string[] + */ + private $messages = []; + + /** + * Automaticky překládat všechny chybové zprávy? + * + * @var bool + */ + private $autoTranslate = false; + + /** + * Pole vlastních hodnot pro konfiguraci uploaderu. + * + * @var array + */ + private $uploadSettings = []; + + /** + * FileUploadControl constructor. + * + * @param string $name Název inputu. + * @param int $maxFiles Maximální počet souborů. + * @param string $maxFileSize Maximální velikosti souboru. + */ + public function __construct($name, $maxFiles, $maxFileSize = null) { + parent::__construct($name); + $this->maxFiles = $maxFiles; + if(is_null($maxFileSize)) { + $this->fileSizeString = ini_get("upload_max_filesize") . "B"; + $this->maxFileSize = $this->parseIniSize(ini_get("upload_max_filesize")); + } else { + $this->fileSizeString = $maxFileSize . "B"; + $this->maxFileSize = $this->parseIniSize($maxFileSize); + } + $this->controller = new Model\UploadController($this); + $this->token = uniqid(); + } + + /** + * Ověření nastavených direktiv, zda nepřekročují nastavení serveru. + * + * @throws \Zet\FileUpload\InvalidValueException + */ + private function checkSettings() { + $postMaxSize = $this->parseIniSize($postMaxSizeString = ini_get("post_max_size")); + $iniMaxFileSize = $this->parseIniSize($iniMaxFileSizeString = ini_get("upload_max_filesize")); + + if($this->maxFileSize > $postMaxSize) { + throw new InvalidValueException( + sprintf( + "Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `post_max_size` (%s).", + $postMaxSizeString + ) + ); + } else if($this->maxFileSize > $iniMaxFileSize) { + throw new InvalidValueException( + sprintf( + "Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `upload_max_filesize` (%s).", + $iniMaxFileSizeString + ) + ); + } + } + + /** + * @param Form $form + */ + protected function attached($form) { + parent::attached($form); + $this->form->addComponent($this->controller, "uploadController" . ucfirst($this->name)); + } + + # -------------------------------------------------------------------- + # Setters \ Getters + # -------------------------------------------------------------------- + /** + * @param \Nette\DI\Container $container + * @internal + */ + public function setContainer($container) { + $this->container = $container; + /** @noinspection PhpParamsInspection */ + $this->cache = new \Nette\Caching\Cache($this->container->getByType('Nette\Caching\IStorage')); + /** @noinspection PhpParamsInspection */ + $this->controller->setRequest($container->getByType('\Nette\Http\Request')); + } + + /** + * @return \Nette\DI\Container + * @internal + */ + public function getContainer() { + return $this->container; + } + + /** + * @return int + * @internal + */ + public function getMaxFiles() { + return $this->maxFiles; + } + + /** + * @param int $maxFiles + * @return $this + */ + public function setMaxFiles($maxFiles) { + $this->maxFiles = $maxFiles; + + return $this; + } + + /** + * @return Model\IUploadModel + * @internal + */ + public function getUploadModel() { + if(is_null($this->uploadModel)) { + return new Model\BaseUploadModel(); + } else { + $model = $this->container->getByType($this->uploadModel); + if($model instanceof Model\IUploadModel) { + return $model; + } else { + throw new \Nette\InvalidStateException( + "Předaný model není instancí \\Zet\\FileUpload\\Model\\IUploadModel." + ); + } + } + } + + /** + * @param string $uploadModel + * @return $this + */ + public function setUploadModel($uploadModel) { + $this->uploadModel = $uploadModel; + + return $this; + } + + /** + * @return int + * @internal + */ + public function getMaxFileSize() { + return $this->maxFileSize; + } + + /** + * @param int $maxFileSize + * @return $this + */ + public function setMaxFileSize($maxFileSize) { + $this->maxFileSize = $this->parseIniSize($maxFileSize); + + return $this; + } + + /** + * @return \Nette\Caching\Cache + */ + public function getCache() { + return $this->cache; + } + + /** + * @return string + * @internal + */ + public function getFileSizeString() { + return $this->fileSizeString; + } + + /** + * @return string + * @internal + */ + public function getFileFilter() { + return $this->fileFilter; + } + + /** + * Nastaví třídu pro filtrování nahrávaných souborů. + * + * @param string $fileFilter + * @return $this + */ + public function setFileFilter($fileFilter) { + $this->fileFilter = $fileFilter; + + return $this; + } + + /** + * Vrátí název pro frontu s tokenem. + * + * @param string $token + * @return string + * @internal + */ + public function getTokenizedCacheName($token) { + return $this->getHtmlId() . "-" . $token; + } + + /** + * Vrátí identifikační token. + * + * @return string + * @internal + */ + public function getToken() { + return $this->token; + } + + /** + * Nastavení vlastních parametrů k uploadovanému souboru. + * + * @param array $params + * @return FileUploadControl + */ + public function setParams(array $params) { + $this->params = $params; + + return $this; + } + + /** + * @return array + */ + public function getParams() { + return $this->params; + } + + /** + * @param string $renderer + * @return FileUploadControl + */ + public function setRenderer($renderer) { + $this->renderer = $renderer; + + return $this; + } + + /** + * @return string + */ + public function getRenderer() { + return $this->renderer; + } + + /** + * @return DefaultFile[] + */ + public function getDefaultFiles() { + return $this->defaultFiles; + } + + /** + * @param DefaultFile[] $defaultFiles + * @return FileUploadControl + */ + public function setDefaultFiles($defaultFiles) { + $this->defaultFiles = $defaultFiles; + + return $this; + } + + /** + * @param DefaultFile $defaultFile + * @return FileUploadControl + */ + public function addDefaultFile($defaultFile) { + $this->defaultFiles[] = $defaultFile; + + return $this; + } + + /** + * @param string[] $messages + * @return FileUploadControl + */ + public function setMessages(array $messages) { + $this->messages = $messages; + + return $this; + } + + /** + * @param string $index + * @param string $message + * @return FileUploadControl + */ + public function setMessage($index, $message) { + $this->messages[ $index ] = $message; + + return $this; + } + + /** + * @return string[] + */ + public function getMessages() { + return $this->messages; + } + + /** + * @return bool + */ + public function isAutoTranslate() { + return $this->autoTranslate; + } + + /** + * @param bool $autoTranslate + * @return FileUploadControl + */ + public function setAutoTranslate($autoTranslate) { + $this->autoTranslate = $autoTranslate; + + return $this; + } + + /** + * @return array + */ + public function getUploadSettings() { + return $this->uploadSettings; + } + + /** + * @param array $uploadSettings + * @return FileUploadControl + */ + public function setUploadSettings($uploadSettings) { + $this->uploadSettings = $uploadSettings; + + return $this; + } + + /** + * @param string $name + * @param mixed $value + * @return FileUploadControl + */ + public function addUploadSettings($name, $value) { + $this->uploadSettings[ $name ] = $value; + + return $this; + } + + # -------------------------------------------------------------------- + # Methods + # -------------------------------------------------------------------- + /** + * Získání identifikačního tokenu. + */ + public function loadHttpData() { + parent::loadHttpData(); + + /** @var \Nette\Http\Request $request */ + $request = $this->getContainer()->getByType('\Nette\Http\Request'); + $this->token = $request->getPost($this->getHtmlName() . "-token"); + } + + /** + * @return \Nette\Utils\Html + * @throws InvalidValueException + */ + public function getControl() { + $this->checkSettings(); + + $this->setOption("rendered", true); + + $container = \Nette\Utils\Html::el("div class='zet-fileupload-container'"); + $container->id = $this->getHtmlId() . "-container"; + + $token = \Nette\Utils\Html::el("input type='hidden' value='" . $this->token . "'"); + $token->addAttributes(["name" => $this->getHtmlName() . "-token"]); + + $container->addHtml($token); + $container->addHtml($this->controller->getJavaScriptTemplate()); + $container->addHtml($this->controller->getControlTemplate()); + + return $container; + } + + /** + * Vrátí nacachované hodnoty z controlleru. + * + * @return mixed|NULL + */ + public function getValue() { + $files = $this->cache->load($this->getTokenizedCacheName($this->token)); + + return $files; + } + + /** + * Delete cache + */ + public function __destruct() { + $this->cache->remove($this->getTokenizedCacheName($this->token)); + } + + /** + * Parses ini size + * + * @param string $value + * @return int + */ + private function parseIniSize($value) { + $units = ['k' => 1024, 'm' => 1048576, 'g' => 1073741824]; + $unit = strtolower(substr($value, -1)); + if(is_numeric($unit) || !isset($units[ $unit ])) { + return $value; + } + + return ((int)$value) * $units[ $unit ]; + } + +} diff --git a/src/Filter/AudioFilter.php b/src/Filter/AudioFilter.php index 1e607d3..dbadb10 100644 --- a/src/Filter/AudioFilter.php +++ b/src/Filter/AudioFilter.php @@ -1,27 +1,29 @@ - - * @package Zet\FileUpload\Filter - */ -class AudioFilter extends BaseFilter { - - /** - * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. - * - * @example array("text/plain" => "txt") - * @return string[] - */ - protected function getMimeTypes() { - return [ - "audio/mpeg3" => "mp3", - "audio/x-mpeg-3" => "mp3", - "audio/ogg" => "ogg", - "audio/x-aiff" => "aiff" - ]; - } + + * @package Zet\FileUpload\Filter + */ +class AudioFilter extends BaseFilter { + + /** + * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. + * + * @example array("text/plain" => "txt") + * @return string[] + */ + protected function getMimeTypes() { + return [ + "audio/mpeg3" => "mp3", + "audio/x-mpeg-3" => "mp3", + "audio/ogg" => "ogg", + "audio/x-aiff" => "aiff", + "audio/x-wav" => "wav", + "audio/wav" => "wav", + ]; + } } \ No newline at end of file diff --git a/src/Filter/ImageFilter.php b/src/Filter/ImageFilter.php index 69cbbd2..b50fc71 100644 --- a/src/Filter/ImageFilter.php +++ b/src/Filter/ImageFilter.php @@ -1,28 +1,29 @@ - - * @package Zet\FileUpload\Filter - */ -class ImageFilter extends BaseFilter { - - /** - * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. - * - * @example array("text/plain" => "txt") - * @return string[] - */ - protected function getMimeTypes() { - return [ - "image/png" => "png", - "image/pjpeg" => "jpeg", - "image/jpeg" => "jpg", - "image/gif" => "gif", - ]; - } - + + * @package Zet\FileUpload\Filter + */ +class ImageFilter extends BaseFilter { + + /** + * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. + * + * @example array("text/plain" => "txt") + * @return string[] + */ + protected function getMimeTypes() { + return [ + "image/png" => "png", + "image/pjpeg" => "jpeg", + "image/jpeg" => "jpg", + "image/gif" => "gif", + 'image/tif' => 'tif', + ]; + } + } \ No newline at end of file From 759476d674cbcdc273c5f0596904399e73c69198 Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Fri, 6 Jul 2018 17:20:07 +0200 Subject: [PATCH 02/10] Fix Bootstrap3Render - 2x return --- src/Template/Renderer/Bootstrap3Renderer.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Template/Renderer/Bootstrap3Renderer.php b/src/Template/Renderer/Bootstrap3Renderer.php index 318dcc0..6d60fc1 100644 --- a/src/Template/Renderer/Bootstrap3Renderer.php +++ b/src/Template/Renderer/Bootstrap3Renderer.php @@ -66,8 +66,6 @@ public function buildDefaultTemplate() { $customContainer->addHtml($container); return $customContainer; - - return $customContainer; } /** From 2ae87bb48b0bb1963e9a30087773a182d042ee1f Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Fri, 6 Jul 2018 17:26:25 +0200 Subject: [PATCH 03/10] Fix controller.js - vicenasobny upload --- src/www/fileupload/controller.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/www/fileupload/controller.js b/src/www/fileupload/controller.js index 9d93ace..6889072 100644 --- a/src/www/fileupload/controller.js +++ b/src/www/fileupload/controller.js @@ -463,7 +463,7 @@ FileUploadController.prototype = { * @returns {boolean} */ canUploadNextFile: function () { - return this.uploaded < this.config.maxFiles || this.addedFiles < this.config.maxFiles; + return this.uploaded < this.config.maxFiles && this.addedFiles < this.config.maxFiles; }, /** From ca1f0ae451ee2a23af783467949216ebb46474ad Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Thu, 16 Apr 2020 20:19:40 +0200 Subject: [PATCH 04/10] Update for Nette 3.0 --- .gitignore | 2 + composer.json | 54 +- src/Exceptions.php | 30 +- src/FileUploadControl.php | 592 ++++++++++-------- src/FileUploadExtension.php | 128 ++-- src/Filter/ArchiveFilter.php | 59 +- src/Filter/AudioFilter.php | 25 +- src/Filter/BaseFilter.php | 137 ++-- src/Filter/DocumentFilter.php | 67 +- src/Filter/IMimeTypeFilter.php | 61 +- src/Filter/ImageFilter.php | 24 +- src/Model/BaseUploadModel.php | 102 +-- src/Model/DefaultFile.php | 64 +- src/Model/IUploadModel.php | 81 +-- src/Model/UploadController.php | 477 +++++++------- src/Template/JavascriptBuilder.php | 139 ++-- src/Template/Renderer/BaseRenderer.php | 117 ++-- src/Template/Renderer/Bootstrap3Renderer.php | 117 ++-- src/Template/Renderer/Bootstrap4Renderer.php | 113 ++-- src/Template/Renderer/Html5Renderer.php | 160 ++--- src/Template/Renderer/IUploadRenderer.php | 14 +- src/Template/js.latte | 2 +- src/www/fileupload/controller.js | 136 ++-- src/www/fileupload/functions.js | 8 +- src/www/fileupload/js/app.js | 10 +- .../js/cors/jquery.postmessage-transport.js | 8 +- .../js/cors/jquery.xdr-transport.js | 4 +- .../js/jquery.fileupload-angular.js | 22 +- .../fileupload/js/jquery.fileupload-audio.js | 20 +- .../fileupload/js/jquery.fileupload-image.js | 28 +- .../js/jquery.fileupload-jquery-ui.js | 20 +- .../js/jquery.fileupload-process.js | 24 +- src/www/fileupload/js/jquery.fileupload-ui.js | 78 +-- .../js/jquery.fileupload-validate.js | 20 +- .../fileupload/js/jquery.fileupload-video.js | 20 +- src/www/fileupload/js/jquery.fileupload.js | 170 ++--- .../fileupload/js/jquery.iframe-transport.js | 10 +- src/www/fileupload/js/main.js | 8 +- src/www/fileupload/style.css | 2 +- 39 files changed, 1691 insertions(+), 1462 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5973cc2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +composer.lock diff --git a/composer.json b/composer.json index f70591d..0d35d26 100644 --- a/composer.json +++ b/composer.json @@ -1,25 +1,29 @@ -{ - "name": "jzechy/jquery-fileupload", - "description": "Nette UploadControl rozšířené o blueimp jQuery FileUpload.", - "homepage": "https://github.com/JZechy/jQuery-FileUpload", - "license": "MIT", - "authors": [ - { - "name": "Jan 'Zechy' Zechovský", - "email": "email@zechy.cz", - "homepage": "http://zechy.cz" - } - ], - "require": { - "php": ">=5.6.0", - "nette/forms": "^v2.4.0", - "nette/http": "^v2.4.0", - "nette/utils": "^v2.4.0", - "nette/di": "^v2.4.0", - "nette/application": "^v2.4.0", - "latte/latte": "^v2.4.0" - }, - "autoload": { - "classmap": ["src/"] - } -} +{ + "name": "ijvo/jquery-fileupload", + "description": "Nette UploadControl rozšířené o blueimp jQuery FileUpload.", + "homepage": "https://github.com/JZechy/jQuery-FileUpload", + "license": "MIT", + "authors": [ + { + "name": "Jan 'Zechy' Zechovský", + "email": "email@zechy.cz", + "homepage": "http://zechy.cz" + }, + { + "name": "Ing. Jaroslav Vaculik -IJVo", + "homepage": "https://ijvo.cz" + } + ], + "require": { + "php": ">=7.2.0", + "nette/forms": "^3.0", + "nette/http": "^3.0", + "nette/utils": "^3.0", + "nette/di": "^3.0", + "nette/application": "^3.0", + "latte/latte": "^2.5" + }, + "autoload": { + "classmap": ["src/"] + } +} diff --git a/src/Exceptions.php b/src/Exceptions.php index f72c4ed..da1bc2c 100644 --- a/src/Exceptions.php +++ b/src/Exceptions.php @@ -1,12 +1,18 @@ - - * @package Zet\FileUpload - */ -class InvalidFileException extends \Exception {} - -class InvalidValueException extends \Exception {} \ No newline at end of file + + * @package Zet\FileUpload + */ +class InvalidFileException extends \Exception +{ // @CSIgnoreLine +} + +class InvalidValueException extends \Exception +{ // @CSIgnoreLine +} diff --git a/src/FileUploadControl.php b/src/FileUploadControl.php index 615a828..0fddb5d 100644 --- a/src/FileUploadControl.php +++ b/src/FileUploadControl.php @@ -1,10 +1,10 @@ * @package Zet\FileUpload */ -class FileUploadControl extends \Nette\Forms\Controls\UploadControl { - - # -------------------------------------------------------------------- - # Registration - # -------------------------------------------------------------------- - /** - * @static - * @param $systemContainer - * @param array $configuration - */ - public static function register(\Nette\DI\Container $systemContainer, $configuration = []) { - $class = __CLASS__; - \Nette\Forms\Container::extensionMethod("addFileUpload", function( - \Nette\Forms\Container $container, $name, $maxFiles = null, $maxFileSize = null - ) use ($class, $systemContainer, $configuration) { - $maxFiles = is_null($maxFiles) ? $configuration["maxFiles"] : $maxFiles; - $maxFileSize = is_null($maxFileSize) ? $configuration["maxFileSize"] : $maxFileSize; - - /** @var FileUploadControl $component */ - $component = new $class($name, $maxFiles, $maxFileSize); - $component->setContainer($systemContainer); - $component->setUploadModel($configuration["uploadModel"]); - $component->setFileFilter($configuration["fileFilter"]); - $component->setRenderer($configuration["renderer"]); - - if($configuration["translator"] === null) { - $translator = $systemContainer->getByType(ITranslator::class, FALSE); - $component->setTranslator($translator); - } else { - $component->setTranslator($configuration["translator"]); - } - - $component->setAutoTranslate($configuration["autoTranslate"]); - $component->setMessages($configuration["messages"]); - $component->setUploadSettings($configuration["uploadSettings"]); - - $container->addComponent($component, $name); - - return $component; - }); - } - - /** - * Vloží CSS do stránky. - * - * @static - * @param string $basePath - */ - public static function getHead($basePath) { - echo ''; - } - - /** - * Vloží skripty do stránky. - * - * @static - * @param string $basePath - */ - public static function getScripts($basePath) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - - # -------------------------------------------------------------------- - # Control definition - # -------------------------------------------------------------------- +class FileUploadControl extends \Nette\Forms\Controls\UploadControl +{ + + use \Nette\SmartObject; + + private const PREFIX = 'jqfu'; + + // -------------------------------------------------------------------- + // Control definition + // -------------------------------------------------------------------- + /** * Povolí nahrávat pouze obrázky png, jpeg, jpg, gif, tif. * * @var string */ - const FILTER_IMAGES = 'Zet\FileUpload\Filter\ImageFilter'; - + private const FILTER_IMAGES = 'Zet\FileUpload\Filter\ImageFilter'; + /** * Povolí nahrávat pouze dokumenty typu txt, doc, docx, xls, xlsx, ppt, pptx, pdf. * * @var string */ - const FILTER_DOCUMENTS = 'Zet\FileUpload\Filter\DocumentFilter'; - + private const FILTER_DOCUMENTS = 'Zet\FileUpload\Filter\DocumentFilter'; + /** * Povolí nahrávat soubory zip, tar, rar, 7z. * * @var string */ - const FILTER_ARCHIVE = 'Zet\FileUpload\Filter\ArchiveFilter'; - + private const FILTER_ARCHIVE = 'Zet\FileUpload\Filter\ArchiveFilter'; + /** * Povolí nahrávat pouze soubory mp3, ogg, aiff, wav. * * @var string */ - const FILTER_AUDIO = 'Zet\FileUpload\Filter\AudioFilter'; - - /** - * @var \Nette\DI\Container - */ + private const FILTER_AUDIO = 'Zet\FileUpload\Filter\AudioFilter'; + + /** @var \Nette\DI\Container */ private $container; - - /** - * @var \Nette\Caching\Cache - */ + + /** @var \Nette\Caching\Cache */ private $cache; - - /** - * @var int - */ + + /** @var int */ private $maxFiles; - - /** - * @var int - */ + + /** @var int */ private $maxFileSize; - - /** - * @var string - */ + + /** @var string */ private $fileSizeString; - - /** - * @var \Zet\FileUpload\Model\UploadController - */ + + /** @var \Zet\FileUpload\Model\UploadController */ private $controller; - - /** - * @var string - */ + + /** @var string */ private $uploadModel; - + /** * Třída pro filtrování nahrávaných souborů. * * @var string */ private $fileFilter; - + /** * Pole vlastních definovaných parametrů. * * @var array */ private $params = []; - - /** - * @var string - */ + + /** @var string */ private $renderer; - - /** - * @var string - */ + + /** @var string */ private $token; - - /** - * @var DefaultFile[] - */ + + /** @var DefaultFile[] */ private $defaultFiles = []; - + /** * Seznam chybových hlášek. * Chyby uploaderu: @@ -194,21 +114,96 @@ public static function getScripts($basePath) { * @var string[] */ private $messages = []; - + /** * Automaticky překládat všechny chybové zprávy? * * @var bool */ private $autoTranslate = false; - + /** * Pole vlastních hodnot pro konfiguraci uploaderu. * * @var array */ private $uploadSettings = []; - + + + // -------------------------------------------------------------------- + // Registration + // -------------------------------------------------------------------- + + + /** + * @static + * @param $systemContainer + * @param array $configuration + */ + public static function register(\Nette\DI\Container $systemContainer, $configuration = []) + { + $class = __CLASS__; + \Nette\Forms\Container::extensionMethod('addFileUpload', static function ( + \Nette\Forms\Container $container, $name, $maxFiles = null, $maxFileSize = null + ) use ($class, $systemContainer, $configuration) { + $maxFiles = $maxFiles ?? $configuration->maxFiles; + $maxFileSize = $maxFileSize ?? $configuration->maxFileSize; + + /** @var FileUploadControl $component */ + $component = new $class($name, $maxFiles, $maxFileSize); + $component->setContainer($systemContainer); + $component->setUploadModel($configuration->uploadModel); + $component->setFileFilter($configuration->fileFilter); + $component->setRenderer($configuration->renderer); + + if (($configuration->translator ?? null) === null) { + $translator = $systemContainer->getByType(ITranslator::class, false); + $component->setTranslator($translator); + } else { + $component->setTranslator($configuration->translator); + } + + $component->setAutoTranslate($configuration->autoTranslate ?? false); + $component->setMessages((array) ($configuration->messages ?? [])); + $component->setUploadSettings($configuration->uploadSettings ?? []); + + $container->addComponent($component, $name); + + return $component; + }); + } + + + /** + * Vloží CSS do stránky. + * + * @static + * @param string $basePath + */ + public static function getHead(string $basePath): void + { + echo ''; + } + + + /** + * Vloží skripty do stránky. + * + * @static + * @param string $basePath + */ + public static function getScripts(string $basePath) + { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + + /** * FileUploadControl constructor. * @@ -216,177 +211,202 @@ public static function getScripts($basePath) { * @param int $maxFiles Maximální počet souborů. * @param string $maxFileSize Maximální velikosti souboru. */ - public function __construct($name, $maxFiles, $maxFileSize = null) { + public function __construct(string $name, int $maxFiles, string $maxFileSize = null) + { parent::__construct($name); $this->maxFiles = $maxFiles; - if(is_null($maxFileSize)) { - $this->fileSizeString = ini_get("upload_max_filesize") . "B"; - $this->maxFileSize = $this->parseIniSize(ini_get("upload_max_filesize")); + if ($maxFileSize === null) { + $this->fileSizeString = ini_get('upload_max_filesize') . 'B'; + $this->maxFileSize = $this->parseIniSize(ini_get('upload_max_filesize')); } else { - $this->fileSizeString = $maxFileSize . "B"; + $this->fileSizeString = $maxFileSize . 'B'; $this->maxFileSize = $this->parseIniSize($maxFileSize); } $this->controller = new Model\UploadController($this); - $this->token = uniqid(); + $this->monitor(\Nette\Forms\Form::class, function (\Nette\Forms\Form $form): void { + $form->addComponent($this->controller, 'uploadController' . ucfirst($this->name)); + }); + $this->token = uniqid(self::PREFIX, true); } - + + /** * Ověření nastavených direktiv, zda nepřekročují nastavení serveru. * * @throws \Zet\FileUpload\InvalidValueException */ - private function checkSettings() { - $postMaxSize = $this->parseIniSize($postMaxSizeString = ini_get("post_max_size")); - $iniMaxFileSize = $this->parseIniSize($iniMaxFileSizeString = ini_get("upload_max_filesize")); - - if($this->maxFileSize > $postMaxSize) { + private function checkSettings(): void + { + $postMaxSize = $this->parseIniSize($postMaxSizeString = ini_get('post_max_size')); + $iniMaxFileSize = $this->parseIniSize($iniMaxFileSizeString = ini_get('upload_max_filesize')); + + if ($this->maxFileSize > $postMaxSize) { throw new InvalidValueException( - sprintf( - "Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `post_max_size` (%s).", - $postMaxSizeString - ) + sprintf( + 'Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `post_max_size` (%s).', + $postMaxSizeString + ) ); - } else if($this->maxFileSize > $iniMaxFileSize) { + } + + if ($this->maxFileSize > $iniMaxFileSize) { throw new InvalidValueException( - sprintf( - "Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `upload_max_filesize` (%s).", - $iniMaxFileSizeString - ) + sprintf( + 'Nastavení pro maximální velikost souboru je větší, než dovoluje direktiva `upload_max_filesize` (%s).', + $iniMaxFileSizeString + ) ); } } - - /** - * @param Form $form - */ - protected function attached($form) { - parent::attached($form); - $this->form->addComponent($this->controller, "uploadController" . ucfirst($this->name)); - } - - # -------------------------------------------------------------------- - # Setters \ Getters - # -------------------------------------------------------------------- + // -------------------------------------------------------------------- + // Setters \ Getters + // -------------------------------------------------------------------- + + /** * @param \Nette\DI\Container $container * @internal */ - public function setContainer($container) { + public function setContainer(\Nette\DI\Container $container): void + { $this->container = $container; /** @noinspection PhpParamsInspection */ - $this->cache = new \Nette\Caching\Cache($this->container->getByType('Nette\Caching\IStorage')); + $this->cache = new \Nette\Caching\Cache($this->container->getByType(\Nette\Caching\IStorage::class)); /** @noinspection PhpParamsInspection */ - $this->controller->setRequest($container->getByType('\Nette\Http\Request')); + $this->controller->setRequest($container->getByType(\Nette\Http\Request::class)); } - + + /** * @return \Nette\DI\Container * @internal */ - public function getContainer() { + public function getContainer(): \Nette\DI\Container + { return $this->container; } - + + /** * @return int * @internal */ - public function getMaxFiles() { + public function getMaxFiles(): int + { return $this->maxFiles; } - + + /** * @param int $maxFiles * @return $this */ - public function setMaxFiles($maxFiles) { + public function setMaxFiles(int $maxFiles): self + { $this->maxFiles = $maxFiles; - + return $this; } - + + /** * @return Model\IUploadModel * @internal */ - public function getUploadModel() { - if(is_null($this->uploadModel)) { + public function getUploadModel(): Model\IUploadModel + { + if ($this->uploadModel === null) { return new Model\BaseUploadModel(); } else { $model = $this->container->getByType($this->uploadModel); - if($model instanceof Model\IUploadModel) { + if ($model instanceof Model\IUploadModel) { return $model; } else { throw new \Nette\InvalidStateException( - "Předaný model není instancí \\Zet\\FileUpload\\Model\\IUploadModel." + 'Předaný model není instancí \\Zet\\FileUpload\\Model\\IUploadModel.' ); } } } - + + /** * @param string $uploadModel * @return $this */ - public function setUploadModel($uploadModel) { + public function setUploadModel(string $uploadModel): self + { $this->uploadModel = $uploadModel; - + return $this; } - + + /** * @return int * @internal */ - public function getMaxFileSize() { + public function getMaxFileSize(): int + { return $this->maxFileSize; } - + + /** * @param int $maxFileSize * @return $this */ - public function setMaxFileSize($maxFileSize) { + public function setMaxFileSize(int $maxFileSize): self + { $this->maxFileSize = $this->parseIniSize($maxFileSize); - + return $this; } - + + /** * @return \Nette\Caching\Cache */ - public function getCache() { + public function getCache(): \Nette\Caching\Cache + { return $this->cache; } - + + /** * @return string * @internal */ - public function getFileSizeString() { + public function getFileSizeString(): string + { return $this->fileSizeString; } - + + /** * @return string * @internal */ - public function getFileFilter() { + public function getFileFilter(): string + { return $this->fileFilter; } - + + /** * Nastaví třídu pro filtrování nahrávaných souborů. * * @param string $fileFilter * @return $this */ - public function setFileFilter($fileFilter) { + public function setFileFilter(string $fileFilter): self + { $this->fileFilter = $fileFilter; - + return $this; } - + + /** * Vrátí název pro frontu s tokenem. * @@ -394,224 +414,266 @@ public function setFileFilter($fileFilter) { * @return string * @internal */ - public function getTokenizedCacheName($token) { - return $this->getHtmlId() . "-" . $token; + public function getTokenizedCacheName(string $token): string + { + return $this->getHtmlId() . '-' . $token; } - + + /** * Vrátí identifikační token. * * @return string * @internal */ - public function getToken() { + public function getToken(): string + { return $this->token; } - + + /** * Nastavení vlastních parametrů k uploadovanému souboru. * * @param array $params * @return FileUploadControl */ - public function setParams(array $params) { + public function setParams(array $params): self + { $this->params = $params; - + return $this; } - + + /** * @return array */ - public function getParams() { + public function getParams(): array + { return $this->params; } - + + /** * @param string $renderer * @return FileUploadControl */ - public function setRenderer($renderer) { + public function setRenderer(string $renderer): self + { $this->renderer = $renderer; - + return $this; } - + + /** * @return string */ - public function getRenderer() { + public function getRenderer(): string + { return $this->renderer; } - + + /** * @return DefaultFile[] */ - public function getDefaultFiles() { + public function getDefaultFiles(): array + { return $this->defaultFiles; } - + + /** * @param DefaultFile[] $defaultFiles * @return FileUploadControl */ - public function setDefaultFiles($defaultFiles) { + public function setDefaultFiles(array $defaultFiles): self + { $this->defaultFiles = $defaultFiles; - + return $this; } - + + /** * @param DefaultFile $defaultFile * @return FileUploadControl */ - public function addDefaultFile($defaultFile) { + public function addDefaultFile(DefaultFile $defaultFile): self + { $this->defaultFiles[] = $defaultFile; - + return $this; } - + + /** * @param string[] $messages * @return FileUploadControl */ - public function setMessages(array $messages) { + public function setMessages(array $messages): self + { $this->messages = $messages; - + return $this; } - + + /** * @param string $index * @param string $message * @return FileUploadControl */ - public function setMessage($index, $message) { - $this->messages[ $index ] = $message; - + public function setMessage(string $index, string $message): self + { + $this->messages[$index] = $message; + return $this; } - + + /** * @return string[] */ - public function getMessages() { + public function getMessages(): array + { return $this->messages; } - + + /** * @return bool */ - public function isAutoTranslate() { + public function isAutoTranslate(): bool + { return $this->autoTranslate; } - + + /** * @param bool $autoTranslate * @return FileUploadControl */ - public function setAutoTranslate($autoTranslate) { + public function setAutoTranslate(bool $autoTranslate): self + { $this->autoTranslate = $autoTranslate; - + return $this; } - + + /** * @return array */ - public function getUploadSettings() { + public function getUploadSettings(): array + { return $this->uploadSettings; } - + + /** * @param array $uploadSettings * @return FileUploadControl */ - public function setUploadSettings($uploadSettings) { + public function setUploadSettings(array $uploadSettings): self + { $this->uploadSettings = $uploadSettings; - + return $this; } - + + /** * @param string $name * @param mixed $value * @return FileUploadControl */ - public function addUploadSettings($name, $value) { - $this->uploadSettings[ $name ] = $value; - + public function addUploadSettings(string $name, mixed $value): self + { + $this->uploadSettings[$name] = $value; + return $this; } - - # -------------------------------------------------------------------- - # Methods - # -------------------------------------------------------------------- + // -------------------------------------------------------------------- + // Methods + // -------------------------------------------------------------------- + + /** * Získání identifikačního tokenu. */ - public function loadHttpData() { + public function loadHttpData(): void + { parent::loadHttpData(); - + /** @var \Nette\Http\Request $request */ $request = $this->getContainer()->getByType('\Nette\Http\Request'); - $this->token = $request->getPost($this->getHtmlName() . "-token"); + $this->token = $request->getPost($this->getHtmlName() . '-token'); } - + + /** * @return \Nette\Utils\Html * @throws InvalidValueException */ - public function getControl() { + public function getControl(): \Nette\Utils\Html + { $this->checkSettings(); - - $this->setOption("rendered", true); - + + $this->setOption('rendered', true); + $container = \Nette\Utils\Html::el("div class='zet-fileupload-container'"); - $container->id = $this->getHtmlId() . "-container"; - + $container->id = $this->getHtmlId() . '-container'; + $token = \Nette\Utils\Html::el("input type='hidden' value='" . $this->token . "'"); - $token->addAttributes(["name" => $this->getHtmlName() . "-token"]); - + $token->addAttributes(['name' => $this->getHtmlName() . '-token']); + $container->addHtml($token); $container->addHtml($this->controller->getJavaScriptTemplate()); $container->addHtml($this->controller->getControlTemplate()); - + return $container; } - + + /** * Vrátí nacachované hodnoty z controlleru. * * @return mixed|NULL */ - public function getValue() { + public function getValue() + { $files = $this->cache->load($this->getTokenizedCacheName($this->token)); - + return $files; } - + + /** * Delete cache */ - public function __destruct() { + public function __destruct() + { $this->cache->remove($this->getTokenizedCacheName($this->token)); } - + + /** * Parses ini size * * @param string $value * @return int */ - private function parseIniSize($value) { + private function parseIniSize(string $value): int + { $units = ['k' => 1024, 'm' => 1048576, 'g' => 1073741824]; $unit = strtolower(substr($value, -1)); - if(is_numeric($unit) || !isset($units[ $unit ])) { + if (is_numeric($unit) || !isset($units[$unit])) { return $value; } - - return ((int)$value) * $units[ $unit ]; + + return ((int) $value) * $units[$unit]; } - } diff --git a/src/FileUploadExtension.php b/src/FileUploadExtension.php index 9256fda..683da11 100644 --- a/src/FileUploadExtension.php +++ b/src/FileUploadExtension.php @@ -1,63 +1,97 @@ * @package Zet\FileUpload */ -final class FileUploadExtension extends \Nette\DI\CompilerExtension { - - /** - * Výchozí konfigurační hodnoty. - * @var array - */ - private $defaults = [ - "maxFiles" => 25, - "maxFileSize" => NULL, - "uploadModel" => NULL, - "fileFilter" => NULL, - "renderer" => '\Zet\FileUpload\Template\Renderer\Html5Renderer', - "translator" => NULL, - "autoTranslate" => false, - "messages" => [ - "maxFiles" => "Maximální počet souborů je {maxFiles}.", - "maxSize" => "Maximální velikost souboru je {maxSize}.", - "fileTypes" => "Povolené typy souborů jsou {fileTypes}.", - - // PHP Errors - "fileSize" => "Soubor je příliš veliký.", - "partialUpload" => "Soubor byl nahrán pouze částěčně.", - "noFile" => "Nebyl nahrán žádný soubor.", - "tmpFolder" => "Chybí dočasná složka.", - "cannotWrite" => "Nepodařilo se zapsat soubor na disk.", - "stopped" => "Nahrávání souboru bylo přerušeno." - ], - "uploadSettings" => [] - ]; - - /** - * Konfigurace nastavená uživatelem. - * @var array - */ - private $configuration = []; - - /** - * - */ - public function loadConfiguration() { - $this->configuration = $this->getConfig($this->defaults); +final class FileUploadExtension extends \Nette\DI\CompilerExtension +{ + + +// /** +// * Výchozí konfigurační hodnoty. +// * @var array +// */ +// private $defaults = [ +// "maxFiles" => 25, +// "maxFileSize" => NULL, +// "uploadModel" => NULL, +// "fileFilter" => NULL, +// "renderer" => '\Zet\FileUpload\Template\Renderer\Html5Renderer', +// "translator" => NULL, +// "autoTranslate" => false, +// "messages" => [ +// "maxFiles" => "Maximální počet souborů je {maxFiles}.", +// "maxSize" => "Maximální velikost souboru je {maxSize}.", +// "fileTypes" => "Povolené typy souborů jsou {fileTypes}.", +// +// // PHP Errors +// "fileSize" => "Soubor je příliš veliký.", +// "partialUpload" => "Soubor byl nahrán pouze částěčně.", +// "noFile" => "Nebyl nahrán žádný soubor.", +// "tmpFolder" => "Chybí dočasná složka.", +// "cannotWrite" => "Nepodařilo se zapsat soubor na disk.", +// "stopped" => "Nahrávání souboru bylo přerušeno." +// ], +// "uploadSettings" => [] +// ]; + + public function getConfigSchema(): Schema + { + return Expect::structure([ + 'maxFiles' => Expect::int(25), + 'maxFileSize' => Expect::string(), + 'uploadModel' => Expect::string(), + 'fileFilter' => Expect::string(), + 'renderer' => Expect::string('\Zet\FileUpload\Template\Renderer\Html5Renderer'), + 'translator' => Expect::string(), + 'autoTranslate' => Expect::bool(false), + 'messages' => Expect::structure([ + 'maxFiles' => Expect::string('Maximální počet souborů je {maxFiles}.'), + 'maxSize' => Expect::string('Maximální velikost souboru je {maxSize}.'), + 'fileTypes' => Expect::string('Povolené typy souborů jsou {fileTypes}.'), + 'fileSize' => Expect::string('Soubor je příliš veliký.'), + 'partialUpload' => Expect::string('Soubor byl nahrán pouze částěčně.'), + 'noFile' => Expect::string('Nebyl nahrán žádný soubor.'), + 'tmpFolder' => Expect::string('Chybí dočasná složka.'), + 'cannotWrite' => Expect::string('Nepodařilo se zapsat soubor na disk.'), + 'stopped' => Expect::string('Nahrávání souboru bylo přerušeno.'), + ]), + 'uploadSettings' => Expect::array(), + ]); } - +// /** +// * Konfigurace nastavená uživatelem. +// * @var array +// */ +// private $configuration = []; +// /** +// * +// */ +// public function loadConfiguration() { +// $this->configuration = $this->getConfig($this->defaults); +// } + + /** * @param \Nette\PhpGenerator\ClassType $class */ - public function afterCompile(\Nette\PhpGenerator\ClassType $class) { - $init = $class->methods["initialize"]; - + public function afterCompile(\Nette\PhpGenerator\ClassType $class): void + { + $init = $class->methods['initialize']; + $init->addBody('\Zet\FileUpload\FileUploadControl::register($this->getService(?), ?);', [ - $this->getContainerBuilder()->getByType('\Nette\DI\Container'), $this->configuration +// $this->getContainerBuilder()->getByType('\Nette\DI\Container'), $this->configuration, + $this->getContainerBuilder()->getByType(Container::class), $this->getConfig(), ]); } -} \ No newline at end of file +} diff --git a/src/Filter/ArchiveFilter.php b/src/Filter/ArchiveFilter.php index 637c926..3c87cc4 100644 --- a/src/Filter/ArchiveFilter.php +++ b/src/Filter/ArchiveFilter.php @@ -1,27 +1,32 @@ - - * @package Zet\FileUpload\Filter - */ -class ArchiveFilter extends BaseFilter { - - /** - * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. - * - * @example array("text/plain" => "txt") - * @return string[] - */ - protected function getMimeTypes() { - return [ - "application/zip" => "zip", - "application/x-rar-compressed" => "rar", - "application/x-tar" => "tar", - "application/x-7z-compressed" => "7z" - ]; - } -} \ No newline at end of file + + * @package Zet\FileUpload\Filter + */ +class ArchiveFilter extends BaseFilter +{ + + + /** + * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. + * + * @example array("text/plain" => "txt") + * @return string[] + */ + protected function getMimeTypes() + { + return [ + 'application/zip' => 'zip', + 'application/x-rar-compressed' => 'rar', + 'application/x-tar' => 'tar', + 'application/x-7z-compressed' => '7z', + ]; + } +} diff --git a/src/Filter/AudioFilter.php b/src/Filter/AudioFilter.php index dbadb10..e275af3 100644 --- a/src/Filter/AudioFilter.php +++ b/src/Filter/AudioFilter.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Filter */ -class AudioFilter extends BaseFilter { - +class AudioFilter extends BaseFilter +{ + + /** * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. * * @example array("text/plain" => "txt") * @return string[] */ - protected function getMimeTypes() { + protected function getMimeTypes() + { return [ - "audio/mpeg3" => "mp3", - "audio/x-mpeg-3" => "mp3", - "audio/ogg" => "ogg", - "audio/x-aiff" => "aiff", - "audio/x-wav" => "wav", - "audio/wav" => "wav", + 'audio/mpeg3' => 'mp3', + 'audio/x-mpeg-3' => 'mp3', + 'audio/ogg' => 'ogg', + 'audio/x-aiff' => 'aiff', + 'audio/x-wav' => 'wav', + 'audio/wav' => 'wav', ]; } -} \ No newline at end of file +} diff --git a/src/Filter/BaseFilter.php b/src/Filter/BaseFilter.php index 5a61ae8..51137ba 100644 --- a/src/Filter/BaseFilter.php +++ b/src/Filter/BaseFilter.php @@ -1,63 +1,74 @@ - - * @package Zet\FileUpload\Filter - */ -abstract class BaseFilter implements IMimeTypeFilter { - use SmartObject; - - /** - * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. - * - * @example array("text/plain" => "txt") - * @return string[] - */ - abstract protected function getMimeTypes(); - - /** - * Ověří mimetype předaného souboru. - * - * @param \Nette\Http\FileUpload $file Nahraný soubor k ověření. - * @return bool Má soubor správný mimetype? - */ - public function checkType(\Nette\Http\FileUpload $file) { - if(\Nette\Utils\Arrays::searchKey($this->getMimeTypes(), $file->getContentType()) !== false) { - return true; - } else { - // Pokud se nepodaří ověřit mimetype, ověříme alespoň koncovku. - if(array_search($this->getExtension($file->getName()), array_unique($this->getMimeTypes())) !== false) { - return true; - } else { - return false; - } - } - } - - /** - * Vrátí seznam povolených typů souborů. - * - * @return string - */ - public function getAllowedTypes() { - return implode(array_unique($this->getMimeTypes()), ", "); - } - - /** - * Vrátí koncovku souboru. - * - * @param string $filename - * @return string - */ - private function getExtension($filename) { - $exploded = explode(".", $filename); - - return $exploded[ count($exploded) - 1 ]; - } -} + + * @package Zet\FileUpload\Filter + */ +abstract class BaseFilter implements IMimeTypeFilter +{ + + use SmartObject; + + + /** + * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. + * + * @example array("text/plain" => "txt") + * @return string[] + */ + abstract protected function getMimeTypes(); + + + /** + * Ověří mimetype předaného souboru. + * + * @param \Nette\Http\FileUpload $file Nahraný soubor k ověření. + * @return bool Má soubor správný mimetype? + */ + public function checkType(\Nette\Http\FileUpload $file) + { + if (\Nette\Utils\Arrays::searchKey($this->getMimeTypes(), $file->getContentType()) !== false) { + return true; + } else { + // Pokud se nepodaří ověřit mimetype, ověříme alespoň koncovku. + if (array_search($this->getExtension($file->getName()), array_unique($this->getMimeTypes()), true) !== false) { + return true; + } else { + return false; + } + } + } + + + /** + * Vrátí seznam povolených typů souborů. + * + * @return string + */ + public function getAllowedTypes() + { + return implode(array_unique($this->getMimeTypes()), ', '); + } + + + /** + * Vrátí koncovku souboru. + * + * @param string $filename + * @return string + */ + private function getExtension($filename) + { + $exploded = explode('.', $filename); + + return $exploded[count($exploded) - 1]; + } +} diff --git a/src/Filter/DocumentFilter.php b/src/Filter/DocumentFilter.php index 6b7d342..dca3e61 100644 --- a/src/Filter/DocumentFilter.php +++ b/src/Filter/DocumentFilter.php @@ -1,31 +1,36 @@ - - * @package Zet\FileUpload\Filter - */ -class DocumentFilter extends BaseFilter { - - /** - * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. - * - * @example array("text/plain" => "txt") - * @return string[] - */ - protected function getMimeTypes() { - return [ - "text/plain" => "txt", - "application/msword" => "doc", - "application/vnd.ms-excel" => "xls", - "application/pdf" => "pdf", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx", - "application/vnd.ms-powerpoint" => "ppt", - "application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx" - ]; - } -} \ No newline at end of file + + * @package Zet\FileUpload\Filter + */ +class DocumentFilter extends BaseFilter +{ + + + /** + * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. + * + * @example array("text/plain" => "txt") + * @return string[] + */ + protected function getMimeTypes() + { + return [ + 'text/plain' => 'txt', + 'application/msword' => 'doc', + 'application/vnd.ms-excel' => 'xls', + 'application/pdf' => 'pdf', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx', + 'application/vnd.ms-powerpoint' => 'ppt', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx', + ]; + } +} diff --git a/src/Filter/IMimeTypeFilter.php b/src/Filter/IMimeTypeFilter.php index f365821..29a5a82 100644 --- a/src/Filter/IMimeTypeFilter.php +++ b/src/Filter/IMimeTypeFilter.php @@ -1,28 +1,33 @@ - - * @package Zet\FileUpload\Filter - */ -interface IMimeTypeFilter { - - /** - * Ověří mimetype předaného souboru. - * - * @param \Nette\Http\FileUpload $file Nahraný soubor k ověření. - * @return bool Má soubor správný mimetype? - */ - public function checkType(\Nette\Http\FileUpload $file); - - /** - * Vrátí seznam povolených typů souborů. - * - * @return string - */ - public function getAllowedTypes(); -} \ No newline at end of file + + * @package Zet\FileUpload\Filter + */ +interface IMimeTypeFilter +{ + + + /** + * Ověří mimetype předaného souboru. + * + * @param \Nette\Http\FileUpload $file Nahraný soubor k ověření. + * @return bool Má soubor správný mimetype? + */ + public function checkType(\Nette\Http\FileUpload $file); + + + /** + * Vrátí seznam povolených typů souborů. + * + * @return string + */ + public function getAllowedTypes(); +} diff --git a/src/Filter/ImageFilter.php b/src/Filter/ImageFilter.php index b50fc71..515e3df 100644 --- a/src/Filter/ImageFilter.php +++ b/src/Filter/ImageFilter.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Filter */ -class ImageFilter extends BaseFilter { - +class ImageFilter extends BaseFilter +{ + + /** * Vrátí seznam povolených typů souborů s jejich typickou koncovkou. * * @example array("text/plain" => "txt") * @return string[] */ - protected function getMimeTypes() { + protected function getMimeTypes() + { return [ - "image/png" => "png", - "image/pjpeg" => "jpeg", - "image/jpeg" => "jpg", - "image/gif" => "gif", - 'image/tif' => 'tif', + 'image/png' => 'png', + 'image/pjpeg' => 'jpeg', + 'image/jpeg' => 'jpg', + 'image/gif' => 'gif', + 'image/tif' => 'tif', ]; } - -} \ No newline at end of file +} diff --git a/src/Model/BaseUploadModel.php b/src/Model/BaseUploadModel.php index 5a81c83..61180cc 100644 --- a/src/Model/BaseUploadModel.php +++ b/src/Model/BaseUploadModel.php @@ -1,46 +1,56 @@ - - * @package Zet\FileUpload\Model - */ -class BaseUploadModel implements IUploadModel { - use SmartObject; - - /** - * Uložení nahraného souboru. - * - * @param \Nette\Http\FileUpload $file - * @param array $params Pole vlastních parametrů. - * @return mixed Vlastní navrátová hodnota. - */ - public function save(\Nette\Http\FileUpload $file, array $params = []) { - return $file->getSanitizedName(); - } - - /** - * Zpracování požadavku o smazání souboru. - * - * @param mixed $uploaded Hodnota navrácená funkcí save. - */ - public function remove($uploaded) { - # By Pass... - } - - /** - * Zpracování přejmenování souboru. - * - * @param mixed $upload Hodnota navrácená funkcí save. - * @param string $newName Nové jméno souboru. - * @return mixed Vlastní návratová hodnota. - */ - public function rename($upload, $newName) { - return \Nette\Utils\Strings::webalize($newName); - } -} + + * @package Zet\FileUpload\Model + */ +class BaseUploadModel implements IUploadModel +{ + + use SmartObject; + + + /** + * Uložení nahraného souboru. + * + * @param \Nette\Http\FileUpload $file + * @param array $params Pole vlastních parametrů. + * @return mixed Vlastní navrátová hodnota. + */ + public function save(\Nette\Http\FileUpload $file, array $params = []) + { + return $file->getSanitizedName(); + } + + + /** + * Zpracování požadavku o smazání souboru. + * + * @param mixed $uploaded Hodnota navrácená funkcí save. + */ + public function remove($uploaded) + { + // By Pass... + } + + + /** + * Zpracování přejmenování souboru. + * + * @param mixed $upload Hodnota navrácená funkcí save. + * @param string $newName Nové jméno souboru. + * @return mixed Vlastní návratová hodnota. + */ + public function rename($upload, $newName) + { + return \Nette\Utils\Strings::webalize($newName); + } +} diff --git a/src/Model/DefaultFile.php b/src/Model/DefaultFile.php index 589da8f..57dd52a 100644 --- a/src/Model/DefaultFile.php +++ b/src/Model/DefaultFile.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Model */ -class DefaultFile { +class DefaultFile +{ + use SmartObject; - + /** * Callback pro smazání výchozího souboru s parametry (mixed $identifier). * * @var array */ public $onDelete = []; - + /** * Odkaz na náhled obrázku. * * @var string */ private $preview; - + /** * Název souboru. * * @var string */ private $filename; - + /** * Identifikátor souboru sloužící pro jeho smazání. * * @var mixed */ private $identifier; - + + /** * @return array */ - public function toArray() { + public function toArray() + { return [ - "preview" => $this->preview, - "filename" => $this->filename, - "id" => $this->identifier + 'preview' => $this->preview, + 'filename' => $this->filename, + 'id' => $this->identifier, ]; } - + + /** * @return string */ - public function getPreview() { + public function getPreview() + { return $this->preview; } - + + /** * @param string $preview */ - public function setPreview($preview) { + public function setPreview($preview) + { $this->preview = $preview; } - + + /** * @return string */ - public function getFilename() { + public function getFilename() + { return $this->filename; } - + + /** * @param string $filename */ - public function setFilename($filename) { + public function setFilename($filename) + { $this->filename = $filename; } - + + /** * @return mixed */ - public function getIdentifier() { + public function getIdentifier() + { return $this->identifier; } - + + /** * @param mixed $identifier */ - public function setIdentifier($identifier) { + public function setIdentifier($identifier) + { $this->identifier = $identifier; } - - } diff --git a/src/Model/IUploadModel.php b/src/Model/IUploadModel.php index 7a4b8f6..9aa01eb 100644 --- a/src/Model/IUploadModel.php +++ b/src/Model/IUploadModel.php @@ -1,38 +1,43 @@ - - * @package Zet\FileUpload\Model - */ -interface IUploadModel { - - /** - * Uložení nahraného souboru. - * - * @param \Nette\Http\FileUpload $file - * @param array $params Pole vlastních parametrů. - * @return mixed Vlastní navrátová hodnota. - */ - public function save(\Nette\Http\FileUpload $file, array $params = []); - - /** - * Zpracování přejmenování souboru. - * - * @param mixed $upload Hodnota navrácená funkcí save. - * @param string $newName Nové jméno souboru. - * @return mixed Vlastní návratová hodnota. - */ - public function rename($upload, $newName); - - /** - * Zpracování požadavku o smazání souboru. - * - * @param mixed $uploaded Hodnota navrácená funkcí save. - */ - public function remove($uploaded); - -} \ No newline at end of file + + * @package Zet\FileUpload\Model + */ +interface IUploadModel +{ + + + /** + * Uložení nahraného souboru. + * + * @param \Nette\Http\FileUpload $file + * @param array $params Pole vlastních parametrů. + * @return mixed Vlastní navrátová hodnota. + */ + public function save(\Nette\Http\FileUpload $file, array $params = []); + + + /** + * Zpracování přejmenování souboru. + * + * @param mixed $upload Hodnota navrácená funkcí save. + * @param string $newName Nové jméno souboru. + * @return mixed Vlastní návratová hodnota. + */ + public function rename($upload, $newName); + + + /** + * Zpracování požadavku o smazání souboru. + * + * @param mixed $uploaded Hodnota navrácená funkcí save. + */ + public function remove($uploaded); +} diff --git a/src/Model/UploadController.php b/src/Model/UploadController.php index c0f47ac..d4c4572 100644 --- a/src/Model/UploadController.php +++ b/src/Model/UploadController.php @@ -1,232 +1,245 @@ - - * @package Zet\FileUpload - */ -class UploadController extends \Nette\Application\UI\Control { - - /** - * @var \Zet\FileUpload\FileUploadControl - */ - private $uploadControl; - - /** - * @var \Nette\Http\Request - */ - private $request; - - /** - * @var \Zet\FileUpload\Filter\IMimeTypeFilter - */ - private $filter; - - /** - * @var BaseRenderer - */ - private $renderer; - - /** - * UploadController constructor. - * - * @param \Zet\FileUpload\FileUploadControl $uploadControl - */ - public function __construct(\Zet\FileUpload\FileUploadControl $uploadControl) { - parent::__construct(); - $this->uploadControl = $uploadControl; - } - - /** - * @param \Nette\Http\Request $request - */ - public function setRequest($request) { - $this->request = $request; - } - - /** - * @return \Zet\FileUpload\Filter\IMimeTypeFilter|NULL - */ - public function getFilter() { - if(is_null($this->filter)) { - /** @noinspection PhpInternalEntityUsedInspection */ - $className = $this->uploadControl->getFileFilter(); - if(!is_null($className)) { - $filterClass = new $className; - if($filterClass instanceof \Zet\FileUpload\Filter\IMimeTypeFilter) { - $this->filter = $filterClass; - } else { - throw new \Nette\UnexpectedValueException( - "Třída pro filtrování souborů neimplementuje rozhraní \\Zet\\FileUpload\\Filter\\IMimeTypeFilter." - ); - } - } - } - - return $this->filter; - } - - /** - * @return \Zet\FileUpload\FileUploadControl - */ - public function getUploadControl() { - return $this->uploadControl; - } - - /** - * @return BaseRenderer - */ - public function getRenderer() { - if(is_null($this->renderer)) { - $rendererClass = $this->uploadControl->getRenderer(); - $this->renderer = new $rendererClass($this->uploadControl, $this->uploadControl->getTranslator()); - - if(!($this->renderer instanceof BaseRenderer)) { - throw new InvalidStateException( - "Renderer musí být instancí třídy `\\Zet\\FileUpload\\Template\\BaseRenderer`." - ); - } - } - - return $this->renderer; - } - - /** - * Vytvoření šablony s JavaScriptem pro FileUpload. - * - * @return string - */ - public function getJavaScriptTemplate() { - $builder = new JavascriptBuilder( - $this->getRenderer(), - $this - ); - - return $builder->getJsTemplate(); - } - - /** - * Vytvoření šablony s přehledem o uploadu. - * - * @return \Nette\Utils\Html - */ - public function getControlTemplate() { - return $this->getRenderer()->buildDefaultTemplate(); - } - - /** - * Zpracování uploadu souboru. - */ - public function handleUpload() { - $files = $this->request->getFiles(); - $token = $this->request->getPost("token"); - $params = json_decode($this->request->getPost("params"), true); - - /** @var \Nette\Http\FileUpload $file */ - $file = $files[ $this->uploadControl->getHtmlName() ]; - /** @noinspection PhpInternalEntityUsedInspection */ - $model = $this->uploadControl->getUploadModel(); - $cache = $this->uploadControl->getCache(); - $filter = $this->getFilter(); - - try { - if(!is_null($filter) && !$filter->checkType($file)) { - throw new \Zet\FileUpload\InvalidFileException($this->getFilter()->getAllowedTypes()); - } - - if($file->isOk()) { - $returnData = $model->save($file, $params); - /** @noinspection PhpInternalEntityUsedInspection */ - $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); - if(empty($cacheFiles)) { - $cacheFiles = [$this->request->getPost("id") => $returnData]; - } else { - $cacheFiles[ $this->request->getPost("id") ] = $returnData; - } - /** @noinspection PhpInternalEntityUsedInspection */ - $cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles); - } - - } catch(\Zet\FileUpload\InvalidFileException $e) { - $this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([ - "id" => $this->request->getPost("id"), - "error" => 100, - "errorMessage" => $e->getMessage() - ])); - - } catch(\Exception $e) { - $this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([ - "id" => $this->request->getPost("id"), - "error" => 99, - "errorMessage" => $e->getMessage() - ])); - } - - $this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([ - "id" => $this->request->getPost("id"), - "error" => $file->getError() - ])); - } - - /** - * Odstraní nahraný soubor. - */ - public function handleRemove() { - $id = $this->request->getQuery("id"); - $token = $this->request->getQuery("token"); - $default = $this->request->getQuery("default", 0); - - if($default == 0) { - $cache = $this->uploadControl->getCache(); - /** @noinspection PhpInternalEntityUsedInspection */ - $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); - if(isset($cacheFiles[ $id ])) { - /** @noinspection PhpInternalEntityUsedInspection */ - $this->uploadControl->getUploadModel()->remove($cacheFiles[ $id ]); - unset($cacheFiles[ $id ]); - /** @noinspection PhpInternalEntityUsedInspection */ - $cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles); - } - } else { - $files = $this->uploadControl->getDefaultFiles(); - - foreach($files as $file) { - if($file->getIdentifier() == $id) { - $file->onDelete($id); - } - } - } - } - - /** - * Přejmenuje nahraný soubor. - */ - public function handleRename() { - $id = $this->request->getQuery("id"); - $newName = $this->request->getQuery("newName"); - $token = $this->request->getQuery("token"); - - $cache = $this->uploadControl->getCache(); - /** @noinspection PhpInternalEntityUsedInspection */ - $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); - - if(isset($cacheFiles[ $id ])) { - /** @noinspection PhpInternalEntityUsedInspection */ - $cacheFiles[ $id ] = $this->uploadControl->getUploadModel()->rename($cacheFiles[ $id ], $newName); - /** @noinspection PhpInternalEntityUsedInspection */ - $cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles); - } - } - - public function validate() { - // Nette ^2.3.10 bypass - } -} + + * @package Zet\FileUpload + */ +class UploadController extends \Nette\Application\UI\Control +{ + + /** @var \Zet\FileUpload\FileUploadControl */ + private $uploadControl; + + /** @var \Nette\Http\Request */ + private $request; + + /** @var \Zet\FileUpload\Filter\IMimeTypeFilter */ + private $filter; + + /** @var BaseRenderer */ + private $renderer; + + + /** + * UploadController constructor. + * + * @param \Zet\FileUpload\FileUploadControl $uploadControl + */ + public function __construct(\Zet\FileUpload\FileUploadControl $uploadControl) + { + $this->uploadControl = $uploadControl; + } + + + /** + * @param \Nette\Http\Request $request + */ + public function setRequest(\Nette\Http\Request $request): void + { + $this->request = $request; + } + + + /** + * @return \Zet\FileUpload\Filter\IMimeTypeFilter|NULL + */ + public function getFilter() + { + if ($this->filter === null) { + /** @noinspection PhpInternalEntityUsedInspection */ + $className = $this->uploadControl->getFileFilter(); + if ($className !== null) { + $filterClass = new $className; + if ($filterClass instanceof \Zet\FileUpload\Filter\IMimeTypeFilter) { + $this->filter = $filterClass; + } else { + throw new \Nette\UnexpectedValueException( + 'Třída pro filtrování souborů neimplementuje rozhraní \\Zet\\FileUpload\\Filter\\IMimeTypeFilter.' + ); + } + } + } + + return $this->filter; + } + + + /** + * @return \Zet\FileUpload\FileUploadControl + */ + public function getUploadControl(): \Zet\FileUpload\FileUploadControl + { + return $this->uploadControl; + } + + + /** + * @return BaseRenderer + */ + public function getRenderer(): BaseRenderer + { + if ($this->renderer === null) { + $rendererClass = $this->uploadControl->getRenderer(); + $this->renderer = new $rendererClass($this->uploadControl, $this->uploadControl->getTranslator()); + + if (!($this->renderer instanceof BaseRenderer)) { + throw new InvalidStateException( + 'Renderer musí být instancí třídy `\\Zet\\FileUpload\\Template\\BaseRenderer`.' + ); + } + } + + return $this->renderer; + } + + + /** + * Vytvoření šablony s JavaScriptem pro FileUpload. + * + * @return string + */ + public function getJavaScriptTemplate(): string + { + $builder = new JavascriptBuilder( + $this->getRenderer(), + $this + ); + + return $builder->getJsTemplate(); + } + + + /** + * Vytvoření šablony s přehledem o uploadu. + * + * @return \Nette\Utils\Html + */ + public function getControlTemplate(): \Nette\Utils\Html + { + return $this->getRenderer()->buildDefaultTemplate(); + } + + + /** + * Zpracování uploadu souboru. + */ + public function handleUpload(): void + { + $files = $this->request->getFiles(); + $token = $this->request->getPost('token'); + $params = json_decode($this->request->getPost('params'), true); + + /** @var \Nette\Http\FileUpload $file */ + $file = $files[$this->uploadControl->getHtmlName()]; + /** @noinspection PhpInternalEntityUsedInspection */ + $model = $this->uploadControl->getUploadModel(); + $cache = $this->uploadControl->getCache(); + $filter = $this->getFilter(); + + try { + if ($filter !== null && !$filter->checkType($file)) { + throw new \Zet\FileUpload\InvalidFileException($this->getFilter()->getAllowedTypes()); + } + + if ($file->isOk()) { + $returnData = $model->save($file, $params); + /** @noinspection PhpInternalEntityUsedInspection */ + $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); + if (empty($cacheFiles)) { + $cacheFiles = [$this->request->getPost('id') => $returnData]; + } else { + $cacheFiles[$this->request->getPost('id')] = $returnData; + } + /** @noinspection PhpInternalEntityUsedInspection */ + $cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles); + } + } catch (\Zet\FileUpload\InvalidFileException $e) { + $this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([ + 'id' => $this->request->getPost('id'), + 'error' => 100, + 'errorMessage' => $e->getMessage(), + ])); + } catch (\Exception $e) { + $this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([ + 'id' => $this->request->getPost('id'), + 'error' => 99, + 'errorMessage' => $e->getMessage(), + ])); + } + + $this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([ + 'id' => $this->request->getPost('id'), + 'error' => $file->getError(), + ])); + } + + + /** + * Odstraní nahraný soubor. + */ + public function handleRemove(): void + { + $id = $this->request->getQuery('id'); + $token = $this->request->getQuery('token'); + $default = $this->request->getQuery('default', 0); + + if ($default == 0) { + $cache = $this->uploadControl->getCache(); + /** @noinspection PhpInternalEntityUsedInspection */ + $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); + if (isset($cacheFiles[$id])) { + /** @noinspection PhpInternalEntityUsedInspection */ + $this->uploadControl->getUploadModel()->remove($cacheFiles[$id]); + unset($cacheFiles[$id]); + /** @noinspection PhpInternalEntityUsedInspection */ + $cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles); + } + } else { + $files = $this->uploadControl->getDefaultFiles(); + + foreach ($files as $file) { + if ($file->getIdentifier() == $id) { + $file->onDelete($id); + } + } + } + } + + + /** + * Přejmenuje nahraný soubor. + */ + public function handleRename(): void + { + $id = $this->request->getQuery('id'); + $newName = $this->request->getQuery('newName'); + $token = $this->request->getQuery('token'); + + $cache = $this->uploadControl->getCache(); + /** @noinspection PhpInternalEntityUsedInspection */ + $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); + + if (isset($cacheFiles[$id])) { + /** @noinspection PhpInternalEntityUsedInspection */ + $cacheFiles[$id] = $this->uploadControl->getUploadModel()->rename($cacheFiles[$id], $newName); + /** @noinspection PhpInternalEntityUsedInspection */ + $cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles); + } + } + + + public function validate() + { + // Nette ^2.3.10 bypass + } +} diff --git a/src/Template/JavascriptBuilder.php b/src/Template/JavascriptBuilder.php index 2300d06..7bf61ed 100644 --- a/src/Template/JavascriptBuilder.php +++ b/src/Template/JavascriptBuilder.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload */ -class JavascriptBuilder { +class JavascriptBuilder +{ + use SmartObject; - - /** - * @var \Nette\Application\UI\ITemplate - */ + + /** @var \Nette\Application\UI\ITemplate */ private $template; - - /** - * @var \Nette\Caching\Cache - */ + + /** @var \Nette\Caching\Cache */ private $cache; - - /** - * @var string - */ + + /** @var string */ private $uploadUrl; - - /** - * @var string - */ + + /** @var string */ private $renameLink; - - /** - * @var BaseRenderer - */ + + /** @var BaseRenderer */ private $renderer; - - /** - * @var UploadController - */ + + /** @var UploadController */ private $controller; - + + /** * JavascriptBuilder constructor. * @@ -53,47 +46,54 @@ class JavascriptBuilder { * @param UploadController $controller */ public function __construct( - BaseRenderer $renderer, - UploadController $controller - ) { + BaseRenderer $renderer, + UploadController $controller + ) + { $this->renderer = $renderer; $this->controller = $controller; $this->cache = $controller->getUploadControl()->getCache(); - + $this->template = $controller->template; - $this->template->setFile(__DIR__ . "/js.latte"); + $this->template->setFile(__DIR__ . '/js.latte'); } - + + /** * @return string */ - public function getJsTemplate() { + public function getJsTemplate() + { return $this->buildTemplate(); } - + + /** * @return string */ - private function buildTemplate() { + private function buildTemplate() + { $this->setSettings(); $this->setRendererSettings(); $this->buildTemplates(); - - return (string)$this->template; + + return (string) $this->template; } - + + /** * Základní nastavení. */ - private function setSettings() { - $this->template->uploadUrl = $this->controller->link("upload"); - $this->template->renameLink = $this->controller->link("rename"); - $this->template->removeLink = $this->controller->link("//remove"); - $this->template->inputId = $this->renderer->getElements()["input"]->attrs["id"]; - + private function setSettings() + { + $this->template->uploadUrl = $this->controller->link('upload'); + $this->template->renameLink = $this->controller->link('rename'); + $this->template->removeLink = $this->controller->link('//remove'); + $this->template->inputId = $this->renderer->getElements()['input']->attrs['id']; + $this->needTranslate(); $this->template->messages = $this->controller->getUploadControl()->getMessages(); - + /** @noinspection PhpInternalEntityUsedInspection */ $this->template->maxFiles = $this->controller->getUploadControl()->getMaxFiles(); /** @noinspection PhpInternalEntityUsedInspection */ @@ -105,50 +105,47 @@ private function setSettings() { $this->template->token = $this->controller->getUploadControl()->getToken(); $this->template->params = json_encode($this->controller->getUploadControl()->getParams()); $this->template->settings = $this->controller->getUploadControl()->getUploadSettings(); - + $default = $this->controller->getUploadControl()->getDefaultFiles(); - + $defaultFiles = []; - foreach($default as $file) { + foreach ($default as $file) { $defaultFiles[] = $file->toArray(); } - + $this->template->defaultFiles = $defaultFiles; } - - /** - * - */ - private function buildTemplates() { + + + private function buildTemplates() + { $this->template->fileContainerTemplate = $this->renderer->buildFileContainerTemplate(); $this->template->fileErrorTemplate = $this->renderer->buildFileError(); } - - /** - * - */ - private function setRendererSettings() { + + + private function setRendererSettings() + { $elements = $this->renderer->getElements(); - + $components = []; - foreach($elements as $type => $element) { - if($element !== null) { - $components[$type] = $element->getAttribute("data-upload-component"); + foreach ($elements as $type => $element) { + if ($element !== null) { + $components[$type] = $element->getAttribute('data-upload-component'); } else { $components[$type] = null; } } - + $this->template->components = $components; } - - /** - * - */ - private function needTranslate() { + + + private function needTranslate() + { $upload = $this->controller->getUploadControl(); - if($upload->isAutoTranslate()) { - foreach($upload->getMessages() as $key => $value) { + if ($upload->isAutoTranslate()) { + foreach ($upload->getMessages() as $key => $value) { $upload->setMessage($key, $upload->getTranslator()->translate($value)); } } diff --git a/src/Template/Renderer/BaseRenderer.php b/src/Template/Renderer/BaseRenderer.php index a6592ca..3d8a013 100644 --- a/src/Template/Renderer/BaseRenderer.php +++ b/src/Template/Renderer/BaseRenderer.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Template\Renderer */ -abstract class BaseRenderer implements IUploadRenderer { +abstract class BaseRenderer implements IUploadRenderer +{ + use SmartObject; - - /** - * ID template ve tvaru: HtmlId-ElementType - * - * @var string - */ - private $idTemplate = "%s-%s"; - + /** * Seznam všech základních komponent uploaderu: *
    @@ -42,29 +39,33 @@ abstract class BaseRenderer implements IUploadRenderer { * @var Html[] */ protected $elements = [ - "container" => null, - "input" => null, - "globalProgress" => null, - "globalProgressValue" => null, - "fileProgress" => null, - "fileProgressValue" => null, - "imagePreview" => null, - "filePreview" => null, - "filename" => null, - "delete" => null, - "errorMessage" => null + 'container' => null, + 'input' => null, + 'globalProgress' => null, + 'globalProgressValue' => null, + 'fileProgress' => null, + 'fileProgressValue' => null, + 'imagePreview' => null, + 'filePreview' => null, + 'filename' => null, + 'delete' => null, + 'errorMessage' => null, ]; - - /** - * @var FileUploadControl - */ + + /** @var FileUploadControl */ protected $fileUploadControl; - + + /** @var ITranslator|NULL */ + protected $translator; + /** - * @var ITranslator|NULL + * ID template ve tvaru: HtmlId-ElementType + * + * @var string */ - protected $translator; - + private $idTemplate = '%s-%s'; + + /** * BaseRenderer constructor. * @@ -72,67 +73,75 @@ abstract class BaseRenderer implements IUploadRenderer { * @param ITranslator|NULL $translator */ public function __construct( - FileUploadControl $fileUploadControl, - ITranslator $translator = null - ) { + FileUploadControl $fileUploadControl, + ITranslator $translator = null + ) + { $this->fileUploadControl = $fileUploadControl; - + $this->init(); $this->translator = $translator; } - + + /** * Inicializace elementů. */ - public function init() { + public function init() + { $htmlId = $this->fileUploadControl->getHtmlId(); - - foreach($this->elements as $type => $value) { - if($type == "input") { + + foreach ($this->elements as $type => $value) { + if ($type == 'input') { $element = Html::el("input type='file' multiple='multiple'")->addAttributes([ - "id" => $htmlId, - "name" => $this->fileUploadControl->getHtmlName(), - "data-upload-component" => $htmlId + 'id' => $htmlId, + 'name' => $this->fileUploadControl->getHtmlName(), + 'data-upload-component' => $htmlId, ]); - } else if($type == "delete") { + } elseif ($type == 'delete') { $element = Html::el("button type='button'")->addAttributes([ - "data-upload-component" => sprintf($this->idTemplate, $htmlId, $type) + 'data-upload-component' => sprintf($this->idTemplate, $htmlId, $type), ]); - } else if($type == "imagePreview") { - $element = Html::el("img")->addAttributes([ - "data-upload-component" => sprintf($this->idTemplate, $htmlId, $type) + } elseif ($type == 'imagePreview') { + $element = Html::el('img')->addAttributes([ + 'data-upload-component' => sprintf($this->idTemplate, $htmlId, $type), ]); } else { - $element = Html::el("div")->addAttributes([ - "data-upload-component" => sprintf($this->idTemplate, $htmlId, $type) + $element = Html::el('div')->addAttributes([ + 'data-upload-component' => sprintf($this->idTemplate, $htmlId, $type), ]); } - - $this->elements[ $type ] = $element; + + $this->elements[$type] = $element; } } - + + /** * @return Html[] */ - public function getElements() { + public function getElements() + { return $this->elements; } - + + /** * Sestavení výchozí šablony uploaderu. * * @return Html */ abstract public function buildDefaultTemplate(); - + + /** * Sestavení šablony pro vkládání nových souborů. * * @return Html */ abstract public function buildFileContainerTemplate(); - + + /** * Sestavení šablony pro soubor, u kterého vznikla chyba. * diff --git a/src/Template/Renderer/Bootstrap3Renderer.php b/src/Template/Renderer/Bootstrap3Renderer.php index 6d60fc1..e73b387 100644 --- a/src/Template/Renderer/Bootstrap3Renderer.php +++ b/src/Template/Renderer/Bootstrap3Renderer.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Template\Renderer */ -class Bootstrap3Renderer extends BaseRenderer { - - public function init() { +class Bootstrap3Renderer extends BaseRenderer +{ + + + public function init() + { parent::init(); - - $this->elements["globalProgressValue"] = null; - $this->elements["fileProgressValue"] = null; + + $this->elements['globalProgressValue'] = null; + $this->elements['fileProgressValue'] = null; } - + + /** * Sestavení výchozí šablony uploaderu. * * @return Html */ - public function buildDefaultTemplate() { - $customContainer = Html::el("div"); - - $this->elements["input"]->setAttribute("style", "display: none"); - $id = $this->elements["input"]->getAttribute("id"); + public function buildDefaultTemplate() + { + $customContainer = Html::el('div'); + + $this->elements['input']->setAttribute('style', 'display: none'); + $id = $this->elements['input']->getAttribute('id'); $button = Html::el("button type='button' class='btn btn-primary'"); - $button->setAttribute("onclick", "document.getElementById('$id').click(); return false;") - ->setAttribute("style", "margin-bottom: 10px"); - $button->setText("Nahrát soubor"); - - $customContainer->addHtml($this->elements["input"]); + $button->setAttribute('onclick', "document.getElementById('$id').click(); return false;") + ->setAttribute('style', 'margin-bottom: 10px'); + $button->setText('Nahrát soubor'); + + $customContainer->addHtml($this->elements['input']); $customContainer->addHtml($button); - - $globalProgress = $this->elements["globalProgress"] - ->setAttribute("class", "progress-bar"); + + $globalProgress = $this->elements['globalProgress'] + ->setAttribute('class', 'progress-bar'); $progressContainer = Html::el("div class='progress'"); $progressContainer->addHtml($globalProgress); $customContainer->addHtml($progressContainer); - - $container = Html::el("table"); - $container->setAttribute("class", "table table-striped"); - - $thead = Html::el("thead"); - $tr = Html::el("tr"); + + $container = Html::el('table'); + $container->setAttribute('class', 'table table-striped'); + + $thead = Html::el('thead'); + $tr = Html::el('tr'); $preview = Html::el("th style='width: 15%;'"); $tr->addHtml($preview); - $filename = Html::el("th")->setText("Soubor"); + $filename = Html::el('th')->setText('Soubor'); $tr->addHtml($filename); - $status = Html::el("th style='width: 20%'")->setText("Stav"); + $status = Html::el("th style='width: 20%'")->setText('Stav'); $tr->addHtml($status); $actions = Html::el("th style='width: 50px'"); $tr->addHtml($actions); $thead->addHtml($tr); - + $container->addHtml($thead); - - $fileUploadContainer = $this->elements["container"]; - $fileUploadContainer->setName("tbody"); + + $fileUploadContainer = $this->elements['container']; + $fileUploadContainer->setName('tbody'); $container->addHtml($fileUploadContainer); $customContainer->addHtml($container); - + return $customContainer; } - + + /** * Sestavení šablony pro vkládání nových souborů. * * @return Html */ - public function buildFileContainerTemplate() { - $tr = Html::el("tr"); - + public function buildFileContainerTemplate() + { + $tr = Html::el('tr'); + $preview = Html::el("td style='vertical-align: middle'"); - $preview->addHtml($this->elements["imagePreview"]->setAttribute("width", "100%")->setAttribute("class", "img-rounded")); - $preview->addHtml($this->elements["filePreview"]->setName("span")->setAttribute("class", "label label-info")); + $preview->addHtml($this->elements['imagePreview']->setAttribute('width', '100%')->setAttribute('class', 'img-rounded')); + $preview->addHtml($this->elements['filePreview']->setName('span')->setAttribute('class', 'label label-info')); $tr->addHtml($preview); - + $name = Html::el("td style='vertical-align: middle'"); - $name->addHtml($this->elements["filename"]); + $name->addHtml($this->elements['filename']); $tr->addHtml($name); - + $progressTd = Html::el("td style='vertical-align: middle'"); $progressContainer = Html::el("div class='progress' style='margin-bottom: 0px'"); - $progress = $this->elements["fileProgress"]->setAttribute("class", "progress-bar"); + $progress = $this->elements['fileProgress']->setAttribute('class', 'progress-bar'); $progressContainer->addHtml($progress); $progressTd->addHtml($progressContainer); $tr->addHtml($progressTd); - + $delete = Html::el("td style='vertical-align: middle' class='text-center'"); $delete->addHtml( - $this->elements["delete"] - ->setAttribute("class", "btn btn-danger") - ->setHtml("×") + $this->elements['delete'] + ->setAttribute('class', 'btn btn-danger') + ->setHtml('×') ); $tr->addHtml($delete); - + return $tr; } - + + /** * Sestavení šablony pro soubor, u kterého vznikla chyba. * * @return Html */ - public function buildFileError() { + public function buildFileError() + { $tr = Html::el("tr class='danger'"); - $tr->addHtml($this->elements["errorMessage"]->setName("td")->addAttributes([ - "colspan" => 4 + $tr->addHtml($this->elements['errorMessage']->setName('td')->addAttributes([ + 'colspan' => 4, ])); - + return $tr; } } diff --git a/src/Template/Renderer/Bootstrap4Renderer.php b/src/Template/Renderer/Bootstrap4Renderer.php index 4f410f1..4aad20a 100644 --- a/src/Template/Renderer/Bootstrap4Renderer.php +++ b/src/Template/Renderer/Bootstrap4Renderer.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Template\Renderer */ -class Bootstrap4Renderer extends BaseRenderer { - - public function init() { +class Bootstrap4Renderer extends BaseRenderer +{ + + + public function init() + { parent::init(); - - $this->elements["globalProgressValue"] = null; - $this->elements["fileProgressValue"] = null; + + $this->elements['globalProgressValue'] = null; + $this->elements['fileProgressValue'] = null; } - + + /** * Sestavení výchozí šablony uploaderu. * * @return Html */ - public function buildDefaultTemplate() { - $customContainer = Html::el("div"); - - $this->elements["input"]->setAttribute("style", "display: none"); - $id = $this->elements["input"]->getAttribute("id"); + public function buildDefaultTemplate() + { + $customContainer = Html::el('div'); + + $this->elements['input']->setAttribute('style', 'display: none'); + $id = $this->elements['input']->getAttribute('id'); $button = Html::el("button type='button' class='btn btn-primary mb-2'"); - $button->setAttribute("onclick", "document.getElementById('$id').click(); return false;"); - $button->setText("Nahrát soubor"); - - $customContainer->addHtml($this->elements["input"]); + $button->setAttribute('onclick', "document.getElementById('$id').click(); return false;"); + $button->setText('Nahrát soubor'); + + $customContainer->addHtml($this->elements['input']); $customContainer->addHtml($button); - - $globalProgress = $this->elements["globalProgress"] - ->setAttribute("class", "progress-bar") - ->setAttribute("style", "height: 20px"); + + $globalProgress = $this->elements['globalProgress'] + ->setAttribute('class', 'progress-bar') + ->setAttribute('style', 'height: 20px'); $progressContainer = Html::el("div class='progress mb-2'"); $progressContainer->addHtml($globalProgress); $customContainer->addHtml($progressContainer); - - $container = $this->elements["container"]; - $container->setName("table"); - $container->setAttribute("class", "table"); - + + $container = $this->elements['container']; + $container->setName('table'); + $container->setAttribute('class', 'table'); + $thead = Html::el("thead class='thead-inverse'"); - $tr = Html::el("tr"); + $tr = Html::el('tr'); $preview = Html::el("th style='width: 15%;'"); $tr->addHtml($preview); - $filename = Html::el("th")->setText("Soubor"); + $filename = Html::el('th')->setText('Soubor'); $tr->addHtml($filename); - $status = Html::el("th style='width: 20%'")->setText("Stav"); + $status = Html::el("th style='width: 20%'")->setText('Stav'); $tr->addHtml($status); $actions = Html::el("th style='width: 50px'"); $tr->addHtml($actions); $thead->addHtml($tr); - + $container->addHtml($thead); $customContainer->addHtml($container); - + return $customContainer; } - + + /** * Sestavení šablony pro vkládání nových souborů. * * @return Html */ - public function buildFileContainerTemplate() { - $tr = Html::el("tr"); - + public function buildFileContainerTemplate() + { + $tr = Html::el('tr'); + $preview = Html::el("td class='align-middle'"); - $preview->addHtml($this->elements["imagePreview"]->setAttribute("width", "100%")->setAttribute("class", "rounded")); - $preview->addHtml($this->elements["filePreview"]->setName("span")->setAttribute("class", "badge badge-pill badge-info")); + $preview->addHtml($this->elements['imagePreview']->setAttribute('width', '100%')->setAttribute('class', 'rounded')); + $preview->addHtml($this->elements['filePreview']->setName('span')->setAttribute('class', 'badge badge-pill badge-info')); $tr->addHtml($preview); - + $name = Html::el("td class='align-middle'"); - $name->addHtml($this->elements["filename"]); + $name->addHtml($this->elements['filename']); $tr->addHtml($name); - + $progressTd = Html::el("td class='align-middle'"); $progressContainer = Html::el("div class='progress'"); - $progress = $this->elements["fileProgress"]->setAttribute("class", "progress-bar") - ->setAttribute("style", "height: 10px"); + $progress = $this->elements['fileProgress']->setAttribute('class', 'progress-bar') + ->setAttribute('style', 'height: 10px'); $progressContainer->addHtml($progress); $progressTd->addHtml($progressContainer); $tr->addHtml($progressTd); - + $delete = Html::el("td class='align-middle text-center'"); $delete->addHtml( - $this->elements["delete"] - ->setAttribute("class", "btn btn-outline-danger") - ->setHtml("×") + $this->elements['delete'] + ->setAttribute('class', 'btn btn-outline-danger') + ->setHtml('×') ); $tr->addHtml($delete); - + return $tr; } - + + /** * Sestavení šablony pro soubor, u kterého vznikla chyba. * * @return Html */ - public function buildFileError() { + public function buildFileError() + { $tr = Html::el("tr class='bg-danger text-light'"); - $tr->addHtml($this->elements["errorMessage"]->setName("td")->addAttributes([ - "colspan" => 4 + $tr->addHtml($this->elements['errorMessage']->setName('td')->addAttributes([ + 'colspan' => 4, ])); - + return $tr; } } diff --git a/src/Template/Renderer/Html5Renderer.php b/src/Template/Renderer/Html5Renderer.php index 7804b6d..b0bced5 100644 --- a/src/Template/Renderer/Html5Renderer.php +++ b/src/Template/Renderer/Html5Renderer.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Template\Renderer */ -class Html5Renderer extends BaseRenderer { - - /** - * - */ - public function init() { +class Html5Renderer extends BaseRenderer +{ + + + public function init() + { parent::init(); - - $this->elements["globalProgressValue"] = null; - $this->elements["fileProgressValue"] = null; - - $this->elements["container"]->setName("table")->addAttributes([ - "style" => "width: 100%", - "border" => "0" + + $this->elements['globalProgressValue'] = null; + $this->elements['fileProgressValue'] = null; + + $this->elements['container']->setName('table')->addAttributes([ + 'style' => 'width: 100%', + 'border' => '0', ]); - - $this->elements["globalProgress"]->setName("progress") - ->addAttributes([ - "value" => 0, - "max" => 100, - "style" => "width: 100%" - ]); - $this->elements["fileProgress"]->setName("progress") - ->addAttributes([ - "value" => 0, - "max" => 100, - "style" => "width: 100%" - ]); - - $this->elements["imagePreview"]->addAttributes([ - "class" => "fileupload-image-preview" + + $this->elements['globalProgress']->setName('progress') + ->addAttributes([ + 'value' => 0, + 'max' => 100, + 'style' => 'width: 100%', + ]); + $this->elements['fileProgress']->setName('progress') + ->addAttributes([ + 'value' => 0, + 'max' => 100, + 'style' => 'width: 100%', + ]); + + $this->elements['imagePreview']->addAttributes([ + 'class' => 'fileupload-image-preview', ]); - $this->elements["filePreview"]->addAttributes([ - "class" => "fileupload-file-extension" + $this->elements['filePreview']->addAttributes([ + 'class' => 'fileupload-file-extension', ]); - - $this->elements["delete"]->addAttributes([ - "class" => "fileupload-delete-button" - ])->setHtml("×"); + + $this->elements['delete']->addAttributes([ + 'class' => 'fileupload-delete-button', + ])->setHtml('×'); } - + + /** * Sestavení výchozí šablony uploaderu. * @return Html */ - public function buildDefaultTemplate() { - $table = $this->elements["container"]; - $table->setAttribute("cellpadding", "5px"); - + public function buildDefaultTemplate() + { + $table = $this->elements['container']; + $table->setAttribute('cellpadding', '5px'); + // Header - $tr = Html::el("tr"); + $tr = Html::el('tr'); $th = Html::el("th colspan='2' style='border-right: none'"); - $th->setText("Nahrávání souborů"); + $th->setText('Nahrávání souborů'); $tr->addHtml($th); $th2 = Html::el("th colspan='2' style='text-align: right; border-left: none'"); - $th2->addHtml($this->elements["input"]->setAttribute("style", "display: none")); + $th2->addHtml($this->elements['input']->setAttribute('style', 'display: none')); $button = Html::el("button type='button'"); - $button->setText("Nahrát soubor"); - $id = $this->elements["input"]->getAttribute("id"); - $button->setAttribute("onclick", "document.getElementById('$id').click(); return false;"); + $button->setText('Nahrát soubor'); + $id = $this->elements['input']->getAttribute('id'); + $button->setAttribute('onclick', "document.getElementById('$id').click(); return false;"); $th2->addHtml($button); - + $tr->addHtml($th2); $table->addHtml($tr); - + // Global Progress - $tr = Html::el("tr"); + $tr = Html::el('tr'); $td = Html::el("td colspan='4'"); - $td->addHtml($this->elements["globalProgress"]); + $td->addHtml($this->elements['globalProgress']); $tr->addHtml($td); $table->addHtml($tr); - + return $table; } - + + /** * Sestavení šablony pro vkládání nových souborů. * @return Html */ - public function buildFileContainerTemplate() { - $tr = Html::el("tr"); - - $preview = Html::el("td")->addAttributes([ - "style" => "width: 15%" + public function buildFileContainerTemplate() + { + $tr = Html::el('tr'); + + $preview = Html::el('td')->addAttributes([ + 'style' => 'width: 15%', ]); - $preview->addHtml($this->elements["imagePreview"]->setAttribute("width", "100%")); - $preview->addHtml($this->elements["filePreview"]); + $preview->addHtml($this->elements['imagePreview']->setAttribute('width', '100%')); + $preview->addHtml($this->elements['filePreview']); $tr->addHtml($preview); - - $name = Html::el("td"); - $name->addHtml($this->elements["filename"]); + + $name = Html::el('td'); + $name->addHtml($this->elements['filename']); $tr->addHtml($name); - - $progress = Html::el("td"); - $progress->addHtml($this->elements["fileProgress"])->addAttributes([ - "style" => "width: 20%" + + $progress = Html::el('td'); + $progress->addHtml($this->elements['fileProgress'])->addAttributes([ + 'style' => 'width: 20%', ]); $tr->addHtml($progress); - - $delete = Html::el("td")->addAttributes([ - "style" => "width: 50px; text-align: center", + + $delete = Html::el('td')->addAttributes([ + 'style' => 'width: 50px; text-align: center', ]); - $delete->addHtml($this->elements["delete"]); + $delete->addHtml($this->elements['delete']); $tr->addHtml($delete); - + return $tr; } - + + /** * Sestavení šablony pro soubor, u kterého vznikla chyba. * @return Html */ - public function buildFileError() { + public function buildFileError() + { $tr = Html::el("tr style='background-color: #ffb6c1'"); - $tr->addHtml($this->elements["errorMessage"]->setName("td")->addAttributes([ - "colspan" => 4 + $tr->addHtml($this->elements['errorMessage']->setName('td')->addAttributes([ + 'colspan' => 4, ])); - + return $tr; } } diff --git a/src/Template/Renderer/IUploadRenderer.php b/src/Template/Renderer/IUploadRenderer.php index 22afbc3..bf889d1 100644 --- a/src/Template/Renderer/IUploadRenderer.php +++ b/src/Template/Renderer/IUploadRenderer.php @@ -1,5 +1,7 @@ * @package Zet\FileUpload\Template\Renderer */ -interface IUploadRenderer { - +interface IUploadRenderer +{ + + /** * Sestavení výchozí šablony uploaderu. * * @return Html */ public function buildDefaultTemplate(); - + + /** * Sestavení šablony pro vkládání nových souborů. * * @return Html */ public function buildFileContainerTemplate(); - + + /** * Sestavení šablony pro soubor, u kterého vznikla chyba. * diff --git a/src/Template/js.latte b/src/Template/js.latte index 3b60048..bd4c920 100644 --- a/src/Template/js.latte +++ b/src/Template/js.latte @@ -163,4 +163,4 @@ \ No newline at end of file + diff --git a/src/www/fileupload/controller.js b/src/www/fileupload/controller.js index 6889072..34d5a70 100644 --- a/src/www/fileupload/controller.js +++ b/src/www/fileupload/controller.js @@ -1,10 +1,10 @@ var Renderer = function (token, components, inputHtmlId, removeLink) { - + /** * @type {string} */ this.token = token; - + /** * Seznam registrovaných komponent uploaderu společně s jejich html id. * - container Kontejner ve kterém se nachází samotný uploaderu. @@ -22,72 +22,72 @@ var Renderer = function (token, components, inputHtmlId, removeLink) { * @param { object. } */ this.components = components; - + /** * @type {string} */ this.inputHtmlId = inputHtmlId; - + /** * @type {string} */ this.removeLink = removeLink; - + /** * @type {string[]} */ this.imageExtension = [ "jpg", "png", "jpeg", "gif" ]; - + this.getSelector = function (name) { return "[data-upload-component=" + name + "]"; }; - + this.getFileExtension = function (filename) { var filenameArray = filename.split("."); return filenameArray[filenameArray.length - 1]; }; - + this.isImage = function (filename) { return this.imageExtension.indexOf(this.getFileExtension(filename).toLowerCase()) !== -1; }; - + this.setImagePreview = function (element, file) { var preview = ""; - + if (file.preview) { preview = file.preview; } else { //noinspection JSUnresolvedVariable preview = URL.createObjectURL(file); } - + element.setAttribute("src", preview); }; - + this.getFileContainer = function (id) { var container = document.querySelector("[data-upload-id='" + id.toString() + "'][for='" + this.inputHtmlId + "']"); - + return container; }; - - + + this.getTemplate = function (template) { var template = $.parseHTML(document.querySelector("." + template + "[for=" + this.inputHtmlId + "]").innerHTML); return template[1]; }; - + this.errorTemplate = function (file, message) { var template = this.getTemplate("upload-template-file-error"); - + if (this.components.filename != null) { var filename = template.querySelector(this.getSelector(this.components.filename)); if (filename != null) { filename.textContent = file.name; } } - + if (this.components.imagePreview != null && this.isImage(file.name)) { var imagePreview = template.querySelector(this.getSelector(this.components.imagePreview)); if (imagePreview != null) { @@ -99,16 +99,16 @@ var Renderer = function (token, components, inputHtmlId, removeLink) { filePreview.textContent = this.getFileExtension(file.name); } } - + template.querySelector(this.getSelector(this.components.errorMessage)).textContent = message; - + return template; } - + }; Renderer.prototype = { - + /** * @param { object. } file * @param { number } id @@ -117,39 +117,39 @@ Renderer.prototype = { var template = this.getTemplate("upload-template-file-container"); template.setAttribute("data-upload-id", id.toString()); template.setAttribute("for", this.inputHtmlId); - + if (this.components.filename != null) { template.querySelector(this.getSelector(this.components.filename)).textContent = file.name; } - + if (this.isImage(file.name) && this.components.imagePreview != null) { var imagePreview = template.querySelector(this.getSelector(this.components.imagePreview)); this.setImagePreview(imagePreview, file); } else if (this.components.filePreview != null) { template.querySelector(this.getSelector(this.components.filePreview)).textContent = this.getFileExtension(file.name); } - + document.querySelector(this.getSelector(this.components.container)).appendChild(template); }, - + addDefaultFile: function (file, controller) { var template = this.getTemplate("upload-template-file-container"); template.setAttribute("for", this.inputHtmlId); - + if (this.components.filename != null) { template.querySelector(this.getSelector(this.components.filename)).textContent = file.filename; } - + if (this.isImage(file.filename) && this.components.imagePreview != null) { var imagePreview = template.querySelector(this.getSelector(this.components.imagePreview)); imagePreview.setAttribute("src", file.preview); } else if (this.components.filePreview != null) { template.querySelector(this.getSelector(this.components.filePreview)).textContent = this.getFileExtension(file.filename); } - + if (this.components.delete != null) { var deleteButton = template.querySelector(this.getSelector(this.components.delete)); - + var self = this; deleteButton.addEventListener("click", function () { $.ajax({ @@ -168,10 +168,10 @@ Renderer.prototype = { }); }); } - + document.querySelector(this.getSelector(this.components.container)).appendChild(template); }, - + /** * @param { object. } file * @param { number } id @@ -181,14 +181,14 @@ Renderer.prototype = { var template = this.errorTemplate(file, message); document.querySelector(this.getSelector(this.components.container)).appendChild(template); }, - + /** * @param { object } data */ updateFileProgress: function (data) { var container = this.getFileContainer(data.formData[0].value); var percents = parseInt(data.loaded / data.total * 100, 10); - + if (this.components.fileProgress != null) { var progress = container.querySelector(this.getSelector(this.components.fileProgress)); if (progress.tagName.toLowerCase() == "progress") { @@ -197,19 +197,19 @@ Renderer.prototype = { progress.style.width = percents + "%"; } } - + if (this.components.fileProgressValue != null) { var value = container.querySelector(this.getSelector(this.components.fileProgressValue)); value.textContent = percents + "%"; } }, - + /** * @param { object } data */ updateProgressAll: function (data) { var percents = parseInt(data.loaded / data.total * 100, 10); - + if (this.components.globalProgress != null) { var progress = document.querySelector(this.getSelector(this.components.globalProgress)); if (progress.tagName.toLowerCase() == "progress") { @@ -218,13 +218,13 @@ Renderer.prototype = { progress.style.width = percents + "%"; } } - + if (this.components.globalProgressValue != null) { var value = document.querySelector(this.getSelector(this.components.globalProgressValue)); value.textContent = percents + "%"; } }, - + /** * */ @@ -237,13 +237,13 @@ Renderer.prototype = { progress.style.width = "0%"; } } - + if (this.components.globalProgressValue != null) { var value = document.querySelector(this.getSelector(this.components.globalProgressValue)); value.textContent = "0%"; } }, - + /** * @param { Object } file * @param { string } message @@ -252,20 +252,20 @@ Renderer.prototype = { fileError: function (file, message, id) { var template = this.errorTemplate(file, message); var fileContainer = this.getFileContainer(id); - + $(fileContainer).replaceWith(template); }, - + /** * @param { number } id * @param { FileUploadController } controller */ fileDone: function (id, controller) { var fileContainer = this.getFileContainer(id); - + if (this.components.delete != null) { var deleteButton = fileContainer.querySelector(this.getSelector(this.components.delete)); - + var self = this; deleteButton.addEventListener("click", function () { $.ajax({ @@ -295,45 +295,45 @@ Renderer.prototype = { * @constructor */ var FileUploadController = function (id, token, renderer, config, messages) { - + /** * @type {number} */ this.id = id; - + /** * @type {string} */ this.token = token; - + /** * @type {Renderer} */ this.renderer = renderer; - + /** * @type {object} */ this.config = config; - + /** * ID uploadovaného souboru. * @type {number} */ this.fileId = 0; - + /** * Počet nahraných souborů. * @type {number} */ this.uploaded = 0; - + /** * Počet přidaných souborů. * @type {number} */ this.addedFiles = 0; - + /** * Chybové hlášky. * @type {object.} @@ -342,7 +342,7 @@ var FileUploadController = function (id, token, renderer, config, messages) { }; FileUploadController.prototype = { - + /** * Přidání nového souboru k odeslání. * @param {object.} files @@ -352,7 +352,7 @@ FileUploadController.prototype = { var readyToSend = false; var file = files[0]; var message = ""; - + if (!this.canUploadNextFile()) { message = this.messages.maxFiles.replace("{maxFiles}", this.config.maxFiles.toString()); this.renderer.addError(file, this.fileId, message); @@ -366,10 +366,10 @@ FileUploadController.prototype = { this.renderer.add(file, this.fileId); readyToSend = true; } - + return readyToSend; }, - + /** * Aktualizace celkového postupu nahrávání. * @param {Object} data @@ -377,7 +377,7 @@ FileUploadController.prototype = { updateProgressAll: function (data) { this.renderer.updateProgressAll(data); }, - + /** * Aktualizace postupu nahrávání jednoho souboru. * @param {Object} data @@ -385,28 +385,28 @@ FileUploadController.prototype = { updateFileProgress: function (data) { this.renderer.updateFileProgress(data); }, - + /** * Spuštění uploadu. */ start: function () { this.renderer.start(); }, - + /** * Dokončení uploadu. * @param {object} data */ done: function (data) { var success = true; - + var result = data.result; var id = result.id; var error = result.error; - + if (error !== 0) { var msg = ""; - + switch (error) { case 1: case 2: @@ -441,7 +441,7 @@ FileUploadController.prototype = { } else { this.renderer.fileDone(id, this); } - + if (success) { this.uploaded++; } else { @@ -449,7 +449,7 @@ FileUploadController.prototype = { this.addedFiles -= 1; } }, - + /** * ID dalšího souboru k odeslání. * @returns {number} @@ -457,7 +457,7 @@ FileUploadController.prototype = { getFileId: function () { return this.fileId++; }, - + /** * Může uživatel nahrát další soubor? * @returns {boolean} @@ -465,14 +465,14 @@ FileUploadController.prototype = { canUploadNextFile: function () { return this.uploaded < this.config.maxFiles && this.addedFiles < this.config.maxFiles; }, - + /** * @returns {Object.} */ getMessages: function () { return this.messages; }, - + /** * * @param defaultFiles diff --git a/src/www/fileupload/functions.js b/src/www/fileupload/functions.js index 6b9d5d2..9b175b3 100644 --- a/src/www/fileupload/functions.js +++ b/src/www/fileupload/functions.js @@ -7,7 +7,7 @@ var readyList = []; var readyFired = false; var readyEventHandlersInstalled = false; - + // call this when the document is ready // this function protects itself against being called more than once function ready() { @@ -27,13 +27,13 @@ readyList = []; } } - + function readyStateChange() { if (document.readyState === "complete") { ready(); } } - + // This is the one public interface // docReady(fn, context); // the context argument is optional - if present, it will be passed @@ -82,4 +82,4 @@ var extendsClass = function (child, parent) { child.prototype = new F(); child._superClass = parent.prototype; child.prototype.constructor = child; -}; \ No newline at end of file +}; diff --git a/src/www/fileupload/js/app.js b/src/www/fileupload/js/app.js index 6f1a24f..2abf90e 100644 --- a/src/www/fileupload/js/app.js +++ b/src/www/fileupload/js/app.js @@ -14,10 +14,10 @@ ;(function () { 'use strict'; - + var isOnGitHub = window.location.hostname === 'blueimp.github.io', url = isOnGitHub ? '//jquery-file-upload.appspot.com/' : 'server/php/'; - + angular.module('demo', [ 'blueimp.fileupload' ]) @@ -43,7 +43,7 @@ } } ]) - + .controller('DemoFileUploadController', [ '$scope', '$http', '$filter', '$window', function ($scope, $http) { @@ -65,7 +65,7 @@ } } ]) - + .controller('FileDestroyController', [ '$scope', '$http', function ($scope, $http) { @@ -97,5 +97,5 @@ } } ]); - + }()); diff --git a/src/www/fileupload/js/cors/jquery.postmessage-transport.js b/src/www/fileupload/js/cors/jquery.postmessage-transport.js index 257436e..ec3071e 100644 --- a/src/www/fileupload/js/cors/jquery.postmessage-transport.js +++ b/src/www/fileupload/js/cors/jquery.postmessage-transport.js @@ -25,7 +25,7 @@ } }(function ($) { 'use strict'; - + var counter = 0, names = [ 'accepts', @@ -49,7 +49,7 @@ convert = function (p) { return p; }; - + $.ajaxSetup({ converters: { 'postmessage text': convert, @@ -57,7 +57,7 @@ 'postmessage html': convert } }); - + $.ajaxTransport('postmessage', function (options) { if (options.postMessage && window.postMessage) { var iframe, @@ -122,5 +122,5 @@ }; } }); - + })); diff --git a/src/www/fileupload/js/cors/jquery.xdr-transport.js b/src/www/fileupload/js/cors/jquery.xdr-transport.js index ebab4cc..2d662d1 100644 --- a/src/www/fileupload/js/cors/jquery.xdr-transport.js +++ b/src/www/fileupload/js/cors/jquery.xdr-transport.js @@ -39,13 +39,13 @@ return { send: function (headers, completeCallback) { var addParamChar = /\?/.test(s.url) ? '&' : '?'; - + function callback(status, statusText, responses, responseHeaders) { xdr.onload = xdr.onerror = xdr.ontimeout = $.noop; xdr = null; completeCallback(status, statusText, responses, responseHeaders); } - + xdr = new XDomainRequest(); // XDomainRequest only supports GET and POST: if (s.type === 'DELETE') { diff --git a/src/www/fileupload/js/jquery.fileupload-angular.js b/src/www/fileupload/js/jquery.fileupload-angular.js index 4009937..d6aed04 100644 --- a/src/www/fileupload/js/jquery.fileupload-angular.js +++ b/src/www/fileupload/js/jquery.fileupload-angular.js @@ -39,9 +39,9 @@ } }(function () { 'use strict'; - + angular.module('blueimp.fileupload', []) - + // The fileUpload service provides configuration options // for the fileUpload directive and default handlers for // File Upload events: @@ -163,7 +163,7 @@ } ]; }) - + // Format byte numbers to readable presentations: .provider('formatFileSizeFilter', function () { var $config = { @@ -197,7 +197,7 @@ }; }; }) - + // The FileUploadController initializes the fileupload widget and // provides scope methods to control the File Upload functionality: .controller('FileUploadController', [ @@ -353,7 +353,7 @@ ); } ]) - + // Provide File Upload progress feedback: .controller('FileUploadProgressController', [ '$scope', '$attrs', '$parse', @@ -379,7 +379,7 @@ ); } ]) - + // Display File Upload previews: .controller('FileUploadPreviewController', [ '$scope', '$element', '$attrs', @@ -395,27 +395,27 @@ ); } ]) - + .directive('fileUpload', function () { return { controller: 'FileUploadController', scope: true }; }) - + .directive('fileUploadProgress', function () { return { controller: 'FileUploadProgressController', scope: true }; }) - + .directive('fileUploadPreview', function () { return { controller: 'FileUploadPreviewController' }; }) - + // Enhance the HTML5 download attribute to // allow drag&drop of files to the desktop: .directive('download', function () { @@ -435,5 +435,5 @@ }); }; }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-audio.js b/src/www/fileupload/js/jquery.fileupload-audio.js index a5a4662..c8fc70d 100644 --- a/src/www/fileupload/js/jquery.fileupload-audio.js +++ b/src/www/fileupload/js/jquery.fileupload-audio.js @@ -37,7 +37,7 @@ } }(function ($, loadImage) { 'use strict'; - + // Prepend to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.unshift( { @@ -54,21 +54,21 @@ disabled: '@disableAudioPreview' } ); - + // The File Upload Audio Preview plugin extends the fileupload widget // with audio preview functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { // The regular expression for the types of audio files to load, // matched against the file type: loadAudioFileTypes: /^audio\/.*$/ }, - + _audioElement: document.createElement('audio'), - + processActions: { - + // Loads the audio file given via data.files and data.index // as audio element if the browser supports playing it. // Accepts the options fileTypes (regular expression) @@ -97,7 +97,7 @@ } return data; }, - + // Sets the audio element as a property of the file object: setAudio: function (data, options) { if (data.audio && !options.disabled) { @@ -105,9 +105,9 @@ } return data; } - + } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-image.js b/src/www/fileupload/js/jquery.fileupload-image.js index e8d10ee..cd61504 100644 --- a/src/www/fileupload/js/jquery.fileupload-image.js +++ b/src/www/fileupload/js/jquery.fileupload-image.js @@ -45,7 +45,7 @@ } }(function ($, loadImage) { 'use strict'; - + // Prepend to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.unshift( { @@ -113,11 +113,11 @@ disabled: '@disableImageReferencesDeletion' } ); - + // The File Upload Resize plugin extends the fileupload widget // with image resize functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { // The regular expression for the types of images to load: // matched against the file type: @@ -149,9 +149,9 @@ // Define if preview images should be resized as canvas elements: previewCanvas: true }, - + processActions: { - + // Loads the image given via data.files and data.index // as img element, if the browser supports the File API. // Accepts the options fileTypes (regular expression) @@ -181,7 +181,7 @@ } return dfd.promise(); }, - + // Resizes the image given as data.canvas or data.img // and updates data.canvas or data.img with the resized image. // Also stores the resized image as preview property. @@ -229,7 +229,7 @@ } return data; }, - + // Saves the processed image given as data.canvas // inplace at data.index of data.files: saveImage: function (data, options) { @@ -269,7 +269,7 @@ } return dfd.promise(); }, - + loadImageMetaData: function (data, options) { if (options.disabled) { return data; @@ -282,7 +282,7 @@ }, options); return dfd.promise(); }, - + saveImageMetaData: function (data, options) { if (!(data.imageHead && data.canvas && data.canvas.toBlob && !options.disabled)) { @@ -299,7 +299,7 @@ data.files[data.index] = blob; return data; }, - + // Sets the resized version of the image as a property of the // file object, must be called after "saveImage": setImage: function (data, options) { @@ -308,7 +308,7 @@ } return data; }, - + deleteImageReferences: function (data, options) { if (!options.disabled) { delete data.img; @@ -318,9 +318,9 @@ } return data; } - + } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-jquery-ui.js b/src/www/fileupload/js/jquery.fileupload-jquery-ui.js index 4ef96fc..a910650 100644 --- a/src/www/fileupload/js/jquery.fileupload-jquery-ui.js +++ b/src/www/fileupload/js/jquery.fileupload-jquery-ui.js @@ -32,9 +32,9 @@ } }(function ($) { 'use strict'; - + $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { processdone: function (e, data) { data.context.find('.start').button('enable'); @@ -65,7 +65,7 @@ }); } }, - + _renderUpload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; @@ -83,7 +83,7 @@ } return node; }, - + _renderDownload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; @@ -96,12 +96,12 @@ } return node; }, - + _startHandler: function (e) { $(e.currentTarget).button('disable'); this._super(e); }, - + _transition: function (node) { var deferred = $.Deferred(); if (node.hasClass('fade')) { @@ -117,7 +117,7 @@ } return deferred; }, - + _create: function () { this._super(); this.element @@ -136,7 +136,7 @@ .button({icons: {primary: 'ui-icon-trash'}}) .end().find('.progress').progressbar(); }, - + _destroy: function () { this.element .find('.fileupload-buttonbar') @@ -155,7 +155,7 @@ .end().find('.progress').progressbar('destroy'); this._super(); } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-process.js b/src/www/fileupload/js/jquery.fileupload-process.js index fcc66c0..2a22ec6 100644 --- a/src/www/fileupload/js/jquery.fileupload-process.js +++ b/src/www/fileupload/js/jquery.fileupload-process.js @@ -34,13 +34,13 @@ } }(function ($) { 'use strict'; - + var originalAdd = $.blueimp.fileupload.prototype.options.add; - + // The File Upload Processing plugin extends the fileupload widget // with file processing functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { // The list of processing actions: processQueue: [ @@ -59,7 +59,7 @@ originalAdd.call(this, e, data); } }, - + processActions: { /* log: function (data, options) { @@ -69,7 +69,7 @@ } */ }, - + _processFile: function (data, originalData) { var that = this, dfd = $.Deferred().resolveWith(that, [data]), @@ -100,7 +100,7 @@ }); return chain; }, - + // Replaces the settings of each processQueue item that // are strings starting with an "@", using the remaining // substring as key for the option map, @@ -121,18 +121,18 @@ } else { settings[key] = value; } - + }); processQueue.push(settings); }); options.processQueue = processQueue; }, - + // Returns the number of files currently in the processsing queue: processing: function () { return this._processing; }, - + // Processes the files given as files property of the data parameter, // returns a Promise object that allows to bind callbacks: process: function (data) { @@ -165,14 +165,14 @@ } return this._processingQueue; }, - + _create: function () { this._super(); this._processing = 0; this._processingQueue = $.Deferred().resolveWith(this) .promise(); } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-ui.js b/src/www/fileupload/js/jquery.fileupload-ui.js index 59a7834..bdb5d39 100644 --- a/src/www/fileupload/js/jquery.fileupload-ui.js +++ b/src/www/fileupload/js/jquery.fileupload-ui.js @@ -43,17 +43,17 @@ } }(function ($, tmpl) { 'use strict'; - + $.blueimp.fileupload.prototype._specialOptions.push( 'filesContainer', 'uploadTemplateId', 'downloadTemplateId' ); - + // The UI version extends the file upload widget // and adds complete user interface interaction: $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { // By default, files added to the widget are uploaded as soon // as the user clicks on the start buttons. To enable automatic @@ -72,19 +72,19 @@ // The expected data type of the upload response, sets the dataType // option of the $.ajax upload requests: dataType: 'json', - + // Error and info messages: messages: { unknownError: 'Unknown error' }, - + // Function returning the current number of files, // used by the maxNumberOfFiles validation: getNumberOfFiles: function () { return this.filesContainer.children() .not('.processing').length; }, - + // Callback to retrieve the list of files from the server response: getFilesFromResponse: function (data) { if (data.result && $.isArray(data.result.files)) { @@ -92,7 +92,7 @@ } return []; }, - + // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop or add API call). // See the basic file upload widget for more information: @@ -392,11 +392,11 @@ } } }, - + _resetFinishedDeferreds: function () { this._finishedUploads = []; }, - + _addFinishedDeferreds: function (deferred) { if (!deferred) { deferred = $.Deferred(); @@ -404,11 +404,11 @@ this._finishedUploads.push(deferred); return deferred; }, - + _getFinishedDeferreds: function () { return this._finishedUploads; }, - + // Link handler, that allows to download files // by drag & drop of the links to the desktop: _enableDragToDesktop: function () { @@ -426,7 +426,7 @@ } }); }, - + _formatFileSize: function (bytes) { if (typeof bytes !== 'number') { return ''; @@ -439,7 +439,7 @@ } return (bytes / 1000).toFixed(2) + ' KB'; }, - + _formatBitrate: function (bits) { if (typeof bits !== 'number') { return ''; @@ -455,7 +455,7 @@ } return bits.toFixed(2) + ' bit/s'; }, - + _formatTime: function (seconds) { var date = new Date(seconds * 1000), days = Math.floor(seconds / 86400); @@ -465,11 +465,11 @@ ('0' + date.getUTCMinutes()).slice(-2) + ':' + ('0' + date.getUTCSeconds()).slice(-2); }, - + _formatPercentage: function (floatValue) { return (floatValue * 100).toFixed(2) + ' %'; }, - + _renderExtendedProgress: function (data) { return this._formatBitrate(data.bitrate) + ' | ' + this._formatTime( @@ -481,7 +481,7 @@ this._formatFileSize(data.loaded) + ' / ' + this._formatFileSize(data.total); }, - + _renderTemplate: function (func, files) { if (!func) { return $(); @@ -496,27 +496,27 @@ } return $(this.options.templatesContainer).html(result).children(); }, - + _renderPreviews: function (data) { data.context.find('.preview').each(function (index, elm) { $(elm).append(data.files[index].preview); }); }, - + _renderUpload: function (files) { return this._renderTemplate( this.options.uploadTemplate, files ); }, - + _renderDownload: function (files) { return this._renderTemplate( this.options.downloadTemplate, files ).find('a[download]').each(this._enableDragToDesktop).end(); }, - + _startHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget), @@ -527,7 +527,7 @@ data.submit(); } }, - + _cancelHandler: function (e) { e.preventDefault(); var template = $(e.currentTarget) @@ -541,7 +541,7 @@ this._trigger('fail', e, data); } }, - + _deleteHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget); @@ -550,12 +550,12 @@ type: 'DELETE' }, button.data())); }, - + _forceReflow: function (node) { return $.support.transition && node.length && node[0].offsetWidth; }, - + _transition: function (node) { var dfd = $.Deferred(); if ($.support.transition && node.hasClass('fade') && node.is(':visible')) { @@ -576,7 +576,7 @@ } return dfd; }, - + _initButtonBarEventHandlers: function () { var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'), filesList = this.options.filesContainer; @@ -611,7 +611,7 @@ } }); }, - + _destroyButtonBarEventHandlers: function () { this._off( this.element.find('.fileupload-buttonbar') @@ -623,7 +623,7 @@ 'change.' ); }, - + _initEventHandlers: function () { this._super(); this._on(this.options.filesContainer, { @@ -633,25 +633,25 @@ }); this._initButtonBarEventHandlers(); }, - + _destroyEventHandlers: function () { this._destroyButtonBarEventHandlers(); this._off(this.options.filesContainer, 'click'); this._super(); }, - + _enableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', false) .parent().removeClass('disabled'); }, - + _disableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', true) .parent().addClass('disabled'); }, - + _initTemplates: function () { var options = this.options; options.templatesContainer = this.document[0].createElement( @@ -666,7 +666,7 @@ } } }, - + _initFilesContainer: function () { var options = this.options; if (options.filesContainer === undefined) { @@ -675,13 +675,13 @@ options.filesContainer = $(options.filesContainer); } }, - + _initSpecialOptions: function () { this._super(); this._initFilesContainer(); this._initTemplates(); }, - + _create: function () { this._super(); this._resetFinishedDeferreds(); @@ -689,7 +689,7 @@ this._disableFileInputButton(); } }, - + enable: function () { var wasDisabled = false; if (this.options.disabled) { @@ -701,7 +701,7 @@ this._enableFileInputButton(); } }, - + disable: function () { if (!this.options.disabled) { this.element.find('input, button').prop('disabled', true); @@ -709,7 +709,7 @@ } this._super(); } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-validate.js b/src/www/fileupload/js/jquery.fileupload-validate.js index 4674cab..436526a 100644 --- a/src/www/fileupload/js/jquery.fileupload-validate.js +++ b/src/www/fileupload/js/jquery.fileupload-validate.js @@ -33,7 +33,7 @@ } }(function ($) { 'use strict'; - + // Append to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.push( { @@ -49,11 +49,11 @@ disabled: '@disableValidation' } ); - + // The File Upload Validation plugin extends the fileupload widget // with file validation functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { /* // The regular expression for allowed file types, matches @@ -66,11 +66,11 @@ // The limit of files to be uploaded: maxNumberOfFiles: 10, */ - + // Function returning the current number of files, // has to be overriden for maxNumberOfFiles validation: getNumberOfFiles: $.noop, - + // Error and info messages: messages: { maxNumberOfFiles: 'Maximum number of files exceeded', @@ -79,9 +79,9 @@ minFileSize: 'File is too small' } }, - + processActions: { - + validate: function (data, options) { if (options.disabled) { return data; @@ -117,9 +117,9 @@ } return dfd.promise(); } - + } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload-video.js b/src/www/fileupload/js/jquery.fileupload-video.js index c308dc4..78cda22 100644 --- a/src/www/fileupload/js/jquery.fileupload-video.js +++ b/src/www/fileupload/js/jquery.fileupload-video.js @@ -37,7 +37,7 @@ } }(function ($, loadImage) { 'use strict'; - + // Prepend to the default processQueue: $.blueimp.fileupload.prototype.options.processQueue.unshift( { @@ -54,21 +54,21 @@ disabled: '@disableVideoPreview' } ); - + // The File Upload Video Preview plugin extends the fileupload widget // with video preview functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { - + options: { // The regular expression for the types of video files to load, // matched against the file type: loadVideoFileTypes: /^video\/.*$/ }, - + _videoElement: document.createElement('video'), - + processActions: { - + // Loads the video file given via data.files and data.index // as video element if the browser supports playing it. // Accepts the options fileTypes (regular expression) @@ -97,7 +97,7 @@ } return data; }, - + // Sets the video element as a property of the file object: setVideo: function (data, options) { if (data.video && !options.disabled) { @@ -105,9 +105,9 @@ } return data; } - + } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.fileupload.js b/src/www/fileupload/js/jquery.fileupload.js index f9be7f8..9eed5cc 100644 --- a/src/www/fileupload/js/jquery.fileupload.js +++ b/src/www/fileupload/js/jquery.fileupload.js @@ -32,7 +32,7 @@ } }(function ($) { 'use strict'; - + // Detect file input support, based on // http://viljamis.com/blog/2012/file-upload-support-on-mobile/ $.support.fileInput = !(new RegExp( @@ -44,7 +44,7 @@ ).test(window.navigator.userAgent) || // Feature detection for all other devices: $('').prop('disabled')); - + // The FileReader API is not actually used, but works as feature detection, // as some Safari versions (5?) support XHR file uploads via the FormData API, // but not non-multipart XHR file uploads. @@ -52,11 +52,11 @@ // window.ProgressEvent instead to detect XHR2 file upload capability: $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader); $.support.xhrFormDataFileUpload = !!window.FormData; - + // Detect support for Blob slicing (required for chunked uploads): $.support.blobSlice = window.Blob && (Blob.prototype.slice || Blob.prototype.webkitSlice || Blob.prototype.mozSlice); - + // Helper function to create drag handlers for dragover/dragenter/dragleave: function getDragHandler(type) { var isDragOver = type === 'dragover'; @@ -75,7 +75,7 @@ } }; } - + // The fileupload widget listens for change events on file input fields defined // via fileInput setting and paste or drop events of the given dropZone. // In addition to the default jQuery Widget methods, the fileupload widget @@ -85,7 +85,7 @@ // "add" method are uploaded immediately, but it is possible to override // the "add" callback option to queue file uploads. $.widget('blueimp.fileupload', { - + options: { // The drop target element(s), by the default the complete document. // Set to null to disable drag & drop support: @@ -165,12 +165,12 @@ bitrateInterval: 500, // By default, uploads are started automatically when adding files: autoUpload: true, - + // Error and info messages: messages: { uploadedBytes: 'Uploaded bytes exceed file size' }, - + // Translation function, gets the message key to be translated // and an object with context specific data as arguments: i18n: function (message, context) { @@ -182,7 +182,7 @@ } return message; }, - + // Additional form data to be sent along with the file uploads can be set // using this option, which accepts an array of objects with name and // value properties, a function returning such an array, a FormData @@ -191,7 +191,7 @@ formData: function (form) { return form.serializeArray(); }, - + // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop, paste or add API call). // If the singleFileUploads option is enabled, this callback will be @@ -219,60 +219,60 @@ }); } }, - + // Other callbacks: - + // Callback for the submit event of each file upload: // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); - + // Callback for the start of each file upload request: // send: function (e, data) {}, // .bind('fileuploadsend', func); - + // Callback for successful uploads: // done: function (e, data) {}, // .bind('fileuploaddone', func); - + // Callback for failed (abort or error) uploads: // fail: function (e, data) {}, // .bind('fileuploadfail', func); - + // Callback for completed (success, abort or error) requests: // always: function (e, data) {}, // .bind('fileuploadalways', func); - + // Callback for upload progress events: // progress: function (e, data) {}, // .bind('fileuploadprogress', func); - + // Callback for global upload progress events: // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); - + // Callback for uploads start, equivalent to the global ajaxStart event: // start: function (e) {}, // .bind('fileuploadstart', func); - + // Callback for uploads stop, equivalent to the global ajaxStop event: // stop: function (e) {}, // .bind('fileuploadstop', func); - + // Callback for change events of the fileInput(s): // change: function (e, data) {}, // .bind('fileuploadchange', func); - + // Callback for paste events to the pasteZone(s): // paste: function (e, data) {}, // .bind('fileuploadpaste', func); - + // Callback for drop events of the dropZone(s): // drop: function (e, data) {}, // .bind('fileuploaddrop', func); - + // Callback for dragover events of the dropZone(s): // dragover: function (e) {}, // .bind('fileuploaddragover', func); - + // Callback for the start of each chunk upload request: // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); - + // Callback for successful chunk uploads: // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); - + // Callback for failed (abort or error) chunk uploads: // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); - + // Callback for completed (success, abort or error) chunk upload requests: // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); - + // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: processData: false, @@ -280,7 +280,7 @@ cache: false, timeout: 0 }, - + // A list of options that require reinitializing event listeners and/or // special initialization code: _specialOptions: [ @@ -290,12 +290,12 @@ 'multipart', 'forceIframeTransport' ], - + _blobSlice: $.support.blobSlice && function () { var slice = this.slice || this.webkitSlice || this.mozSlice; return slice.apply(this, arguments); }, - + _BitrateTimer: function () { this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); this.loaded = 0; @@ -310,13 +310,13 @@ return this.bitrate; }; }, - + _isXHRUpload: function (options) { return !options.forceIframeTransport && ((!options.multipart && $.support.xhrFileUpload) || $.support.xhrFormDataFileUpload); }, - + _getFormData: function (options) { var formData; if ($.type(options.formData) === 'function') { @@ -334,7 +334,7 @@ } return []; }, - + _getTotal: function (files) { var total = 0; $.each(files, function (index, file) { @@ -342,7 +342,7 @@ }); return total; }, - + _initProgressObject: function (obj) { var progress = { loaded: 0, @@ -355,7 +355,7 @@ obj._progress = progress; } }, - + _initResponseObject: function (obj) { var prop; if (obj._response) { @@ -368,7 +368,7 @@ obj._response = {}; } }, - + _onProgress: function (e, data) { if (e.lengthComputable) { var now = ((Date.now) ? Date.now() : (new Date()).getTime()), @@ -413,7 +413,7 @@ ); } }, - + _initProgressListener: function (options) { var that = this, xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); @@ -433,12 +433,12 @@ }; } }, - + _isInstanceOf: function (type, obj) { // Cross-frame instanceof check return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, - + _initXHRData: function (options) { var that = this, formData, @@ -511,7 +511,7 @@ // Blob reference is not needed anymore, free memory: options.blob = null; }, - + _initIframeSettings: function (options) { var targetHost = $('').prop('href', options.url).prop('host'); // Setting the dataType to iframe enables the iframe transport: @@ -526,7 +526,7 @@ }); } }, - + _initDataSettings: function (options) { if (this._isXHRUpload(options)) { if (!this._chunkedUpload(options, true)) { @@ -544,7 +544,7 @@ this._initIframeSettings(options); } }, - + _getParamName: function (options) { var fileInput = $(options.fileInput), paramName = options.paramName; @@ -567,7 +567,7 @@ } return paramName; }, - + _initFormSettings: function (options) { // Retrieve missing options from the input field and the // associated form, if available: @@ -596,14 +596,14 @@ options.formAcceptCharset = options.form.attr('accept-charset'); } }, - + _getAJAXSettings: function (data) { var options = $.extend({}, this.options, data); this._initFormSettings(options); this._initDataSettings(options); return options; }, - + // jQuery 1.6 doesn't provide .state(), // while jQuery 1.8+ removed .isRejected() and .isResolved(): _getDeferredState: function (deferred) { @@ -618,7 +618,7 @@ } return 'pending'; }, - + // Maps jqXHR callbacks to the equivalent // methods of the given Promise object: _enhancePromise: function (promise) { @@ -627,7 +627,7 @@ promise.complete = promise.always; return promise; }, - + // Creates and returns a Promise object enhanced with // the jqXHR methods abort, success, error and complete: _getXHRPromise: function (resolveOrReject, context, args) { @@ -642,7 +642,7 @@ promise.abort = dfd.promise; return this._enhancePromise(promise); }, - + // Adds convenience methods to the data callback argument: _addConvenienceMethods: function (e, data) { var that = this, @@ -702,7 +702,7 @@ return this._response; }; }, - + // Parses the Range header from the server response // and returns the uploaded bytes: _getUploadedBytes: function (jqXHR) { @@ -712,7 +712,7 @@ parseInt(parts[1], 10); return upperBytesPos && upperBytesPos + 1; }, - + // Uploads a file in multiple, sequential requests // by splitting the file up in multiple blob chunks. // If the second parameter is true, only tests if the file @@ -817,7 +817,7 @@ upload(); return promise; }, - + _beforeSend: function (e, data) { if (this._active === 0) { // the start callback is triggered when an upload starts @@ -843,7 +843,7 @@ this._progress.loaded += data.loaded; this._progress.total += data.total; }, - + _onDone: function (result, textStatus, jqXHR, options) { var total = options._progress.total, response = options._response; @@ -861,7 +861,7 @@ response.jqXHR = options.jqXHR = jqXHR; this._trigger('done', null, options); }, - + _onFail: function (jqXHR, textStatus, errorThrown, options) { var response = options._response; if (options.recalculateProgress) { @@ -875,13 +875,13 @@ response.errorThrown = options.errorThrown = errorThrown; this._trigger('fail', null, options); }, - + _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { // jqXHRorResult, textStatus and jqXHRorError are added to the // options object via done and fail callbacks this._trigger('always', null, options); }, - + _onSend: function (e, data) { if (!data.submit) { this._addConvenienceMethods(e, data); @@ -967,7 +967,7 @@ } return send(); }, - + _onAdd: function (e, data) { var that = this, result = true, @@ -1043,7 +1043,7 @@ }); return result; }, - + _replaceFileInput: function (data) { var input = data.fileInput, inputClone = input.clone(true), @@ -1076,7 +1076,7 @@ this.element = inputClone; } }, - + _handleFileTreeEntry: function (entry, path) { var that = this, dfd = $.Deferred(), @@ -1132,7 +1132,7 @@ } return dfd.promise(); }, - + _handleFileTreeEntries: function (entries, path) { var that = this; return $.when.apply( @@ -1147,7 +1147,7 @@ ); }); }, - + _getDroppedFiles: function (dataTransfer) { dataTransfer = dataTransfer || {}; var items = dataTransfer.items; @@ -1172,7 +1172,7 @@ $.makeArray(dataTransfer.files) ).promise(); }, - + _getSingleFileInputFiles: function (fileInput) { fileInput = $(fileInput); var entries = fileInput.prop('webkitEntries') || @@ -1201,7 +1201,7 @@ } return $.Deferred().resolve(files).promise(); }, - + _getFileInputFiles: function (fileInput) { if (!(fileInput instanceof $) || fileInput.length === 1) { return this._getSingleFileInputFiles(fileInput); @@ -1216,7 +1216,7 @@ ); }); }, - + _onChange: function (e) { var that = this, data = { @@ -1237,7 +1237,7 @@ } }); }, - + _onPaste: function (e) { var items = e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.items, @@ -1258,7 +1258,7 @@ } } }, - + _onDrop: function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var that = this, @@ -1278,13 +1278,13 @@ }); } }, - + _onDragOver: getDragHandler('dragover'), - + _onDragEnter: getDragHandler('dragenter'), - + _onDragLeave: getDragHandler('dragleave'), - + _initEventHandlers: function () { if (this._isXHRUpload(this.options)) { this._on(this.options.dropZone, { @@ -1305,17 +1305,17 @@ }); } }, - + _destroyEventHandlers: function () { this._off(this.options.dropZone, 'dragenter dragleave dragover drop'); this._off(this.options.pasteZone, 'paste'); this._off(this.options.fileInput, 'change'); }, - + _destroy: function () { this._destroyEventHandlers(); }, - + _setOption: function (key, value) { var reinit = $.inArray(key, this._specialOptions) !== -1; if (reinit) { @@ -1327,7 +1327,7 @@ this._initEventHandlers(); } }, - + _initSpecialOptions: function () { var options = this.options; if (options.fileInput === undefined) { @@ -1343,19 +1343,19 @@ options.pasteZone = $(options.pasteZone); } }, - + _getRegExp: function (str) { var parts = str.split('/'), modifiers = parts.pop(); parts.shift(); return new RegExp(parts.join('/'), modifiers); }, - + _isRegExpOption: function (key, value) { return key !== 'url' && $.type(value) === 'string' && /^\/.*\/[igm]{0,3}$/.test(value); }, - + _initDataAttributes: function () { var that = this, options = this.options, @@ -1380,7 +1380,7 @@ } ); }, - + _create: function () { this._initDataAttributes(); this._initSpecialOptions(); @@ -1390,13 +1390,13 @@ this._initProgressObject(this); this._initEventHandlers(); }, - + // This method is exposed to the widget API and allows to query // the number of active uploads: active: function () { return this._active; }, - + // This method is exposed to the widget API and allows to query // the widget upload progress. // It returns an object with loaded, total and bitrate properties @@ -1404,7 +1404,7 @@ progress: function () { return this._progress; }, - + // This method is exposed to the widget API and allows adding files // using the fileupload API. The data parameter accepts an object which // must have a files property and can contain additional options: @@ -1424,7 +1424,7 @@ this._onAdd(null, data); } }, - + // This method is exposed to the widget API and allows sending files // using the fileupload API. The data parameter accepts an object which // must have a files or fileInput property and can contain additional options: @@ -1476,7 +1476,7 @@ } return this._getXHRPromise(false, data && data.context); } - + }); - + })); diff --git a/src/www/fileupload/js/jquery.iframe-transport.js b/src/www/fileupload/js/jquery.iframe-transport.js index 53d3f6a..0893b13 100644 --- a/src/www/fileupload/js/jquery.iframe-transport.js +++ b/src/www/fileupload/js/jquery.iframe-transport.js @@ -25,17 +25,17 @@ } }(function ($) { 'use strict'; - + // Helper variable to create unique names for the transport iframes: var counter = 0, jsonAPI = $, jsonParse = 'parseJSON'; - + if ('JSON' in window && 'parse' in JSON) { jsonAPI = JSON; jsonParse = 'parse'; } - + // The iframe transport accepts four additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, @@ -187,7 +187,7 @@ }; } }); - + // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, xml // and script. @@ -220,5 +220,5 @@ } } }); - + })); diff --git a/src/www/fileupload/js/main.js b/src/www/fileupload/js/main.js index 2fdede3..40216a2 100644 --- a/src/www/fileupload/js/main.js +++ b/src/www/fileupload/js/main.js @@ -13,14 +13,14 @@ $(function () { 'use strict'; - + // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: 'server/php/' }); - + // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', @@ -30,7 +30,7 @@ $(function () { '/cors/result.html?%s' ) ); - + if (window.location.hostname === 'blueimp.github.io') { // Demo settings: $('#fileupload').fileupload('option', { @@ -71,5 +71,5 @@ $(function () { .call(this, $.Event('done'), {result: result}); }); } - + }); diff --git a/src/www/fileupload/style.css b/src/www/fileupload/style.css index 87c7ea8..74d7633 100644 --- a/src/www/fileupload/style.css +++ b/src/www/fileupload/style.css @@ -52,4 +52,4 @@ .well.well-sm.zet-fileupload-file .filename.alert { word-wrap: break-word; overflow: visible; -} \ No newline at end of file +} From ead236e66ca986beaba50b6a50093ba551a5d283 Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Thu, 16 Apr 2020 21:01:22 +0200 Subject: [PATCH 05/10] Readme --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a7d361f..c3e7588 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # jQuery-FileUpload -[![Latest stable](https://img.shields.io/packagist/v/jzechy/jquery-fileupload.svg?style=flat-square)](https://packagist.org/packages/jzechy/jquery-fileupload) -[![license](https://img.shields.io/github/license/jzechy/jquery-fileupload.svg?maxAge=2592000&style=flat-square)](https://github.com/JZechy/jQuery-FileUpload/blob/master/LICENSE) -[![Downloads Total](https://img.shields.io/packagist/dt/jzechy/jquery-fileupload.svg?style=flat-square)](https://packagist.org/packages/jzechy/jquery-fileupload) -[![Open Issues](https://img.shields.io/github/issues/jzechy/jquery-fileupload.svg?style=flat-square)](https://github.com/JZechy/jquery-fileupload/issues) +[![Latest stable](https://img.shields.io/packagist/v/ijvo/jquery-fileupload.svg?style=flat-square)](https://packagist.org/packages/ijvo/jquery-fileupload) +[![license](https://img.shields.io/github/license/ijvo/jquery-fileupload.svg?maxAge=2592000&style=flat-square)](https://github.com/JZechy/jQuery-FileUpload/blob/master/LICENSE) +[![Downloads Total](https://img.shields.io/packagist/dt/ijvo/jquery-fileupload.svg?style=flat-square)](https://packagist.org/packages/ijvo/jquery-fileupload) +[![Open Issues](https://img.shields.io/github/issues/ijvo/jquery-fileupload.svg?style=flat-square)](https://github.com/JZechy/jquery-fileupload/issues) jQuery-FileUpload je komponenta, fungující jako rozšíření UploadControl v Nette formuláři, která pro nahrávání souborů využívá [blueimp/jQuery-File-Upload](https://github.com/blueimp/jQuery-File-Upload). @@ -11,7 +11,7 @@ Komponenta nabízí možnost [vlastního uživatelského rozhraní](https://gith ## Composer ``` -composer require jzechy/jquery-fileupload +composer require ijvo/jquery-fileupload ``` ## Odkazy From 3faef7bdcf202adc5907ba4a55a5b45ad76cd21a Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Fri, 19 Jun 2020 00:34:09 +0200 Subject: [PATCH 06/10] Model\UploadControl - Nette\Http\Request::getQuery() parameter $default is deprecated --- src/Model/UploadController.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Model/UploadController.php b/src/Model/UploadController.php index d4c4572..73d282f 100644 --- a/src/Model/UploadController.php +++ b/src/Model/UploadController.php @@ -191,9 +191,10 @@ public function handleRemove(): void { $id = $this->request->getQuery('id'); $token = $this->request->getQuery('token'); - $default = $this->request->getQuery('default', 0); + //$default = $this->request->getQuery('default', 0); + $default = $this->request->getQuery('default'); - if ($default == 0) { + if ($default == null) { $cache = $this->uploadControl->getCache(); /** @noinspection PhpInternalEntityUsedInspection */ $cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token)); From 17e77c2c92817d80dc20d498554280166f6fab43 Mon Sep 17 00:00:00 2001 From: Jaroslav Vaculik -IJVo Date: Tue, 15 Sep 2020 13:41:11 +0200 Subject: [PATCH 07/10] BaseFilter.php -implode() --- phpstan.neon | 5 +++++ src/Filter/BaseFilter.php | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 phpstan.neon diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..9a4606f --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,5 @@ +includes: + - c:\Wamp\NetteTools\phpstan\vendor\phpstan\phpstan-nette\extension.neon + - c:\Wamp\NetteTools\phpstan\vendor\phpstan\phpstan-nette\rules.neon + +parameters: \ No newline at end of file diff --git a/src/Filter/BaseFilter.php b/src/Filter/BaseFilter.php index 51137ba..2bde84f 100644 --- a/src/Filter/BaseFilter.php +++ b/src/Filter/BaseFilter.php @@ -35,7 +35,7 @@ abstract protected function getMimeTypes(); */ public function checkType(\Nette\Http\FileUpload $file) { - if (\Nette\Utils\Arrays::searchKey($this->getMimeTypes(), $file->getContentType()) !== false) { + if (\Nette\Utils\Arrays::searchKey($this->getMimeTypes(), $file->getContentType()) !== null) { return true; } else { // Pokud se nepodaří ověřit mimetype, ověříme alespoň koncovku. @@ -55,7 +55,7 @@ public function checkType(\Nette\Http\FileUpload $file) */ public function getAllowedTypes() { - return implode(array_unique($this->getMimeTypes()), ', '); + return implode(', ', array_unique($this->getMimeTypes())); } From e98d2e872d98a00a78be5349f2589541f00d941b Mon Sep 17 00:00:00 2001 From: "Ing. Jaroslav Vaculik, IJVo" Date: Sat, 17 Dec 2022 19:03:33 +0100 Subject: [PATCH 08/10] js.latte -escapeJs, SetMaxFileSize type params --- .gitignore | 2 +- src/FileUploadControl.php | 4 ++-- src/Template/js.latte | 26 +++++++++++++------------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index 5973cc2..0bfe817 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ - +vendor/* composer.lock diff --git a/src/FileUploadControl.php b/src/FileUploadControl.php index 0fddb5d..cd42da4 100644 --- a/src/FileUploadControl.php +++ b/src/FileUploadControl.php @@ -353,10 +353,10 @@ public function getMaxFileSize(): int /** - * @param int $maxFileSize + * @param string $maxFileSize * @return $this */ - public function setMaxFileSize(int $maxFileSize): self + public function setMaxFileSize(string $maxFileSize): self { $this->maxFileSize = $this->parseIniSize($maxFileSize); diff --git a/src/Template/js.latte b/src/Template/js.latte index bd4c920..1510b71 100644 --- a/src/Template/js.latte +++ b/src/Template/js.latte @@ -7,63 +7,63 @@ * Adresa pro zpracování nahrávání souborů. * @type string */ - var uploadUrl = {$uploadUrl|escapeJS|noescape}; + var uploadUrl = {$uploadUrl|escapeJs|noescape}; /** * HTML ID elementu. * @type string */ - var input = {$inputId|escapeJS|noescape}; + var input = {$inputId|escapeJs|noescape}; /** * Jedná se o vývojovou verzi? * @type boolean */ - var productionMode = {$productionMode|escapeJS|noescape}; + var productionMode = {$productionMode|escapeJs|noescape}; /** * Identifikační token. * @type string */ - var token = {$token|escapeJS|noescape}; + var token = {$token|escapeJs|noescape}; /** * Maximální počet souborů. * @type number */ - var maxFiles = {$maxFiles|escapeJS|noescape}; + var maxFiles = {$maxFiles|escapeJs|noescape}; /** * Maximální velikosti souboru. * @type number */ - var maxFileSize = {$maxFileSize|escapeJS|noescape}; + var maxFileSize = {$maxFileSize|escapeJs|noescape}; /** * Velikost souboru vyjádřena stylem např. 3MB. * @type String */ - var fileSizeString = {$fileSizeString|escapeJS|noescape}; + var fileSizeString = {$fileSizeString|escapeJs|noescape}; /** * Pole vlastních parametrů. */ - var params = {$params|escapeJS|noescape}; + var params = {$params|escapeJs|noescape}; /** * Seznam nadefinovaných komponent. */ - var components = {$components|escapeJS|noescape}; + var components = {$components|escapeJs|noescape}; /** * Odkaz pro smazání souboru. */ - var removeLink = {$removeLink|escapeJS|noescape}; + var removeLink = {$removeLink|escapeJs|noescape}; /** * Seznam výchozích souborů. */ - var defaultFiles = {$defaultFiles|escapeJS|noescape}; + var defaultFiles = {$defaultFiles|escapeJs|noescape}; /** * Konfigurace controlleru. @@ -79,7 +79,7 @@ /** * Zprávy pro chybová hlášení. */ - var messages = {$messages|escapeJS|noescape}; + var messages = {$messages|escapeJs|noescape}; /** * JS Renderer. @@ -109,7 +109,7 @@ "url": uploadUrl, "dataType": "json", {foreach $settings as $name => $value} - {$name}: {$value|escapeJS|noescape}, + {$name}: {$value|escapeJs|noescape}, {/foreach} // Přidání nového souboru. From 8579807a98a74a4644eed0186976ea8c31bad27d Mon Sep 17 00:00:00 2001 From: "Ing. Jaroslav Vaculik, IJVo" Date: Sat, 17 Dec 2022 19:09:24 +0100 Subject: [PATCH 09/10] latte 3.0+, php 8+ --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 0d35d26..b53ee0a 100644 --- a/composer.json +++ b/composer.json @@ -15,13 +15,13 @@ } ], "require": { - "php": ">=7.2.0", + "php": ">=8.0 <8.2", "nette/forms": "^3.0", "nette/http": "^3.0", "nette/utils": "^3.0", "nette/di": "^3.0", "nette/application": "^3.0", - "latte/latte": "^2.5" + "latte/latte": "^3.0" }, "autoload": { "classmap": ["src/"] From a67e1712921e3e9546bc646d186d4523db7ca41d Mon Sep 17 00:00:00 2001 From: MikKuba Date: Thu, 17 Aug 2023 13:53:08 +0200 Subject: [PATCH 10/10] Update FileUploadExtension.php FIX depracted notice for PHP 8+ --- src/FileUploadExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/FileUploadExtension.php b/src/FileUploadExtension.php index 683da11..337814d 100644 --- a/src/FileUploadExtension.php +++ b/src/FileUploadExtension.php @@ -87,7 +87,7 @@ public function getConfigSchema(): Schema */ public function afterCompile(\Nette\PhpGenerator\ClassType $class): void { - $init = $class->methods['initialize']; + $init = $class->getMethods()['initialize']; $init->addBody('\Zet\FileUpload\FileUploadControl::register($this->getService(?), ?);', [ // $this->getContainerBuilder()->getByType('\Nette\DI\Container'), $this->configuration,