commit_id
string
repo
string
commit_message
string
diff
string
label
int64
d0cdf7a9f08ded7fcf1bc05fe44e7d25031c42e4
1up-lab/OneupUploaderBundle
Merge branch 'release-1.0' of github.com:mitom/OneupUploaderBundle into mitom-release-1.0 Conflicts: EventListener/AllowedExtensionValidationListener.php EventListener/DisallowedExtensionValidationListener.php
commit d0cdf7a9f08ded7fcf1bc05fe44e7d25031c42e4 (from 48b19bc18fb944fe8b05a70173bff94074b8f83b) Merge: 48b19bc 147388f Author: Jim Schmid <[email protected]> Date: Mon Oct 14 21:17:41 2013 +0200 Merge branch 'release-1.0' of github.com:mitom/OneupUploaderBundle into mitom-release-1.0 Conflicts: EventListener/AllowedExtensionValidationListener.php EventListener/DisallowedExtensionValidationListener.php diff --git a/.travis.yml b/.travis.yml index 0acf73b..fc9e984 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,6 @@ php: - 5.4 env: - - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 7f930d4..2e803bb 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -48,19 +48,21 @@ abstract class AbstractChunkedController extends AbstractController $request = $this->container->get('request'); $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); - // reset uploaded to always have a return value - $uploaded = null; - // get information about this chunked request list($last, $uuid, $index, $orig) = $this->parseChunkedRequest($request); $chunk = $chunkManager->addChunk($uuid, $index, $file, $orig); - $this->dispatchChunkEvents($chunk, $response, $request, $last); + if ($chunk) { + $this->dispatchChunkEvents($chunk, $response, $request, $last); + } if ($chunkManager->getLoadDistribution()) { $chunks = $chunkManager->getChunks($uuid); $assembled = $chunkManager->assembleChunks($chunks, true, $last); + if (!$chunk) { + $this->dispatchChunkEvents($assembled, $response, $request, $last); + } } // if all chunks collected and stored, proceed @@ -73,9 +75,7 @@ abstract class AbstractChunkedController extends AbstractController $path = $assembled->getPath(); - // create a temporary uploaded file to meet the interface restrictions - $uploadedFile = new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, $assembled->getSize(), null, true); - $uploaded = $this->handleUpload($uploadedFile, $response, $request); + $this->handleUpload($assembled, $response, $request); $chunkManager->cleanup($path); } diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 04397d2..03e14cb 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -2,9 +2,10 @@ namespace Oneup\UploaderBundle\Controller; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\FileBag; @@ -99,12 +100,18 @@ abstract class AbstractController * * Note: The return value differs when * - * @param UploadedFile The file to upload + * @param The file to upload * @param response A response object. * @param request The request object. */ - protected function handleUpload(UploadedFile $file, ResponseInterface $response, Request $request) + protected function handleUpload($file, ResponseInterface $response, Request $request) { + // wrap the file if it is not done yet which can only happen + // if it wasn't a chunked upload, in which case it is definitely + // on the local filesystem. + if (!($file instanceof FileInterface)) { + $file = new FilesystemFile($file); + } $this->validate($file); $this->dispatchPreUploadEvent($file, $response, $request); @@ -126,7 +133,7 @@ abstract class AbstractController * @param response A response object. * @param request The request object. */ - protected function dispatchPreUploadEvent(UploadedFile $uploaded, ResponseInterface $response, Request $request) + protected function dispatchPreUploadEvent(FileInterface $uploaded, ResponseInterface $response, Request $request) { $dispatcher = $this->container->get('event_dispatcher'); @@ -161,7 +168,7 @@ abstract class AbstractController } } - protected function validate(UploadedFile $file) + protected function validate(FileInterface $file) { $dispatcher = $this->container->get('event_dispatcher'); $event = new ValidationEvent($file, $this->container->get('request'), $this->config, $this->type); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 3ebfbec..a9efae7 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -18,7 +18,20 @@ class Configuration implements ConfigurationInterface ->addDefaultsIfNotSet() ->children() ->scalarNode('maxage')->defaultValue(604800)->end() - ->scalarNode('directory')->defaultNull()->end() + ->arrayNode('storage') + ->addDefaultsIfNotSet() + ->children() + ->enumNode('type') + ->values(array('filesystem', 'gaufrette')) + ->defaultValue('filesystem') + ->end() + ->scalarNode('filesystem')->defaultNull()->end() + ->scalarNode('directory')->defaultNull()->end() + ->scalarNode('stream_wrapper')->defaultNull()->end() + ->scalarNode('sync_buffer_size')->defaultValue('100K')->end() + ->scalarNode('prefix')->defaultValue('chunks')->end() + ->end() + ->end() ->booleanNode('load_distribution')->defaultTrue()->end() ->end() ->end() @@ -56,6 +69,7 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('directory')->defaultNull()->end() + ->scalarNode('stream_wrapper')->defaultNull()->end() ->scalarNode('sync_buffer_size')->defaultValue('100K')->end() ->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index fae9056..c017bdc 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -13,11 +13,14 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { protected $storageServices = array(); + protected $container; + protected $config; public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); - $config = $this->processConfiguration($configuration, $configs); + $this->config = $this->processConfiguration($configuration, $configs); + $this->container = $container; $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); @@ -25,133 +28,216 @@ class OneupUploaderExtension extends Extension $loader->load('validators.xml'); $loader->load('errorhandler.xml'); - if ($config['twig']) { + if ($this->config['twig']) { $loader->load('twig.xml'); } - $config['chunks']['directory'] = is_null($config['chunks']['directory']) ? - sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')) : - $this->normalizePath($config['chunks']['directory']) + $this->createChunkStorageService(); + $this->processOrphanageConfig(); + + $container->setParameter('oneup_uploader.chunks', $this->config['chunks']); + $container->setParameter('oneup_uploader.orphanage', $this->config['orphanage']); + + $controllers = array(); + + // handle mappings + foreach ($this->config['mappings'] as $key => $mapping) { + $controllers[$key] = $this->processMapping($key, $mapping); + } + + $container->setParameter('oneup_uploader.controllers', $controllers); + } + + protected function processOrphanageConfig() + { + if ($this->config['chunks']['storage']['type'] === 'filesystem') { + $defaultDir = sprintf('%s/uploader/orphanage', $this->container->getParameter('kernel.cache_dir')); + } else { + $defaultDir = 'orphanage'; + } + + $this->config['orphanage']['directory'] = is_null($this->config['orphanage']['directory']) ? $defaultDir: + $this->normalizePath($this->config['orphanage']['directory']) ; + } - $config['orphanage']['directory'] = is_null($config['orphanage']['directory']) ? - sprintf('%s/uploader/orphanage', $container->getParameter('kernel.cache_dir')) : - $this->normalizePath($config['orphanage']['directory']) + protected function processMapping($key, &$mapping) + { + $mapping['max_size'] = $mapping['max_size'] < 0 ? + $this->getMaxUploadSize($mapping['max_size']) : + $mapping['max_size'] ; + $controllerName = $this->createController($key, $mapping); - $container->setParameter('oneup_uploader.chunks', $config['chunks']); - $container->setParameter('oneup_uploader.orphanage', $config['orphanage']); + $this->verifyPhpVersion($mapping); - $controllers = array(); + return array($controllerName, array( + 'enable_progress' => $mapping['enable_progress'], + 'enable_cancelation' => $mapping['enable_cancelation'] + )); + } - // handle mappings - foreach ($config['mappings'] as $key => $mapping) { - $mapping['max_size'] = $mapping['max_size'] < 0 ? - $this->getMaxUploadSize($mapping['max_size']) : - $mapping['max_size'] - ; + protected function createController($key, $config) + { + // create the storage service according to the configuration + $storageService = $this->createStorageService($config['storage'], $key, $config['use_orphanage']); - // create the storage service according to the configuration - $storageService = null; - - // if a service is given, return a reference to this service - // this allows a user to overwrite the storage layer if needed - if (!is_null($mapping['storage']['service'])) { - $storageService = new Reference($mapping['storage']['service']); - } else { - // no service was given, so we create one - $storageName = sprintf('oneup_uploader.storage.%s', $key); - - if ($mapping['storage']['type'] == 'filesystem') { - $mapping['storage']['directory'] = is_null($mapping['storage']['directory']) ? - sprintf('%s/../web/uploads/%s', $container->getParameter('kernel.root_dir'), $key) : - $this->normalizePath($mapping['storage']['directory']) - ; - - $container - ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $mapping['storage']['type'])) - ->addArgument($mapping['storage']['directory']) - ; - } - - if ($mapping['storage']['type'] == 'gaufrette') { - if(!class_exists('Gaufrette\\Filesystem')) - throw new InvalidArgumentException('You have to install Gaufrette in order to use it as a storage service.'); - - if(strlen($mapping['storage']['filesystem']) <= 0) - throw new ServiceNotFoundException('Empty service name'); - - $container - ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $mapping['storage']['type'])) - ->addArgument(new Reference($mapping['storage']['filesystem'])) - ->addArgument($this->getValueInBytes($mapping['storage']['sync_buffer_size'])) - ; - } - - $storageService = new Reference($storageName); - - if ($mapping['use_orphanage']) { - $orphanageName = sprintf('oneup_uploader.orphanage.%s', $key); - - // this mapping wants to use the orphanage, so create - // a masked filesystem for the controller - $container - ->register($orphanageName, '%oneup_uploader.orphanage.class%') - ->addArgument($storageService) - ->addArgument(new Reference('session')) - ->addArgument($config['orphanage']) - ->addArgument($key) - ; - - // switch storage of mapping to orphanage - $storageService = new Reference($orphanageName); - } - } + if ($config['frontend'] != 'custom') { + $controllerName = sprintf('oneup_uploader.controller.%s', $key); + $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $config['frontend']); + } else { + $customFrontend = $config['custom_frontend']; - if ($mapping['frontend'] != 'custom') { - $controllerName = sprintf('oneup_uploader.controller.%s', $key); - $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $mapping['frontend']); - } else { - $customFrontend = $mapping['custom_frontend']; + $controllerName = sprintf('oneup_uploader.controller.%s', $customFrontend['name']); + $controllerType = $customFrontend['class']; - $controllerName = sprintf('oneup_uploader.controller.%s', $customFrontend['name']); - $controllerType = $customFrontend['class']; + if(empty($controllerName) || empty($controllerType)) + throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); + } - if(empty($controllerName) || empty($controllerType)) - throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); - } + $errorHandler = $this->createErrorHandler($config); + + // create controllers based on mapping + $this->container + ->register($controllerName, $controllerType) + + ->addArgument(new Reference('service_container')) + ->addArgument($storageService) + ->addArgument($errorHandler) + ->addArgument($config) + ->addArgument($key) + + ->addTag('oneup_uploader.routable', array('type' => $key)) + ->setScope('request') + ; + + return $controllerName; + } + + protected function createErrorHandler($config) + { + return is_null($config['error_handler']) ? + new Reference('oneup_uploader.error_handler.'.$config['frontend']) : + new Reference($config['error_handler']); + } - $errorHandler = is_null($mapping['error_handler']) ? - new Reference('oneup_uploader.error_handler.'.$mapping['frontend']) : - new Reference($mapping['error_handler']); + protected function verifyPhpVersion($config) + { + if ($config['enable_progress'] || $config['enable_cancelation']) { + if (strnatcmp(phpversion(), '5.4.0') < 0) { + throw new InvalidArgumentException('You need to run PHP version 5.4.0 or above to use the progress/cancelation feature.'); + } + } + } - // create controllers based on mapping - $container - ->register($controllerName, $controllerType) + protected function createChunkStorageService() + { + $config = &$this->config['chunks']['storage']; - ->addArgument(new Reference('service_container')) - ->addArgument($storageService) - ->addArgument($errorHandler) - ->addArgument($mapping) - ->addArgument($key) + $storageClass = sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type']); + if ($config['type'] === 'filesystem') { + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : + $this->normalizePath($config['directory']) + ; - ->addTag('oneup_uploader.routable', array('type' => $key)) - ->setScope('request') + $this->container + ->register('oneup_uploader.chunks_storage', sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type'])) + ->addArgument($config['directory']) ; + } else { + $this->registerGaufretteStorage( + 'oneup_uploader.chunks_storage', + $storageClass, $config['filesystem'], + $config['sync_buffer_size'], + $config['stream_wrapper'], + $config['prefix'] + ); + + $this->container->setParameter('oneup_uploader.orphanage.class', 'Oneup\UploaderBundle\Uploader\Storage\GaufretteOrphanageStorage'); + + // enforce load distribution when using gaufrette as chunk + // torage to avoid moving files forth-and-back + $this->config['chunks']['load_distribution'] = true; + } + } - if ($mapping['enable_progress'] || $mapping['enable_cancelation']) { - if (strnatcmp(phpversion(), '5.4.0') < 0) { - throw new InvalidArgumentException('You need to run PHP version 5.4.0 or above to use the progress/cancelation feature.'); - } + protected function createStorageService(&$config, $key, $orphanage = false) + { + $storageService = null; + + // if a service is given, return a reference to this service + // this allows a user to overwrite the storage layer if needed + if (!is_null($config['service'])) { + $storageService = new Reference($config['storage']['service']); + } else { + // no service was given, so we create one + $storageName = sprintf('oneup_uploader.storage.%s', $key); + $storageClass = sprintf('%%oneup_uploader.storage.%s.class%%', $config['type']); + + if ($config['type'] == 'filesystem') { + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : + $this->normalizePath($config['directory']) + ; + + $this->container + ->register($storageName, $storageClass) + ->addArgument($config['directory']) + ; } - $controllers[$key] = array($controllerName, array( - 'enable_progress' => $mapping['enable_progress'], - 'enable_cancelation' => $mapping['enable_cancelation'] - )); + if ($config['type'] == 'gaufrette') { + $this->registerGaufretteStorage( + $storageName, + $storageClass, + $config['filesystem'], + $config['sync_buffer_size'], + $config['stream_wrapper'] + ); + } + + $storageService = new Reference($storageName); + + if ($orphanage) { + $orphanageName = sprintf('oneup_uploader.orphanage.%s', $key); + + // this mapping wants to use the orphanage, so create + // a masked filesystem for the controller + $this->container + ->register($orphanageName, '%oneup_uploader.orphanage.class%') + ->addArgument($storageService) + ->addArgument(new Reference('session')) + ->addArgument(new Reference('oneup_uploader.chunks_storage')) + ->addArgument($this->config['orphanage']) + ->addArgument($key) + ; + + // switch storage of mapping to orphanage + $storageService = new Reference($orphanageName); + } } - $container->setParameter('oneup_uploader.controllers', $controllers); + return $storageService; + } + + protected function registerGaufretteStorage($key, $class, $filesystem, $buffer, $streamWrapper = null, $prefix = '') + { + if(!class_exists('Gaufrette\\Filesystem')) + throw new InvalidArgumentException('You have to install Gaufrette in order to use it as a chunk storage service.'); + + if(strlen($filesystem) <= 0) + throw new ServiceNotFoundException('Empty service name'); + + $streamWrapper = $this->normalizeStreamWrapper($streamWrapper); + + $this->container + ->register($key, $class) + ->addArgument(new Reference($filesystem)) + ->addArgument($this->getValueInBytes($buffer)) + ->addArgument($streamWrapper) + ->addArgument($prefix) + ; } protected function getMaxUploadSize($input) @@ -182,4 +268,13 @@ class OneupUploaderExtension extends Extension { return rtrim($input, '/'); } + + protected function normalizeStreamWrapper($input) + { + if (is_null($input)) { + return null; + } + + return rtrim($input, '/') . '/'; + } } diff --git a/Event/ValidationEvent.php b/Event/ValidationEvent.php index 8110b78..15e1c18 100644 --- a/Event/ValidationEvent.php +++ b/Event/ValidationEvent.php @@ -2,8 +2,8 @@ namespace Oneup\UploaderBundle\Event; +use Oneup\UploaderBundle\Uploader\File\FileInterface; use Symfony\Component\EventDispatcher\Event; -use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; class ValidationEvent extends Event @@ -13,7 +13,7 @@ class ValidationEvent extends Event protected $type; protected $request; - public function __construct(UploadedFile $file, Request $request, array $config, $type) + public function __construct(FileInterface $file, Request $request, array $config, $type) { $this->file = $file; $this->config = $config; diff --git a/EventListener/AllowedMimetypeValidationListener.php b/EventListener/AllowedMimetypeValidationListener.php index 195f6bd..66aa7b9 100644 --- a/EventListener/AllowedMimetypeValidationListener.php +++ b/EventListener/AllowedMimetypeValidationListener.php @@ -16,8 +16,7 @@ class AllowedMimetypeValidationListener return; } - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $mimetype = finfo_file($finfo, $file->getRealpath()); + $mimetype = $file->getMimeType(); if (!in_array($mimetype, $config['allowed_mimetypes'])) { throw new ValidationException('error.whitelist'); diff --git a/EventListener/DisallowedMimetypeValidationListener.php b/EventListener/DisallowedMimetypeValidationListener.php index 452eff6..c5ace44 100644 --- a/EventListener/DisallowedMimetypeValidationListener.php +++ b/EventListener/DisallowedMimetypeValidationListener.php @@ -16,8 +16,7 @@ class DisallowedMimetypeValidationListener return; } - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $mimetype = finfo_file($finfo, $file->getRealpath()); + $mimetype = $file->getExtension(); if (in_array($mimetype, $config['disallowed_mimetypes'])) { throw new ValidationException('error.blacklist'); diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 39502ab..c970994 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -5,11 +5,13 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> + <parameter key="oneup_uploader.chunks_storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage</parameter> + <parameter key="oneup_uploader.chunks_storage.filesystem.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> <parameter key="oneup_uploader.storage.filesystem.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage</parameter> - <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\OrphanageStorage</parameter> + <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemOrphanageStorage</parameter> <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> <parameter key="oneup_uploader.controller.fineuploader.class">Oneup\UploaderBundle\Controller\FineUploaderController</parameter> <parameter key="oneup_uploader.controller.blueimp.class">Oneup\UploaderBundle\Controller\BlueimpController</parameter> @@ -26,6 +28,7 @@ <!-- managers --> <service id="oneup_uploader.chunk_manager" class="%oneup_uploader.chunks.manager.class%"> <argument>%oneup_uploader.chunks%</argument> + <argument type="service" id="oneup_uploader.chunks_storage" /> </service> <service id="oneup_uploader.orphanage_manager" class="%oneup_uploader.orphanage.manager.class%"> diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index 4f5c5e1..fd6d87a 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -31,11 +31,53 @@ You can configure the `ChunkManager` by using the following configuration parame oneup_uploader: chunks: maxage: 86400 - directory: %kernel.cache_dir%/uploader/chunks + storage: + directory: %kernel.cache_dir%/uploader/chunks ``` You can choose a custom directory to save the chunks temporarily while uploading by changing the parameter `directory`. +## Use Gaufrette to store chunk files + +You can also use a Gaufrette filesystem as the chunk storage. A possible use case is to use chunked uploads behind non-session sticky load balancers. +To do this you must first set up [Gaufrette](gaufrette_storage.md). There are however some additional things to keep in mind. +The configuration for the Gaufrette chunk storage should look as the following: + +```yaml +oneup_uploader: + chunks: + maxage: 86400 + storage: + type: gaufrette + filesystem: gaufrette.gallery_filesystem + prefix: 'chunks' + stream_wrapper: 'gaufrette://gallery/' +``` + +> :exclamation: Setting the `stream_wrapper` is heavily recommended for better performance, see the reasons in the [gaufrette configuration](gaufrette_storage.md#configure-your-mappings) + +As you can see there are is an option, `prefix`. It represents the directory + *relative* to the filesystem's directory which the chunks are stored in. +Gaufrette won't allow it to be outside of the filesystem. +This will give you a better structured directory, +as the chunk's folders and the uploaded files won't mix with each other. +You can set it to an empty string (`''`), if you don't need it. Otherwise it defaults to `chunks`. + +> :exclamation: You can only use stream capable filesystems for the chunk storage, at the time of this writing +only the Local filesystem is capable of streaming directly. + +The chunks will be read directly from the temporary directory and appended to the already existing part on the given filesystem, +resulting in only one single read and one single write operation. + +> :exclamation: Do not use a Gaufrette filesystem for the chunk storage and a local filesystem for the mapping. This is not possible to check during container setup and will throw unexpected errors at runtime! + +You can achieve the biggest improvement if you use the same filesystem as your storage. If you do so, the assembled +file only has to be moved out of the chunk directory, which takes no time on a local filesystem. + +> The load distribution is forcefully turned on, if you use Gaufrette as the chunk storage. + +See the [Use Chunked Uploads behind Load Balancers](load_balancers.md) section in the documentation for a full configuration example. + ## Clean up The ChunkManager can be forced to clean up old and orphanaged chunks by using the command provided by the OneupUploaderBundle. diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 07c420b..dcc5a20 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -7,7 +7,13 @@ All available configuration options along with their default values are listed b oneup_uploader: chunks: maxage: 604800 - directory: ~ + storage: + type: filesystem + directory: ~ + filesystem: ~ + sync_buffer_size: 100K + stream_wrapper: ~ + prefix: 'chunks' load_distribution: true orphanage: maxage: 604800 @@ -26,6 +32,7 @@ oneup_uploader: type: filesystem filesystem: ~ directory: ~ + stream_wrapper: ~ sync_buffer_size: 100K allowed_mimetypes: [] disallowed_mimetypes: [] diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index 4aaeabc..9b59e58 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -12,19 +12,19 @@ First, create a custom namer which implements ```Oneup\UploaderBundle\Uploader\N namespace Acme\DemoBundle; -use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; class CatNamer implements NamerInterface { - public function name(UploadedFile $file) + public function name(FileInterface $file) { return 'grumpycat.jpg'; } } ``` -To match the `NamerInterface` you have to implement the function `name()` which expects an `UploadedFile` and should return a string representing the name of the given file. The example above would name every file _grumpycat.jpg_ and is therefore not very useful. +To match the `NamerInterface` you have to implement the function `name()` which expects an `FileInterface` and should return a string representing the name of the given file. The example above would name every file _grumpycat.jpg_ and is therefore not very useful. Next, register your created namer as a service in your `services.xml` diff --git a/Resources/doc/gaufrette_storage.md b/Resources/doc/gaufrette_storage.md index 6c93347..2e74a3c 100644 --- a/Resources/doc/gaufrette_storage.md +++ b/Resources/doc/gaufrette_storage.md @@ -53,7 +53,7 @@ knp_gaufrette: local: directory: %kernel.root_dir%/../web/uploads create: true - + filesystems: gallery: adapter: gallery @@ -71,7 +71,7 @@ oneup_uploader: gallery: storage: type: gaufrette - filesystem: gaufrette.gallery_filesystem + filesystem: gaufrette.gallery_filesystem ``` You can specify the buffer size used for syncing files from your filesystem to the gaufrette storage by changing the property `sync_buffer_size`. @@ -84,7 +84,31 @@ oneup_uploader: gallery: storage: type: gaufrette - filesystem: gaufrette.gallery_filesystem + filesystem: gaufrette.gallery_filesystem sync_buffer_size: 1M ``` +You may also specify the stream wrapper protocol for your filesystem: +```yml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + storage: + type: gaufrette + filesystem: gaufrette.gallery_filesystem + stream_wrapper: gaufrette://gallery/ +``` + +> This is only useful if you are using a stream-capable adapter. At the time of this writing, only +the local adapter is capable of streaming directly. + +The first part (`gaufrette`) in the example above `MUST` be the same as `knp_gaufrette.stream_wrapper.protocol`, +the second part (`gallery`) in the example, `MUST` be the key of the filesytem (`knp_gaufette.filesystems.key`). +It also must end with a slash (`/`). + +This is particularly useful if you want to get exact informations about your files. Gaufrette offers you every functionality +to do this without relying on the stream wrapper, however it will have to download the file and load it into memory +to operate on it. If `stream_wrapper` is specified, the bundle will try to open the file as streams when such operation +is requested. (e.g. getting the size of the file, the mime-type based on content) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index fe69b15..430fc08 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -124,6 +124,7 @@ some more advanced features. * [Validate your uploads](custom_validator.md) * [General/Generic Events](events.md) * [Enable Session upload progress / upload cancelation](progress.md) +* [Use Chunked Uploads behind Load Balancers](load_balancers.md) * [Configuration Reference](configuration_reference.md) * [Testing this bundle](testing.md) diff --git a/Resources/doc/load_balancers.md b/Resources/doc/load_balancers.md new file mode 100644 index 0000000..c178600 --- /dev/null +++ b/Resources/doc/load_balancers.md @@ -0,0 +1,41 @@ +Use Chunked Uploads behind Load Balancers +========================================= + +If you want to use Chunked Uploads behind load balancers that is not configured to use sticky sessions you'll eventually end up with a bunch of chunks on every instance and the bundle is not able to reassemble the file on the server. + +You can avoid this problem by using Gaufrette as an abstract filesystem. Check the following configuration as an example. + +```yaml +knp_gaufrette: + adapters: + gallery: + local: + directory: %kernel.root_dir%/../web/uploads + create: true + + filesystems: + gallery: + adapter: gallery + + stream_wrapper: ~ + +oneup_uploader: + chunks: + storage: + type: gaufrette + filesystem: gaufrette.gallery_filesystem + stream_wrapper: gaufrette://gallery/ + + mappings: + gallery: + frontend: fineuploader + storage: + type: gaufrette + filesystem: gaufrette.gallery_filesystem +``` + +> :exclamation: Event though it is possible to use two different Gaufrette filesystems - one for the the chunk storage - and one for the mapping, it is not recommended. + +> :exclamation: Do not use a Gaufrette filesystem for the chunk storage and a local filesystem one for the mapping. This is not possible to check during configuration and will throw unexpected errors! + +Using Gaufrette filesystems for chunked upload directories has some limitations. It is highly recommended to use a `Local` Gaufrette adapter as it is the only one that is able to `rename` a file but `move` it. Especially when working with bigger files this can have serious perfomance advantages as this way the file doesn't have to be moved entirely to memory! \ No newline at end of file diff --git a/Resources/doc/orphanage.md b/Resources/doc/orphanage.md index 59478cd..b4051a2 100644 --- a/Resources/doc/orphanage.md +++ b/Resources/doc/orphanage.md @@ -67,6 +67,12 @@ oneup_uploader: You can choose a custom directory to save the orphans temporarily while uploading by changing the parameter `directory`. +If you are using a gaufrette filesystem as the chunk storage, the ```directory``` specified above should be +relative to the filesystem's root directory. It will detect if you are using a gaufrette chunk storage +and default to ```orphanage```. + +> The orphanage and the chunk storage are forced to be on the same filesystem. + ## Clean up The `OrphanageManager` can be forced to clean up orphans by using the command provided by the OneupUploaderBundle. @@ -79,4 +85,4 @@ The `Orphanage` will save uploaded files in a directory like the following: %kernel.cache_dir%/uploader/orphanage/{session_id}/uploaded_file.ext -It is currently not possible to change the part after `%kernel.cache_dir%/uploader/orphanage` dynamically. This has some implications. If a user will upload files through your `gallery` mapping, and choose not to submit the form, but instead start over with a new form handled by the `gallery` mapping, the newly uploaded files are going to be moved in the same directory. Therefore you will get both the files uploaded the first time and the second time if you trigger the `uploadFiles` method. \ No newline at end of file +It is currently not possible to change the part after `%kernel.cache_dir%/uploader/orphanage` dynamically. This has some implications. If a user will upload files through your `gallery` mapping, and choose not to submit the form, but instead start over with a new form handled by the `gallery` mapping, the newly uploaded files are going to be moved in the same directory. Therefore you will get both the files uploaded the first time and the second time if you trigger the `uploadFiles` method. diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 8b56bfb..77a5bac 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -34,7 +34,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest // event data $validationCount = 0; - $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + $dispatcher->addListener(UploadEvents::VALIDATION, function() use (&$validationCount) { ++ $validationCount; }); diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index c5b8af6..2aec2f7 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -4,7 +4,6 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; -use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\UploadEvents; class BlueimpValidationTest extends AbstractValidationTest @@ -32,7 +31,7 @@ class BlueimpValidationTest extends AbstractValidationTest // event data $validationCount = 0; - $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + $dispatcher->addListener(UploadEvents::VALIDATION, function() use (&$validationCount) { ++ $validationCount; }); diff --git a/Tests/DependencyInjection/OneupUploaderExtensionTest.php b/Tests/DependencyInjection/OneupUploaderExtensionTest.php index 1b09fbf..85ac094 100644 --- a/Tests/DependencyInjection/OneupUploaderExtensionTest.php +++ b/Tests/DependencyInjection/OneupUploaderExtensionTest.php @@ -28,6 +28,28 @@ class OneupUploaderExtensionTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2147483648, $method->invoke($mock, '2G')); } + public function testNormalizationOfStreamWrapper() + { + $mock = $this->getMockBuilder('Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension') + ->disableOriginalConstructor() + ->getMock() + ; + + $method = new \ReflectionMethod( + 'Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension', + 'normalizeStreamWrapper' + ); + $method->setAccessible(true); + + $output1 = $method->invoke($mock, 'gaufrette://gallery'); + $output2 = $method->invoke($mock, 'gaufrette://gallery/'); + $output3 = $method->invoke($mock, null); + + $this->assertEquals('gaufrette://gallery/', $output1); + $this->assertEquals('gaufrette://gallery/', $output2); + $this->assertNull($output3); + } + public function testGetMaxUploadSize() { $mock = $this->getMockBuilder('Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension') diff --git a/Tests/Uploader/Chunk/ChunkManagerTest.php b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php similarity index 63% rename from Tests/Uploader/Chunk/ChunkManagerTest.php rename to Tests/Uploader/Chunk/Storage/ChunkStorageTest.php index 4ce9c4a..af1f32f 100644 --- a/Tests/Uploader/Chunk/ChunkManagerTest.php +++ b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php @@ -1,32 +1,14 @@ <?php -namespace Oneup\UploaderBundle\Tests\Uploader\Chunk; +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; -use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder; -use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; - -class ChunkManagerTest extends \PHPUnit_Framework_TestCase +abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase { protected $tmpDir; - - public function setUp() - { - // create a cache dir - $tmpDir = sprintf('/tmp/%s', uniqid()); - - $system = new Filesystem(); - $system->mkdir($tmpDir); - - $this->tmpDir = $tmpDir; - } - - public function tearDown() - { - $system = new Filesystem(); - $system->remove($this->tmpDir); - } + protected $storage; public function testExistanceOfTmpDir() { @@ -49,16 +31,15 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase { // get a manager configured with a max-age of 5 minutes $maxage = 5 * 60; - $manager = $this->getManager($maxage); $numberOfFiles = 10; $finder = new Finder(); $finder->in($this->tmpDir); $this->fillDirectory($numberOfFiles); - $this->assertCount(10, $finder); + $this->assertCount($numberOfFiles, $finder); - $manager->clear(); + $this->storage->clear($maxage); $this->assertTrue(is_dir($this->tmpDir)); $this->assertTrue(is_writeable($this->tmpDir)); @@ -75,21 +56,12 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase $filesystem = new Filesystem(); $filesystem->remove($this->tmpDir); - $manager = $this->getManager(10); - $manager->clear(); + $this->storage->clear(10); // yey, no exception $this->assertTrue(true); } - protected function getManager($maxage) - { - return new ChunkManager(array( - 'directory' => $this->tmpDir, - 'maxage' => $maxage - )); - } - protected function fillDirectory($number) { $system = new Filesystem(); diff --git a/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php b/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php new file mode 100644 index 0000000..8e54cc4 --- /dev/null +++ b/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php @@ -0,0 +1,31 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; + +use Symfony\Component\Filesystem\Filesystem; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage; + +class FilesystemStorageTest extends ChunkStorageTest +{ + protected $tmpDir; + + public function setUp() + { + // create a cache dir + $tmpDir = sprintf('/tmp/%s', uniqid()); + + $system = new Filesystem(); + $system->mkdir($tmpDir); + + $this->tmpDir = $tmpDir; + $this->storage = new FilesystemStorage(array( + 'directory' => $this->tmpDir + )); + } + + public function tearDown() + { + $system = new Filesystem(); + $system->remove($this->tmpDir); + } +} diff --git a/Tests/Uploader/Chunk/Storage/GaufretteStorageTest.php b/Tests/Uploader/Chunk/Storage/GaufretteStorageTest.php new file mode 100644 index 0000000..375d450 --- /dev/null +++ b/Tests/Uploader/Chunk/Storage/GaufretteStorageTest.php @@ -0,0 +1,43 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; + +use Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage; +use Symfony\Component\Filesystem\Filesystem; +use Gaufrette\Adapter\Local as Adapter; +use Gaufrette\Filesystem as GaufretteFilesystem; + +class GaufretteStorageTest extends ChunkStorageTest +{ + protected $parentDir; + protected $chunkKey = 'chunks'; + protected $chunkDir; + + public function setUp() + { + // create a cache dir + $parentDir = sprintf('/tmp/%s', uniqid()); + + $system = new Filesystem(); + $system->mkdir($parentDir); + + $this->parentDir = $parentDir; + + $adapter = new Adapter($this->parentDir, true); + + $filesystem = new GaufretteFilesystem($adapter); + + $this->storage = new GaufretteStorage($filesystem, 100000, null, $this->chunkKey); + $this->tmpDir = $this->parentDir.'/'.$this->chunkKey; + + $system->mkdir($this->tmpDir); + + } + + public function tearDown() + { + $system = new Filesystem(); + $system->remove($this->parentDir); + } + +} diff --git a/Tests/Uploader/File/FileTest.php b/Tests/Uploader/File/FileTest.php new file mode 100644 index 0000000..2753089 --- /dev/null +++ b/Tests/Uploader/File/FileTest.php @@ -0,0 +1,43 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\File; + +abstract class FileTest extends \PHPUnit_Framework_TestCase +{ + protected $file; + protected $pathname; + protected $path; + protected $basename; + protected $extension; + protected $size; + protected $mimeType; + + public function testGetPathName() + { + $this->assertEquals($this->pathname, $this->file->getPathname()); + } + + public function testGetPath() + { + $this->assertEquals($this->path, $this->file->getPath()); + } + + public function testGetBasename() + { + $this->assertEquals($this->basename, $this->file->getBasename()); + } + + public function testGetExtension() + { + $this->assertEquals($this->extension, $this->file->getExtension()); + } + + public function testGetSize() + { + $this->assertEquals($this->size, $this->file->getSize()); + } + + public function testGetMimeType() + { + $this->assertEquals($this->mimeType, $this->file->getMimeType()); + } +} diff --git a/Tests/Uploader/File/FilesystemFileTest.php b/Tests/Uploader/File/FilesystemFileTest.php new file mode 100644 index 0000000..0868cb9 --- /dev/null +++ b/Tests/Uploader/File/FilesystemFileTest.php @@ -0,0 +1,30 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\File; + +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FilesystemFileTest extends FileTest +{ + public function setUp() + { + $this->path = sys_get_temp_dir(). '/oneup_test_tmp'; + mkdir($this->path); + + $this->basename = 'test_file.txt'; + $this->pathname = $this->path .'/'. $this->basename; + $this->extension = 'txt'; + $this->size = 9; //something = 9 bytes + $this->mimeType = 'text/plain'; + + file_put_contents($this->pathname, 'something'); + + $this->file = new FilesystemFile(new UploadedFile($this->pathname, 'test_file.txt', null, null, null, true)); + } + + public function tearDown() + { + unlink($this->pathname); + rmdir($this->path); + } +} diff --git a/Tests/Uploader/File/GaufretteFileTest.php b/Tests/Uploader/File/GaufretteFileTest.php new file mode 100644 index 0000000..fc7e2f7 --- /dev/null +++ b/Tests/Uploader/File/GaufretteFileTest.php @@ -0,0 +1,44 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\File; + +use Gaufrette\File; +use Gaufrette\StreamWrapper; +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; +use Gaufrette\Adapter\Local as Adapter; +use Gaufrette\Filesystem as GaufretteFileSystem; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; + +class GaufretteFileTest extends FileTest +{ + public function setUp() + { + $adapter = new Adapter(sys_get_temp_dir(), true); + $filesystem = new GaufretteFilesystem($adapter); + + $map = StreamWrapper::getFilesystemMap(); + $map->set('oneup', $filesystem); + + StreamWrapper::register(); + + $this->storage = new GaufretteStorage($filesystem, 100000); + + $this->path = 'oneup_test_tmp'; + mkdir(sys_get_temp_dir().'/'.$this->path); + + $this->basename = 'test_file.txt'; + $this->pathname = $this->path .'/'. $this->basename; + $this->extension = 'txt'; + $this->size = 9; //something = 9 bytes + $this->mimeType = 'text/plain'; + + file_put_contents(sys_get_temp_dir() .'/' . $this->pathname, 'something'); + + $this->file = new GaufretteFile(new File($this->pathname, $filesystem), $filesystem, 'gaufrette://oneup/'); + } + + public function tearDown() + { + unlink(sys_get_temp_dir().'/'.$this->pathname); + rmdir(sys_get_temp_dir().'/'.$this->path); + } +} diff --git a/Tests/Uploader/Naming/UniqidNamerTest.php b/Tests/Uploader/Naming/UniqidNamerTest.php index 2ff1631..d20df0a 100644 --- a/Tests/Uploader/Naming/UniqidNamerTest.php +++ b/Tests/Uploader/Naming/UniqidNamerTest.php @@ -8,14 +8,14 @@ class UniqidNamerTest extends \PHPUnit_Framework_TestCase { public function testNamerReturnsName() { - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') ->disableOriginalConstructor() ->getMock() ; $file ->expects($this->any()) - ->method('guessExtension') + ->method('getExtension') ->will($this->returnValue('jpeg')) ; @@ -25,14 +25,14 @@ class UniqidNamerTest extends \PHPUnit_Framework_TestCase public function testNamerReturnsUniqueName() { - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') ->disableOriginalConstructor() ->getMock() ; $file ->expects($this->any()) - ->method('guessExtension') + ->method('getExtension') ->will($this->returnValue('jpeg')) ; diff --git a/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php new file mode 100644 index 0000000..d647848 --- /dev/null +++ b/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php @@ -0,0 +1,52 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; + +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\Storage\FilesystemOrphanageStorage; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage as FilesystemChunkStorage; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; + +use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; + +class FilesystemOrphanageStorageTest extends OrphanageTest +{ + public function setUp() + { + $this->numberOfPayloads = 5; + $this->tempDirectory = sys_get_temp_dir() . '/orphanage'; + $this->realDirectory = sys_get_temp_dir() . '/storage'; + $this->payloads = array(); + + $filesystem = new Filesystem(); + $filesystem->mkdir($this->tempDirectory); + $filesystem->mkdir($this->realDirectory); + + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + // create temporary file + $file = tempnam(sys_get_temp_dir(), 'uploader'); + + $pointer = fopen($file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + $this->payloads[] = new FilesystemFile(new UploadedFile($file, $i . 'grumpycat.jpeg', null, null, null, true)); + } + + // create underlying storage + $this->storage = new FilesystemStorage($this->realDirectory); + // is ignored anyways + $chunkStorage = new FilesystemChunkStorage('/tmp/'); + + // create orphanage + $session = new Session(new MockArraySessionStorage()); + $session->start(); + + $config = array('directory' => $this->tempDirectory); + + $this->orphanage = new FilesystemOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat'); + } +} diff --git a/Tests/Uploader/Storage/FilesystemStorageTest.php b/Tests/Uploader/Storage/FilesystemStorageTest.php index 6f3e011..1ae9964 100644 --- a/Tests/Uploader/Storage/FilesystemStorageTest.php +++ b/Tests/Uploader/Storage/FilesystemStorageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -26,7 +27,7 @@ class FilesystemStorageTest extends \PHPUnit_Framework_TestCase public function testUpload() { - $payload = new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true); + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); $storage = new FilesystemStorage($this->directory); $storage->upload($payload, 'notsogrumpyanymore.jpeg'); diff --git a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php new file mode 100644 index 0000000..418298c --- /dev/null +++ b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php @@ -0,0 +1,118 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Gaufrette\File; +use Gaufrette\Filesystem as GaufretteFilesystem; + +use Gaufrette\Adapter\Local as Adapter; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage as GaufretteChunkStorage; + +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteOrphanageStorage; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; +use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; + +class GaufretteOrphanageStorageTest extends OrphanageTest +{ + protected $chunkDirectory; + protected $chunksKey = 'chunks'; + protected $orphanageKey = 'orphanage'; + + public function setUp() + { + $this->numberOfPayloads = 5; + $this->realDirectory = sys_get_temp_dir() . '/storage'; + $this->chunkDirectory = $this->realDirectory .'/' . $this->chunksKey; + $this->tempDirectory = $this->realDirectory . '/' . $this->orphanageKey; + $this->payloads = array(); + + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + + $filesystem = new \Symfony\Component\Filesystem\Filesystem(); + $filesystem->mkdir($this->realDirectory); + $filesystem->mkdir($this->chunkDirectory); + $filesystem->mkdir($this->tempDirectory); + + $adapter = new Adapter($this->realDirectory, true); + $filesystem = new GaufretteFilesystem($adapter); + + $this->storage = new GaufretteStorage($filesystem, 100000); + + $chunkStorage = new GaufretteChunkStorage($filesystem, 100000, null, 'chunks'); + + // create orphanage + $session = new Session(new MockArraySessionStorage()); + $session->start(); + + $config = array('directory' => 'orphanage'); + + $this->orphanage = new GaufretteOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat'); + + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + // create temporary file as if it was reassembled by the chunk manager + $file = tempnam($this->chunkDirectory, 'uploader'); + + $pointer = fopen($file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + //gaufrette needs the key relative to it's root + $fileKey = str_replace($this->realDirectory, '', $file); + + $this->payloads[] = new GaufretteFile(new File($fileKey, $filesystem), $filesystem); + } + } + + public function testUpload() + { + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + // exclude the orphanage and the chunks + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $this->assertCount(0, $finder); + } + + public function testUploadAndFetching() + { + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $this->assertCount(0, $finder); + + $files = $this->orphanage->uploadFiles(); + + $this->assertTrue(is_array($files)); + $this->assertCount($this->numberOfPayloads, $files); + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount(0, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + } + + public function checkIfTempnameMatchesAfterCreation() + { + return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + } +} diff --git a/Tests/Uploader/Storage/GaufretteStorageTest.php b/Tests/Uploader/Storage/GaufretteStorageTest.php index f9ecfe6..008e618 100644 --- a/Tests/Uploader/Storage/GaufretteStorageTest.php +++ b/Tests/Uploader/Storage/GaufretteStorageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -33,7 +34,7 @@ class GaufretteStorageTest extends \PHPUnit_Framework_TestCase public function testUpload() { - $payload = new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true); + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); $this->storage->upload($payload, 'notsogrumpyanymore.jpeg'); $finder = new Finder(); diff --git a/Tests/Uploader/Storage/OrphanageStorageTest.php b/Tests/Uploader/Storage/OrphanageTest.php similarity index 61% rename from Tests/Uploader/Storage/OrphanageStorageTest.php rename to Tests/Uploader/Storage/OrphanageTest.php index bcaf525..836ab86 100644 --- a/Tests/Uploader/Storage/OrphanageStorageTest.php +++ b/Tests/Uploader/Storage/OrphanageTest.php @@ -4,14 +4,8 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpFoundation\File\UploadedFile; -use Symfony\Component\HttpFoundation\Session\Session; -use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; -use Oneup\UploaderBundle\Uploader\Storage\OrphanageStorage; -use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; - -class OrphanageStorageTest extends \PHPUnit_Framework_TestCase +abstract class OrphanageTest extends \PHPUnit_Framework_Testcase { protected $tempDirectory; protected $realDirectory; @@ -20,40 +14,6 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase protected $payloads; protected $numberOfPayloads; - public function setUp() - { - $this->numberOfPayloads = 5; - $this->tempDirectory = sys_get_temp_dir() . '/orphanage'; - $this->realDirectory = sys_get_temp_dir() . '/storage'; - $this->payloads = array(); - - $filesystem = new Filesystem(); - $filesystem->mkdir($this->tempDirectory); - $filesystem->mkdir($this->realDirectory); - - for ($i = 0; $i < $this->numberOfPayloads; $i ++) { - // create temporary file - $file = tempnam(sys_get_temp_dir(), 'uploader'); - - $pointer = fopen($file, 'w+'); - fwrite($pointer, str_repeat('A', 1024), 1024); - fclose($pointer); - - $this->payloads[] = new UploadedFile($file, $i . 'grumpycat.jpeg', null, null, null, true); - } - - // create underlying storage - $this->storage = new FilesystemStorage($this->realDirectory); - - // create orphanage - $session = new Session(new MockArraySessionStorage()); - $session->start(); - - $config = array('directory' => $this->tempDirectory); - - $this->orphanage = new OrphanageStorage($this->storage, $session, $config, 'cat'); - } - public function testUpload() { for ($i = 0; $i < $this->numberOfPayloads; $i ++) { diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 4f7733b..49050c0 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -2,111 +2,45 @@ namespace Oneup\UploaderBundle\Uploader\Chunk; -use Symfony\Component\HttpFoundation\File\File; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\ChunkStorageInterface; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Symfony\Component\Finder\Finder; -use Symfony\Component\Filesystem\Filesystem; use Oneup\UploaderBundle\Uploader\Chunk\ChunkManagerInterface; class ChunkManager implements ChunkManagerInterface { - public function __construct($configuration) + protected $configuration; + protected $storage; + + public function __construct($configuration, ChunkStorageInterface $storage) { $this->configuration = $configuration; + $this->storage = $storage; } public function clear() { - $system = new Filesystem(); - $finder = new Finder(); - - try { - $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds')->files(); - } catch (\InvalidArgumentException $e) { - // the finder will throw an exception of type InvalidArgumentException - // if the directory he should search in does not exist - // in that case we don't have anything to clean - return; - } - - foreach ($finder as $file) { - $system->remove($file); - } + $this->storage->clear($this->configuration['maxage']); } public function addChunk($uuid, $index, UploadedFile $chunk, $original) { - $filesystem = new Filesystem(); - $path = sprintf('%s/%s', $this->configuration['directory'], $uuid); - $name = sprintf('%s_%s', $index, $original); - - // create directory if it does not yet exist - if(!$filesystem->exists($path)) - $filesystem->mkdir(sprintf('%s/%s', $this->configuration['directory'], $uuid)); - - return $chunk->move($path, $name); + return $this->storage->addChunk($uuid, $index, $chunk, $original); } - public function assembleChunks(\IteratorAggregate $chunks, $removeChunk = true, $renameChunk = false) + public function assembleChunks($chunks, $removeChunk = true, $renameChunk = false) { - $iterator = $chunks->getIterator()->getInnerIterator(); - - $base = $iterator->current(); - $iterator->next(); - - while ($iterator->valid()) { - - $file = $iterator->current(); - - if (false === file_put_contents($base->getPathname(), file_get_contents($file->getPathname()), \FILE_APPEND | \LOCK_EX)) { - throw new \RuntimeException('Reassembling chunks failed.'); - } - - if ($removeChunk) { - $filesystem = new Filesystem(); - $filesystem->remove($file->getPathname()); - } - - $iterator->next(); - } - - $name = $base->getBasename(); - - if ($renameChunk) { - $name = preg_replace('/^(\d+)_/', '', $base->getBasename()); - } - - // remove the prefix added by self::addChunk - $assembled = new File($base->getRealPath()); - $assembled = $assembled->move($base->getPath(), $name); - - return $assembled; + return $this->storage->assembleChunks($chunks, $removeChunk, $renameChunk); } public function cleanup($path) { - // cleanup - $filesystem = new Filesystem(); - $filesystem->remove($path); - - return true; + return $this->storage->cleanup($path); } public function getChunks($uuid) { - $finder = new Finder(); - $finder - ->in(sprintf('%s/%s', $this->configuration['directory'], $uuid))->files()->sort(function(\SplFileInfo $a, \SplFileInfo $b) { - $t = explode('_', $a->getBasename()); - $s = explode('_', $b->getBasename()); - $t = (int) $t[0]; - $s = (int) $s[0]; - - return $s < $t; - }); - - return $finder; + return $this->storage->getChunks($uuid); } public function getLoadDistribution() diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index 0991a3e..c89d9bf 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -21,13 +21,13 @@ interface ChunkManagerInterface /** * Assembles the given chunks and return the resulting file. * - * @param \IteratorAggregate $chunks - * @param bool $removeChunk Remove the chunk file once its assembled. - * @param bool $renameChunk Rename the chunk file once its assembled. + * @param $chunks + * @param bool $removeChunk Remove the chunk file once its assembled. + * @param bool $renameChunk Rename the chunk file once its assembled. * * @return File */ - public function assembleChunks(\IteratorAggregate $chunks, $removeChunk = true, $renameChunk = false); + public function assembleChunks($chunks, $removeChunk = true, $renameChunk = false); /** * Get chunks associated with the given uuid. diff --git a/Uploader/Chunk/Storage/ChunkStorageInterface.php b/Uploader/Chunk/Storage/ChunkStorageInterface.php new file mode 100644 index 0000000..2be1146 --- /dev/null +++ b/Uploader/Chunk/Storage/ChunkStorageInterface.php @@ -0,0 +1,18 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; + +use Symfony\Component\HttpFoundation\File\UploadedFile; + +interface ChunkStorageInterface +{ + public function clear($maxAge); + + public function addChunk($uuid, $index, UploadedFile $chunk, $original); + + public function assembleChunks($chunks, $removeChunk, $renameChunk); + + public function cleanup($path); + + public function getChunks($uuid); +} diff --git a/Uploader/Chunk/Storage/FilesystemStorage.php b/Uploader/Chunk/Storage/FilesystemStorage.php new file mode 100644 index 0000000..8855188 --- /dev/null +++ b/Uploader/Chunk/Storage/FilesystemStorage.php @@ -0,0 +1,123 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; + +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpFoundation\File\File; + +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FilesystemStorage implements ChunkStorageInterface +{ + protected $directory; + + public function __construct($directory) + { + $this->directory = $directory; + } + + public function clear($maxAge) + { + $system = new Filesystem(); + $finder = new Finder(); + + try { + $finder->in($this->directory)->date('<=' . -1 * (int) $maxAge . 'seconds')->files(); + } catch (\InvalidArgumentException $e) { + // the finder will throw an exception of type InvalidArgumentException + // if the directory he should search in does not exist + // in that case we don't have anything to clean + return; + } + + foreach ($finder as $file) { + $system->remove($file); + } + } + + public function addChunk($uuid, $index, UploadedFile $chunk, $original) + { + $filesystem = new Filesystem(); + $path = sprintf('%s/%s', $this->directory, $uuid); + $name = sprintf('%s_%s', $index, $original); + + // create directory if it does not yet exist + if(!$filesystem->exists($path)) + $filesystem->mkdir(sprintf('%s/%s', $this->directory, $uuid)); + + return $chunk->move($path, $name); + } + + public function assembleChunks($chunks, $removeChunk, $renameChunk) + { + if (!($chunks instanceof \IteratorAggregate)) { + throw new \InvalidArgumentException('The first argument must implement \IteratorAggregate interface.'); + } + + $iterator = $chunks->getIterator()->getInnerIterator(); + + $base = $iterator->current(); + $iterator->next(); + + while ($iterator->valid()) { + + $file = $iterator->current(); + + if (false === file_put_contents($base->getPathname(), file_get_contents($file->getPathname()), \FILE_APPEND | \LOCK_EX)) { + throw new \RuntimeException('Reassembling chunks failed.'); + } + + if ($removeChunk) { + $filesystem = new Filesystem(); + $filesystem->remove($file->getPathname()); + } + + $iterator->next(); + } + + $name = $base->getBasename(); + + if ($renameChunk) { + // remove the prefix added by self::addChunk + $name = preg_replace('/^(\d+)_/', '', $base->getBasename()); + } + + $assembled = new File($base->getRealPath()); + $assembled = $assembled->move($base->getPath(), $name); + + // the file is only renamed before it is uploaded + if ($renameChunk) { + // create an file to meet interface restrictions + $assembled = new FilesystemFile(new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, $assembled->getSize(), null, true)); + } + + return $assembled; + } + + public function cleanup($path) + { + // cleanup + $filesystem = new Filesystem(); + $filesystem->remove($path); + + return true; + } + + public function getChunks($uuid) + { + $finder = new Finder(); + $finder + ->in(sprintf('%s/%s', $this->directory, $uuid))->files()->sort(function(\SplFileInfo $a, \SplFileInfo $b) { + $t = explode('_', $a->getBasename()); + $s = explode('_', $b->getBasename()); + $t = (int) $t[0]; + $s = (int) $s[0]; + + return $s < $t; + }); + + return $finder; + } +} diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php new file mode 100644 index 0000000..5c641d0 --- /dev/null +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -0,0 +1,159 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; + +use Gaufrette\Adapter\StreamFactory; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; +use Gaufrette\Filesystem; + +use Oneup\UploaderBundle\Uploader\Gaufrette\StreamManager; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class GaufretteStorage extends StreamManager implements ChunkStorageInterface +{ + protected $unhandledChunk; + protected $prefix; + protected $streamWrapperPrefix; + + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) + { + if (!($filesystem->getAdapter() instanceof StreamFactory)) { + throw new \InvalidArgumentException('The filesystem used as chunk storage must implement StreamFactory'); + } + $this->filesystem = $filesystem; + $this->bufferSize = $bufferSize; + $this->prefix = $prefix; + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + /** + * Clears files and folders older than $maxAge in $prefix + * $prefix must be passable so it can clean the orphanage too + * as it is forced to be the same filesystem. + * + * @param $maxAge + * @param null $prefix + */ + public function clear($maxAge, $prefix = null) + { + $prefix = $prefix ? :$this->prefix; + $matches = $this->filesystem->listKeys($prefix); + + $now = time(); + $toDelete = array(); + + // Collect the directories that are old, + // this also means the files inside are old + // but after the files are deleted the dirs + // would remain + foreach ($matches['dirs'] as $key) { + if ($maxAge <= $now-$this->filesystem->mtime($key)) { + $toDelete[] = $key; + } + } + // The same directory is returned for every file it contains + array_unique($toDelete); + foreach ($matches['keys'] as $key) { + if ($maxAge <= $now-$this->filesystem->mtime($key)) { + $this->filesystem->delete($key); + } + } + + foreach ($toDelete as $key) { + // The filesystem will throw exceptions if + // a directory is not empty + try { + $this->filesystem->delete($key); + } catch (\Exception $e) { + continue; + } + } + } + + /** + * Only saves the information about the chunk to avoid moving it + * forth-and-back to reassemble it. Load distribution is enforced + * for gaufrette based chunk storage therefore assembleChunks will + * be called in the same request. + * + * @param $uuid + * @param $index + * @param UploadedFile $chunk + * @param $original + */ + public function addChunk($uuid, $index, UploadedFile $chunk, $original) + { + $this->unhandledChunk = array( + 'uuid' => $uuid, + 'index' => $index, + 'chunk' => $chunk, + 'original' => $original + ); + } + + public function assembleChunks($chunks, $removeChunk, $renameChunk) + { + // the index is only added to be in sync with the filesystem storage + $path = $this->prefix.'/'.$this->unhandledChunk['uuid'].'/'; + $filename = $this->unhandledChunk['index'].'_'.$this->unhandledChunk['original']; + + if (empty($chunks)) { + $target = $filename; + $this->ensureRemotePathExists($path.$target); + } else { + /* + * The array only contains items with matching prefix until the filename + * therefore the order will be decided depending on the filename + * It is only case-insensitive to be overly-careful. + */ + sort($chunks, SORT_STRING | SORT_FLAG_CASE); + $target = pathinfo($chunks[0], PATHINFO_BASENAME); + } + + $dst = $this->filesystem->createStream($path.$target); + if ($this->unhandledChunk['index'] === 0) { + // if it's the first chunk overwrite the already existing part + // to avoid appending to earlier failed uploads + $this->openStream($dst, 'w'); + } else { + $this->openStream($dst, 'a'); + } + + + // Meet the interface requirements + $uploadedFile = new FilesystemFile($this->unhandledChunk['chunk']); + + $this->stream($uploadedFile, $dst); + + if ($renameChunk) { + $name = preg_replace('/^(\d+)_/', '', $target); + $this->filesystem->rename($path.$target, $path.$name); + $target = $name; + } + $uploaded = $this->filesystem->get($path.$target); + + if (!$renameChunk) { + return $uploaded; + } + + return new GaufretteFile($uploaded, $this->filesystem, $this->streamWrapperPrefix); + } + + public function cleanup($path) + { + $this->filesystem->delete($path); + } + + public function getChunks($uuid) + { + $results = $this->filesystem->listKeys($this->prefix.'/'.$uuid); + + return $results['keys']; + } + + public function getFilesystem() + { + return $this->filesystem; + } +} diff --git a/Uploader/File/FileInterface.php b/Uploader/File/FileInterface.php new file mode 100644 index 0000000..511169d --- /dev/null +++ b/Uploader/File/FileInterface.php @@ -0,0 +1,57 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\File; + +/** + * Every function in this interface should be considered unsafe. + * They are only meant to abstract away some basic file functionality. + * For safe methods rely on the parent functions. + * + * Interface FileInterface + * + * @package Oneup\UploaderBundle\Uploader\File + */ +interface FileInterface +{ + /** + * Returns the size of the file + * + * @return int + */ + public function getSize(); + + /** + * Returns the path of the file + * + * @return string + */ + public function getPathname(); + + /** + * Return the path of the file without the filename + * + * @return mixed + */ + public function getPath(); + + /** + * Returns the guessed mime type of the file + * + * @return string + */ + public function getMimeType(); + + /** + * Returns the basename of the file + * + * @return string + */ + public function getBasename(); + + /** + * Returns the guessed extension of the file + * + * @return mixed + */ + public function getExtension(); +} diff --git a/Uploader/File/FilesystemFile.php b/Uploader/File/FilesystemFile.php new file mode 100644 index 0000000..539df73 --- /dev/null +++ b/Uploader/File/FilesystemFile.php @@ -0,0 +1,24 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\File; + +use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FilesystemFile extends UploadedFile implements FileInterface +{ + public function __construct(File $file) + { + if ($file instanceof UploadedFile) { + parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); + } else { + parent::__construct($file->getPathname(), $file->getBasename(), $file->getMimeType(), $file->getSize(), 0, true); + } + + } + + public function getExtension() + { + return $this->getClientOriginalExtension(); + } +} diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php new file mode 100644 index 0000000..0b6904b --- /dev/null +++ b/Uploader/File/GaufretteFile.php @@ -0,0 +1,104 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\File; + +use Gaufrette\Adapter\StreamFactory; +use Gaufrette\File; +use Gaufrette\Filesystem; + +class GaufretteFile extends File implements FileInterface +{ + protected $filesystem; + protected $streamWrapperPrefix; + protected $mimeType; + + public function __construct(File $file, Filesystem $filesystem, $streamWrapperPrefix = null) + { + parent::__construct($file->getKey(), $filesystem); + $this->filesystem = $filesystem; + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + /** + * Returns the size of the file + * + * !! WARNING !! + * Calling this loads the entire file into memory, + * unless it is on a stream-capable filesystem. + * In case of bigger files this could throw exceptions, + * and will have heavy performance footprint. + * !! ------- !! + * + */ + public function getSize() + { + // This can only work on streamable files, so basically local files, + // still only perform it once even on local files to avoid bothering the filesystem.php g + if ($this->filesystem->getAdapter() instanceof StreamFactory && !$this->size) { + if ($this->streamWrapperPrefix) { + try { + $this->setSize(filesize($this->streamWrapperPrefix.$this->getKey())); + } catch (\Exception $e) { + // Fail gracefully if there was a problem with opening the file and + // let gaufrette load the file into memory allowing it to throw exceptions + // if that doesn't work either. + // Not empty to make the scrutiziner happy. + return parent::getSize(); + } + } + } + + return parent::getSize(); + } + + public function getPathname() + { + return $this->getKey(); + } + + public function getPath() + { + return pathinfo($this->getKey(), PATHINFO_DIRNAME); + } + + public function getBasename() + { + return pathinfo($this->getKey(), PATHINFO_BASENAME); + } + + /** + * @return string + */ + public function getMimeType() + { + // This can only work on streamable files, so basically local files, + // still only perform it once even on local files to avoid bothering the filesystem. + if ($this->filesystem->getAdapter() instanceof StreamFactory && !$this->mimeType) { + if ($this->streamWrapperPrefix) { + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $this->mimeType = finfo_file($finfo, $this->streamWrapperPrefix.$this->getKey()); + finfo_close($finfo); + } + } + + return $this->mimeType; + } + + /** + * Now that we may be able to get the mime-type the extension + * COULD be guessed based on that, but it would be even less + * accurate as mime-types can have multiple extensions + * + * @return mixed + */ + public function getExtension() + { + return pathinfo($this->getKey(), PATHINFO_EXTENSION); + } + + public function getFilesystem() + { + return $this->filesystem; + } + +} diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php new file mode 100644 index 0000000..58868b8 --- /dev/null +++ b/Uploader/Gaufrette/StreamManager.php @@ -0,0 +1,59 @@ +<?php +namespace Oneup\UploaderBundle\Uploader\Gaufrette; + +use Gaufrette\Stream; +use Gaufrette\StreamMode; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Gaufrette\Stream\Local as LocalStream; +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; + +class StreamManager +{ + protected $filesystem; + public $buffersize; + + protected function createSourceStream(FileInterface $file) + { + if ($file instanceof GaufretteFile) { + // The file is always streamable as the chunk storage only allows + // adapters that implement StreamFactory + return $file->createStream(); + } + + return new LocalStream($file->getPathname()); + } + + protected function ensureRemotePathExists($path) + { + // this is a somehow ugly workaround introduced + // because the stream-mode is not able to create + // subdirectories. + if(!$this->filesystem->has($path)) + $this->filesystem->write($path, '', true); + } + + protected function openStream(Stream $stream, $mode) + { + // always use binary mode + $mode = $mode.'b+'; + + return $stream->open(new StreamMode($mode)); + } + + protected function stream(FileInterface $file, Stream $dst) + { + $src = $this->createSourceStream($file); + + // always use reading only for the source + $this->openStream($src, 'r'); + + while (!$src->eof()) { + $data = $src->read($this->bufferSize); + $dst->write($data); + } + + $dst->close(); + $src->close(); + } + +} diff --git a/Uploader/Naming/NamerInterface.php b/Uploader/Naming/NamerInterface.php index d44b817..fabd017 100644 --- a/Uploader/Naming/NamerInterface.php +++ b/Uploader/Naming/NamerInterface.php @@ -2,15 +2,15 @@ namespace Oneup\UploaderBundle\Uploader\Naming; -use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Uploader\File\FileInterface; interface NamerInterface { /** * Name a given file and return the name * - * @param UploadedFile $file + * @param FileInterface $file * @return string */ - public function name(UploadedFile $file); + public function name(FileInterface $file); } diff --git a/Uploader/Naming/UniqidNamer.php b/Uploader/Naming/UniqidNamer.php index 4c16b98..34a7141 100644 --- a/Uploader/Naming/UniqidNamer.php +++ b/Uploader/Naming/UniqidNamer.php @@ -2,13 +2,12 @@ namespace Oneup\UploaderBundle\Uploader\Naming; -use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; +use Oneup\UploaderBundle\Uploader\File\FileInterface; class UniqidNamer implements NamerInterface { - public function name(UploadedFile $file) + public function name(FileInterface $file) { - return sprintf('%s.%s', uniqid(), $file->guessExtension()); + return sprintf('%s.%s', uniqid(), $file->getExtension()); } } diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index b09dd25..6903db7 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -24,6 +24,14 @@ class OrphanageManager public function clear() { + // Really ugly solution to clearing the orphanage on gaufrette + $class = $this->container->getParameter('oneup_uploader.orphanage.class'); + if ($class === 'Oneup\UploaderBundle\Uploader\Storage\GaufretteOrphanageStorage') { + $chunkStorage = $this->container->get('oneup_uploader.chunks_storage '); + $chunkStorage->clear($this->config['maxage'], $this->config['directory']); + + return; + } $system = new Filesystem(); $finder = new Finder(); diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/FilesystemOrphanageStorage.php similarity index 71% rename from Uploader/Storage/OrphanageStorage.php rename to Uploader/Storage/FilesystemOrphanageStorage.php index fcbbaf0..e0026cc 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -2,6 +2,9 @@ namespace Oneup\UploaderBundle\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\ChunkStorageInterface; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Finder\Finder; @@ -10,24 +13,25 @@ use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Storage\OrphanageStorageInterface; -class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInterface +class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageStorageInterface { protected $storage; protected $session; protected $config; protected $type; - public function __construct(StorageInterface $storage, SessionInterface $session, $config, $type) + public function __construct(StorageInterface $storage, SessionInterface $session, ChunkStorageInterface $chunkStorage, $config, $type) { parent::__construct($config['directory']); + // We can just ignore the chunkstorage here, it's not needed to access the files $this->storage = $storage; $this->session = $session; $this->config = $config; $this->type = $type; } - public function upload(File $file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { if(!$this->session->isStarted()) throw new \RuntimeException('You need a running session in order to run the Orphanage.'); @@ -42,7 +46,7 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte $return = array(); foreach ($files as $file) { - $return[] = $this->storage->upload(new File($file->getPathname()), str_replace($this->getFindPath(), '', $file)); + $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), str_replace($this->getFindPath(), '', $file)); } return $return; diff --git a/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index d6915e0..ce62631 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -2,9 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\HttpFoundation\File\File; - -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; +use Oneup\UploaderBundle\Uploader\File\FileInterface; class FilesystemStorage implements StorageInterface { @@ -15,7 +13,7 @@ class FilesystemStorage implements StorageInterface $this->directory = $directory; } - public function upload(File $file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); $path = sprintf('%s/%s', $this->directory, $path); diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php new file mode 100644 index 0000000..ea5379f --- /dev/null +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -0,0 +1,90 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use Gaufrette\File; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage as GaufretteChunkStorage; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageStorageInterface +{ + protected $storage; + protected $session; + protected $chunkStorage; + protected $config; + protected $type; + + /** + * @param StorageInterface $storage + * @param SessionInterface $session + * @param GaufretteChunkStorage $chunkStorage This class is only used if the gaufrette chunk storage is used. + * @param $config + * @param $type + */ + public function __construct(StorageInterface $storage, SessionInterface $session, GaufretteChunkStorage $chunkStorage, $config, $type) + { + // initiate the storage on the chunk storage's filesystem + // the prefix and stream wrapper are unnecessary. + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, null, null); + + $this->storage = $storage; + $this->chunkStorage = $chunkStorage; + $this->session = $session; + $this->config = $config; + $this->type = $type; + } + + public function upload(FileInterface $file, $name, $path = null) + { + if(!$this->session->isStarted()) + throw new \RuntimeException('You need a running session in order to run the Orphanage.'); + + return parent::upload($file, $name, $this->getPath()); + } + + public function uploadFiles() + { + try { + $files = $this->getFiles(); + $return = array(); + + foreach ($files as $key => $file) { + try { + $return[] = $this->storage->upload($file, str_replace($this->getPath(), '', $key)); + } catch (\Exception $e) { + // well, we tried. + continue; + } + } + + return $return; + } catch (\Exception $e) { + return array(); + } + } + + public function getFiles() + { + $keys = $this->chunkStorage->getFilesystem()->listKeys($this->getPath()); + $keys = $keys['keys']; + $files = array(); + + foreach ($keys as $key) { + // gotta pass the filesystem to both as you can't get it out from one.. + $files[$key] = new GaufretteFile(new File($key, $this->chunkStorage->getFilesystem()), $this->chunkStorage->getFilesystem()); + } + + return $files; + } + + protected function getPath() + { + // the storage is initiated in the root of the filesystem, from where the orphanage directory + // should be relative. + return sprintf('%s/%s/%s', $this->config['directory'], $this->session->getId(), $this->type); + } + +} diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index f2229d0..7b9bc7e 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -2,26 +2,25 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\HttpFoundation\File\File; -use Gaufrette\Stream\Local as LocalStream; -use Gaufrette\StreamMode; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; use Gaufrette\Filesystem; +use Symfony\Component\Filesystem\Filesystem as LocalFilesystem; use Gaufrette\Adapter\MetadataSupporter; +use Oneup\UploaderBundle\Uploader\Gaufrette\StreamManager; -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; - -class GaufretteStorage implements StorageInterface +class GaufretteStorage extends StreamManager implements StorageInterface { - protected $filesystem; - protected $bufferSize; + protected $streamWrapperPrefix; - public function __construct(Filesystem $filesystem, $bufferSize) + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix = null) { $this->filesystem = $filesystem; $this->bufferSize = $bufferSize; + $this->streamWrapperPrefix = $streamWrapperPrefix; } - public function upload(File $file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); @@ -29,26 +28,28 @@ class GaufretteStorage implements StorageInterface $this->filesystem->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); } - $src = new LocalStream($file->getPathname()); - $dst = $this->filesystem->createStream($path); + if ($file instanceof GaufretteFile) { + if ($file->getFilesystem() == $this->filesystem) { + $file->getFilesystem()->rename($file->getKey(), $path); - // this is a somehow ugly workaround introduced - // because the stream-mode is not able to create - // subdirectories. - if(!$this->filesystem->has($path)) - $this->filesystem->write($path, '', true); + return new GaufretteFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + } + } - $src->open(new StreamMode('rb+')); - $dst->open(new StreamMode('wb+')); + $this->ensureRemotePathExists($path); + $dst = $this->filesystem->createStream($path); - while (!$src->eof()) { - $data = $src->read($this->bufferSize); - $dst->write($data); - } + $this->openStream($dst, 'w'); + $this->stream($file, $dst); - $dst->close(); - $src->close(); + if ($file instanceof GaufretteFile) { + $file->delete(); + } else { + $filesystem = new LocalFilesystem(); + $filesystem->remove($file->getPathname()); + } - return $this->filesystem->get($path); + return new GaufretteFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); } + } diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 79fb3ae..31665d8 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -2,16 +2,16 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\HttpFoundation\File\File; +use Oneup\UploaderBundle\Uploader\File\FileInterface; interface StorageInterface { /** * Uploads a File instance to the configured storage. * - * @param File $file + * @param $file * @param string $name * @param string $path */ - public function upload(File $file, $name, $path = null); + public function upload(FileInterface $file, $name, $path = null); } diff --git a/composer.json b/composer.json index b4a4d15..a6be9f8 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ ], "require": { - "symfony/framework-bundle": "2.*", + "symfony/framework-bundle": ">=2.2", "symfony/finder": ">=2.2.0" }, commit d0cdf7a9f08ded7fcf1bc05fe44e7d25031c42e4 (from 147388f69ed1b5d5fa8b91e2c039fb7e8deb0093) Merge: 48b19bc 147388f Author: Jim Schmid <[email protected]> Date: Mon Oct 14 21:17:41 2013 +0200 Merge branch 'release-1.0' of github.com:mitom/OneupUploaderBundle into mitom-release-1.0 Conflicts: EventListener/AllowedExtensionValidationListener.php EventListener/DisallowedExtensionValidationListener.php diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c11e014..a9efae7 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -73,12 +73,6 @@ class Configuration implements ConfigurationInterface ->scalarNode('sync_buffer_size')->defaultValue('100K')->end() ->end() ->end() - ->arrayNode('allowed_extensions') - ->prototype('scalar')->end() - ->end() - ->arrayNode('disallowed_extensions') - ->prototype('scalar')->end() - ->end() ->arrayNode('allowed_mimetypes') ->prototype('scalar')->end() ->end() diff --git a/EventListener/AllowedExtensionValidationListener.php b/EventListener/AllowedExtensionValidationListener.php deleted file mode 100644 index add50ca..0000000 --- a/EventListener/AllowedExtensionValidationListener.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Oneup\UploaderBundle\Event\ValidationEvent; -use Oneup\UploaderBundle\Uploader\Exception\ValidationException; - -class AllowedExtensionValidationListener -{ - public function onValidate(ValidationEvent $event) - { - $config = $event->getConfig(); - $file = $event->getFile(); - - $extension = $file->getExtension(); - - if (count($config['allowed_extensions']) > 0 && !in_array($extension, $config['allowed_extensions'])) { - throw new ValidationException('error.whitelist'); - } - } -} diff --git a/EventListener/DisallowedExtensionValidationListener.php b/EventListener/DisallowedExtensionValidationListener.php deleted file mode 100644 index 9f000de..0000000 --- a/EventListener/DisallowedExtensionValidationListener.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Oneup\UploaderBundle\Event\ValidationEvent; -use Oneup\UploaderBundle\Uploader\Exception\ValidationException; - -class DisallowedExtensionValidationListener -{ - public function onValidate(ValidationEvent $event) - { - $config = $event->getConfig(); - $file = $event->getFile(); - - $extension = $file->getExtension(); - - if (count($config['disallowed_extensions']) > 0 && in_array($extension, $config['disallowed_extensions'])) { - throw new ValidationException('error.blacklist'); - } - } -} diff --git a/Resources/config/validators.xml b/Resources/config/validators.xml index 5b2ffe0..4c3fc73 100644 --- a/Resources/config/validators.xml +++ b/Resources/config/validators.xml @@ -8,14 +8,6 @@ <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener"> - <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> - </service> - - <service id="oneup_uploader.validation_listener.disallowed_extension" class="Oneup\UploaderBundle\EventListener\DisallowedExtensionValidationListener"> - <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> - </service> - <service id="oneup_uploader.validation_listener.allowed_mimetype" class="Oneup\UploaderBundle\EventListener\AllowedMimetypeValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 0a712c9..dcc5a20 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -34,8 +34,6 @@ oneup_uploader: directory: ~ stream_wrapper: ~ sync_buffer_size: 100K - allowed_extensions: [] - disallowed_extensions: [] allowed_mimetypes: [] disallowed_mimetypes: [] error_handler: oneup_uploader.error_handler.noop diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 619cebc..a350ddb 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -23,8 +23,7 @@ oneup_uploader: max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] @@ -38,8 +37,7 @@ oneup_uploader: max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] @@ -53,8 +51,7 @@ oneup_uploader: max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] @@ -68,8 +65,7 @@ oneup_uploader: max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] @@ -83,8 +79,7 @@ oneup_uploader: max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] @@ -98,8 +93,7 @@ oneup_uploader: max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] @@ -115,8 +109,7 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload error_handler: oneup_uploader.error_handler.blueimp - allowed_extensions: [ "ok" ] - disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] disallowed_mimetypes: [ "image/gif" ] diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 1a3c4b7..77a5bac 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -7,8 +7,6 @@ use Oneup\UploaderBundle\UploadEvents; abstract class AbstractValidationTest extends AbstractControllerTest { - abstract protected function getFileWithCorrectExtension(); - abstract protected function getFileWithIncorrectExtension(); abstract protected function getFileWithCorrectMimeType(); abstract protected function getFileWithIncorrectMimeType(); abstract protected function getOversizedFile(); @@ -27,26 +25,6 @@ abstract class AbstractValidationTest extends AbstractControllerTest $this->assertCount(0, $this->getUploadedFiles()); } - public function testAgainstCorrectExtension() - { - // assemble a request - $client = $this->client; - $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectExtension())); - $response = $client->getResponse(); - - $this->assertTrue($response->isSuccessful()); - $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); - $this->assertCount(1, $this->getUploadedFiles()); - - foreach ($this->getUploadedFiles() as $file) { - $this->assertTrue($file->isFile()); - $this->assertTrue($file->isReadable()); - $this->assertEquals(128, $file->getSize()); - } - } - public function testEvents() { $client = $this->client; @@ -60,7 +38,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectExtension())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType())); $this->assertEquals(1, $validationCount); } @@ -82,25 +60,11 @@ abstract class AbstractValidationTest extends AbstractControllerTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectExtension())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType())); $this->assertEquals(1, $validationCount); } - public function testAgainstIncorrectExtension() - { - // assemble a request - $client = $this->client; - $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithIncorrectExtension())); - $response = $client->getResponse(); - - //$this->assertTrue($response->isNotSuccessful()); - $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); - $this->assertCount(0, $this->getUploadedFiles()); - } - public function testAgainstCorrectMimeType() { // assemble a request diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index 95667fd..2aec2f7 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -22,26 +22,6 @@ class BlueimpValidationTest extends AbstractValidationTest $this->assertCount(0, $this->getUploadedFiles()); } - public function testAgainstCorrectExtension() - { - // assemble a request - $client = $this->client; - $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension(), array('HTTP_ACCEPT' => 'application/json')); - $response = $client->getResponse(); - - $this->assertTrue($response->isSuccessful()); - $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); - $this->assertCount(1, $this->getUploadedFiles()); - - foreach ($this->getUploadedFiles() as $file) { - $this->assertTrue($file->isFile()); - $this->assertTrue($file->isReadable()); - $this->assertEquals(128, $file->getSize()); - } - } - public function testEvents() { $client = $this->client; @@ -55,25 +35,11 @@ class BlueimpValidationTest extends AbstractValidationTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType()); $this->assertEquals(1, $validationCount); } - public function testAgainstIncorrectExtension() - { - // assemble a request - $client = $this->client; - $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectExtension(), array('HTTP_ACCEPT' => 'application/json')); - $response = $client->getResponse(); - - //$this->assertTrue($response->isNotSuccessful()); - $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); - $this->assertCount(0, $this->getUploadedFiles()); - } - public function testAgainstCorrectMimeType() { // assemble a request @@ -130,26 +96,6 @@ class BlueimpValidationTest extends AbstractValidationTest ))); } - protected function getFileWithCorrectExtension() - { - return array('files' => array(new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ))); - } - - protected function getFileWithIncorrectExtension() - { - return array('files' => array(new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ))); - } - protected function getFileWithCorrectMimeType() { return array('files' => array(new UploadedFile( diff --git a/Tests/Controller/DropzoneValidationTest.php b/Tests/Controller/DropzoneValidationTest.php index 73cb5ff..abe7f06 100644 --- a/Tests/Controller/DropzoneValidationTest.php +++ b/Tests/Controller/DropzoneValidationTest.php @@ -27,26 +27,6 @@ class DropzoneValidationTest extends AbstractValidationTest ); } - protected function getFileWithCorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ); - } - - protected function getFileWithIncorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ); - } - protected function getFileWithCorrectMimeType() { return new UploadedFile( diff --git a/Tests/Controller/FancyUploadValidationTest.php b/Tests/Controller/FancyUploadValidationTest.php index 7e48964..1f78228 100644 --- a/Tests/Controller/FancyUploadValidationTest.php +++ b/Tests/Controller/FancyUploadValidationTest.php @@ -27,26 +27,6 @@ class FancyUploadValidationTest extends AbstractValidationTest ); } - protected function getFileWithCorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ); - } - - protected function getFileWithIncorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ); - } - protected function getFileWithCorrectMimeType() { return new UploadedFile( diff --git a/Tests/Controller/FineUploaderValidationTest.php b/Tests/Controller/FineUploaderValidationTest.php index d1961e4..a3b1a7e 100644 --- a/Tests/Controller/FineUploaderValidationTest.php +++ b/Tests/Controller/FineUploaderValidationTest.php @@ -27,26 +27,6 @@ class FineUploaderValidationTest extends AbstractValidationTest ); } - protected function getFileWithCorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ); - } - - protected function getFileWithIncorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ); - } - protected function getFileWithCorrectMimeType() { return new UploadedFile( diff --git a/Tests/Controller/PluploadValidationTest.php b/Tests/Controller/PluploadValidationTest.php index 61ffc55..c9e9be9 100644 --- a/Tests/Controller/PluploadValidationTest.php +++ b/Tests/Controller/PluploadValidationTest.php @@ -27,26 +27,6 @@ class PluploadValidationTest extends AbstractValidationTest ); } - protected function getFileWithCorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ); - } - - protected function getFileWithIncorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ); - } - protected function getFileWithCorrectMimeType() { return new UploadedFile( diff --git a/Tests/Controller/UploadifyValidationTest.php b/Tests/Controller/UploadifyValidationTest.php index 0f10650..086267f 100644 --- a/Tests/Controller/UploadifyValidationTest.php +++ b/Tests/Controller/UploadifyValidationTest.php @@ -27,26 +27,6 @@ class UploadifyValidationTest extends AbstractValidationTest ); } - protected function getFileWithCorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ); - } - - protected function getFileWithIncorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ); - } - protected function getFileWithCorrectMimeType() { return new UploadedFile( diff --git a/Tests/Controller/YUI3ValidationTest.php b/Tests/Controller/YUI3ValidationTest.php index ca4919c..2325c61 100644 --- a/Tests/Controller/YUI3ValidationTest.php +++ b/Tests/Controller/YUI3ValidationTest.php @@ -27,26 +27,6 @@ class YUI3ValidationTest extends AbstractValidationTest ); } - protected function getFileWithCorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.ok', - 'text/plain', - 128 - ); - } - - protected function getFileWithIncorrectExtension() - { - return new UploadedFile( - $this->createTempFile(128), - 'cat.fail', - 'text/plain', - 128 - ); - } - protected function getFileWithCorrectMimeType() { return new UploadedFile(
0
7884373aed3344919d6aee3f95251307bbf24808
1up-lab/OneupUploaderBundle
fixed existing tests and some mistakes revealed by them
commit 7884373aed3344919d6aee3f95251307bbf24808 Author: mitom <[email protected]> Date: Thu Oct 10 19:59:30 2013 +0200 fixed existing tests and some mistakes revealed by them diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 01b0a6d..1a3c4b7 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -56,7 +56,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest // event data $validationCount = 0; - $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + $dispatcher->addListener(UploadEvents::VALIDATION, function() use (&$validationCount) { ++ $validationCount; }); diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index 4bbfa1c..19fea99 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -52,7 +52,7 @@ class BlueimpValidationTest extends AbstractValidationTest // event data $validationCount = 0; - $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + $dispatcher->addListener(UploadEvents::VALIDATION, function() use (&$validationCount) { ++ $validationCount; }); diff --git a/Tests/Uploader/Chunk/ChunkManagerTest.php b/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php similarity index 80% rename from Tests/Uploader/Chunk/ChunkManagerTest.php rename to Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php index 4ce9c4a..1df65ea 100644 --- a/Tests/Uploader/Chunk/ChunkManagerTest.php +++ b/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php @@ -1,13 +1,12 @@ <?php -namespace Oneup\UploaderBundle\Tests\Uploader\Chunk; +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage; -use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; - -class ChunkManagerTest extends \PHPUnit_Framework_TestCase +class FilesystemStorageTest extends \PHPUnit_Framework_TestCase { protected $tmpDir; @@ -49,7 +48,7 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase { // get a manager configured with a max-age of 5 minutes $maxage = 5 * 60; - $manager = $this->getManager($maxage); + $manager = $this->getStorage(); $numberOfFiles = 10; $finder = new Finder(); @@ -58,7 +57,7 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase $this->fillDirectory($numberOfFiles); $this->assertCount(10, $finder); - $manager->clear(); + $manager->clear($maxage); $this->assertTrue(is_dir($this->tmpDir)); $this->assertTrue(is_writeable($this->tmpDir)); @@ -75,18 +74,17 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase $filesystem = new Filesystem(); $filesystem->remove($this->tmpDir); - $manager = $this->getManager(10); - $manager->clear(); + $manager = $this->getStorage(); + $manager->clear(10); // yey, no exception $this->assertTrue(true); } - protected function getManager($maxage) + protected function getStorage() { - return new ChunkManager(array( - 'directory' => $this->tmpDir, - 'maxage' => $maxage + return new FilesystemStorage(array( + 'directory' => $this->tmpDir )); } diff --git a/Tests/Uploader/Naming/UniqidNamerTest.php b/Tests/Uploader/Naming/UniqidNamerTest.php index 2ff1631..d20df0a 100644 --- a/Tests/Uploader/Naming/UniqidNamerTest.php +++ b/Tests/Uploader/Naming/UniqidNamerTest.php @@ -8,14 +8,14 @@ class UniqidNamerTest extends \PHPUnit_Framework_TestCase { public function testNamerReturnsName() { - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') ->disableOriginalConstructor() ->getMock() ; $file ->expects($this->any()) - ->method('guessExtension') + ->method('getExtension') ->will($this->returnValue('jpeg')) ; @@ -25,14 +25,14 @@ class UniqidNamerTest extends \PHPUnit_Framework_TestCase public function testNamerReturnsUniqueName() { - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') ->disableOriginalConstructor() ->getMock() ; $file ->expects($this->any()) - ->method('guessExtension') + ->method('getExtension') ->will($this->returnValue('jpeg')) ; diff --git a/Tests/Uploader/Storage/FilesystemStorageTest.php b/Tests/Uploader/Storage/FilesystemStorageTest.php index 6f3e011..1ae9964 100644 --- a/Tests/Uploader/Storage/FilesystemStorageTest.php +++ b/Tests/Uploader/Storage/FilesystemStorageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -26,7 +27,7 @@ class FilesystemStorageTest extends \PHPUnit_Framework_TestCase public function testUpload() { - $payload = new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true); + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); $storage = new FilesystemStorage($this->directory); $storage->upload($payload, 'notsogrumpyanymore.jpeg'); diff --git a/Tests/Uploader/Storage/GaufretteStorageTest.php b/Tests/Uploader/Storage/GaufretteStorageTest.php index f9ecfe6..008e618 100644 --- a/Tests/Uploader/Storage/GaufretteStorageTest.php +++ b/Tests/Uploader/Storage/GaufretteStorageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -33,7 +34,7 @@ class GaufretteStorageTest extends \PHPUnit_Framework_TestCase public function testUpload() { - $payload = new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true); + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); $this->storage->upload($payload, 'notsogrumpyanymore.jpeg'); $finder = new Finder(); diff --git a/Tests/Uploader/Storage/OrphanageStorageTest.php b/Tests/Uploader/Storage/OrphanageStorageTest.php index bcaf525..b2eed0a 100644 --- a/Tests/Uploader/Storage/OrphanageStorageTest.php +++ b/Tests/Uploader/Storage/OrphanageStorageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -39,7 +40,7 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase fwrite($pointer, str_repeat('A', 1024), 1024); fclose($pointer); - $this->payloads[] = new UploadedFile($file, $i . 'grumpycat.jpeg', null, null, null, true); + $this->payloads[] = new FilesystemFile(new UploadedFile($file, $i . 'grumpycat.jpeg', null, null, null, true)); } // create underlying storage diff --git a/Uploader/File/FilesystemFile.php b/Uploader/File/FilesystemFile.php index c24ba28..539df73 100644 --- a/Uploader/File/FilesystemFile.php +++ b/Uploader/File/FilesystemFile.php @@ -2,21 +2,23 @@ namespace Oneup\UploaderBundle\Uploader\File; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; class FilesystemFile extends UploadedFile implements FileInterface { - public function __construct(UploadedFile $file) + public function __construct(File $file) { - parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); + if ($file instanceof UploadedFile) { + parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); + } else { + parent::__construct($file->getPathname(), $file->getBasename(), $file->getMimeType(), $file->getSize(), 0, true); + } } public function getExtension() { - // If the file is in tmp, it has no extension, but the wrapper object - // will have the original extension, otherwise it is better to rely - // on the actual extension - return parent::getExtension() ? :$this->getClientOriginalExtension(); + return $this->getClientOriginalExtension(); } } diff --git a/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index f2613bf..ce62631 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -2,7 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\File\FileInterface; class FilesystemStorage implements StorageInterface { @@ -13,7 +13,7 @@ class FilesystemStorage implements StorageInterface $this->directory = $directory; } - public function upload($file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); $path = sprintf('%s/%s', $this->directory, $path); diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 1c0bc9c..f1ae5bd 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -12,14 +12,14 @@ class GaufretteStorage extends StreamManager implements StorageInterface { protected $streamWrapperPrefix; - public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix) + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix = null) { $this->filesystem = $filesystem; $this->bufferSize = $bufferSize; $this->streamWrapperPrefix = $streamWrapperPrefix; } - public function upload($file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/OrphanageStorage.php index ffdd2ae..22656aa 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -29,7 +29,7 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte $this->type = $type; } - public function upload($file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { if(!$this->session->isStarted()) throw new \RuntimeException('You need a running session in order to run the Orphanage.'); @@ -44,7 +44,7 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte $return = array(); foreach ($files as $file) { - $return[] = $this->storage->upload(new File($file->getPathname()), str_replace($this->getFindPath(), '', $file)); + $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), str_replace($this->getFindPath(), '', $file)); } return $return; diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 0c7e4b5..31665d8 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -9,9 +9,9 @@ interface StorageInterface /** * Uploads a File instance to the configured storage. * - * @param $file - * @param string $name - * @param string $path + * @param $file + * @param string $name + * @param string $path */ - public function upload($file, $name, $path = null); + public function upload(FileInterface $file, $name, $path = null); }
0
e17d9857b7e104b2d32806acf4a69b9d1ac00eb4
1up-lab/OneupUploaderBundle
Test the orphanage after really uploading files.
commit e17d9857b7e104b2d32806acf4a69b9d1ac00eb4 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 21:30:20 2013 +0200 Test the orphanage after really uploading files. diff --git a/Tests/Uploader/Storage/OrphanageStorageTest.php b/Tests/Uploader/Storage/OrphanageStorageTest.php index 043f7a2..c09caaf 100644 --- a/Tests/Uploader/Storage/OrphanageStorageTest.php +++ b/Tests/Uploader/Storage/OrphanageStorageTest.php @@ -23,8 +23,8 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase public function setUp() { $this->numberOfPayloads = 5; - $this->tempDirectory = sys_get_temp_dir() . '/storage'; - $this->realDirectory = sys_get_temp_dir() . '/orphanage'; + $this->tempDirectory = sys_get_temp_dir() . '/orphanage'; + $this->realDirectory = sys_get_temp_dir() . '/storage'; $this->payloads = array(); $filesystem = new Filesystem(); @@ -44,7 +44,7 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase } // create underlying storage - $this->storage = new FilesystemStorage($this->tempDirectory); + $this->storage = new FilesystemStorage($this->realDirectory); // create orphanage $session = new Session(new MockArraySessionStorage()); @@ -62,17 +62,44 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); } - // find in tempDirectory, should equals numberOfPayloads $finder = new Finder(); $finder->in($this->tempDirectory)->files(); $this->assertCount($this->numberOfPayloads, $finder); - // find in realDirectory, should equals 0 $finder = new Finder(); $finder->in($this->realDirectory)->files(); $this->assertCount(0, $finder); } + public function testUploadAndFetching() + { + for($i = 0; $i < $this->numberOfPayloads; $i ++) + { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->files(); + $this->assertCount(0, $finder); + + $files = $this->orphanage->uploadFiles(); + + $this->assertTrue(is_array($files)); + $this->assertCount($this->numberOfPayloads, $files); + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount(0, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + } + public function tearDown() { $filesystem = new Filesystem();
0
7bb3f2af115ac4462c8cdb5d58c7ca64bb8f4a3c
1up-lab/OneupUploaderBundle
Update chunked_uploads.md
commit 7bb3f2af115ac4462c8cdb5d58c7ca64bb8f4a3c Author: mitom <[email protected]> Date: Fri Oct 11 10:48:44 2013 +0200 Update chunked_uploads.md diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index 7b0dadc..b6c560d 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -51,8 +51,10 @@ oneup_uploader: stream_wrapper: 'gaufrette://gallery/' ``` +> Setting the stream_wrapper is heavily recommended for better performance, see the reasons in the [gaufrette configuration](gaufrette_storage.md#configure-your-mappings) + As you can see there are is a new option, ```prefix```. It represents the directory -in *relative* to the filesystem's directory which the chunks are stored in. + *relative* to the filesystem's directory which the chunks are stored in. Gaufrette won't allow it to be outside of the filesystem. > You can only use stream capable filesystems for the chunk storage, at the time of this writing @@ -68,7 +70,7 @@ resulting in only 1 read and 1 write operation. You can achieve the biggest improvement if you use the same filesystem as your storage, as if you do so, the assembled file only has to be moved out of the chunk directory, which on the same filesystem takes almost not time. -> The load_distribution is forcefully turned on, if you use gaufrette as the chunk storage. +> The ```load distribution``` is forcefully turned on, if you use gaufrette as the chunk storage. ## Clean up
0
e016c7218ce2046fafcac1cd907afd57e823779e
1up-lab/OneupUploaderBundle
Merge pull request #112 from mvrhov/patch-1 catch non-existing directory exception.
commit e016c7218ce2046fafcac1cd907afd57e823779e (from bcde9b99fc62015b4e93abf68dfc9fb51a146c22) Merge: bcde9b9 34c38d9 Author: Jim Schmid <[email protected]> Date: Fri Jun 20 10:44:41 2014 +0200 Merge pull request #112 from mvrhov/patch-1 catch non-existing directory exception. diff --git a/Uploader/Storage/FilesystemOrphanageStorage.php b/Uploader/Storage/FilesystemOrphanageStorage.php index e0026cc..8a2e0e4 100644 --- a/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -58,7 +58,15 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageS public function getFiles() { $finder = new Finder(); - $finder->in($this->getFindPath())->files(); + try { + $finder->in($this->getFindPath())->files(); + } catch (\InvalidArgumentException $e) { + //catch non-existing directory exception. + //This can happen if getFiles is called and no file has yet been uploaded + + //push empty array into the finder so we can emulate no files found + $finder->append(array()); + } return $finder; }
0
7733402b40836ed6a5fa6b06b255e3ee75b5c8db
1up-lab/OneupUploaderBundle
Moved logic of building the path variable in the Orphenage to a separated function.
commit 7733402b40836ed6a5fa6b06b255e3ee75b5c8db Author: Jim Schmid <[email protected]> Date: Wed Mar 13 12:09:00 2013 +0100 Moved logic of building the path variable in the Orphenage to a separated function. diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php index c7a5506..0109f1f 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Orphanage/Orphanage.php @@ -23,12 +23,8 @@ class Orphanage implements OrphanageInterface if(!$this->session->isStarted()) throw new \RuntimeException('You need a running session in order to run the Orphanage.'); - // prefix directory with session id - $id = $this->session->getId(); - $path = sprintf('%s/%s', $this->config['directory'], $id); - // move file to orphanage - return $file->move($path, $name); + return $file->move($this->getPath(), $name); } public function removeFile(File $file) @@ -40,4 +36,12 @@ class Orphanage implements OrphanageInterface { } + + protected function getPath() + { + $id = $this->session->getId(); + $path = sprintf('%s/%s', $this->config['directory'], $id); + + return $path; + } } \ No newline at end of file
0
0abd7065d1e36193147ba5cbaf53f3e5576389ae
1up-lab/OneupUploaderBundle
Update custom_validator.md Cc https://github.com/1up-lab/OneupUploaderBundle/pull/211
commit 0abd7065d1e36193147ba5cbaf53f3e5576389ae Author: Jim Schmid <[email protected]> Date: Mon Feb 8 08:48:06 2016 +0100 Update custom_validator.md Cc https://github.com/1up-lab/OneupUploaderBundle/pull/211 diff --git a/Resources/doc/custom_validator.md b/Resources/doc/custom_validator.md index 2d5b5f0..1a4d77d 100644 --- a/Resources/doc/custom_validator.md +++ b/Resources/doc/custom_validator.md @@ -53,3 +53,5 @@ services: tags: - { name: kernel.event_listener, event: oneup_uploader.validation, method: onValidate } ``` + +Since version 1.6 you can listen to an event thrown for every uploader specifically. The name for the event is `oneup_uploader.validation.{type}` where `{type}` represents the config key of the uploader you want to target.
0
2f9cd2b4dd6a67a93ca49b9cc5c7c9aab8bd6fba
1up-lab/OneupUploaderBundle
Merge pull request #224 from JHGitty/patch-6 Add warning to custom namer doc
commit 2f9cd2b4dd6a67a93ca49b9cc5c7c9aab8bd6fba (from 18a7f3194bfd8a451e194410bc24a0620bae3acd) Merge: 18a7f31 4c51d95 Author: Jim Schmid <[email protected]> Date: Mon Feb 8 08:27:01 2016 +0100 Merge pull request #224 from JHGitty/patch-6 Add warning to custom namer doc diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index c83002d..0d9dc17 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -24,7 +24,7 @@ class CatNamer implements NamerInterface } ``` -To match the `NamerInterface` you have to implement the function `name()` which expects an `FileInterface` and should return a string representing the name of the given file. The example above would name every file _grumpycat.jpg_ and is therefore not very useful. +To match the `NamerInterface` you have to implement the function `name()` which expects an `FileInterface` and should return a string representing the name of the given file. The example above would name every file _grumpycat.jpg_ and is therefore not very useful. The namer should return an unique name to avoid issues if the file already exists. Next, register your created namer as a service in your `services.xml` commit 2f9cd2b4dd6a67a93ca49b9cc5c7c9aab8bd6fba (from 4c51d95f8b59b8373d351a26373cae0bcd69d650) Merge: 18a7f31 4c51d95 Author: Jim Schmid <[email protected]> Date: Mon Feb 8 08:27:01 2016 +0100 Merge pull request #224 from JHGitty/patch-6 Add warning to custom namer doc diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index fd6d87a..c577309 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -1,7 +1,7 @@ Using Chunked Uploads ===================== -Fine Uploader comes bundled with the possibility to use so called chunked uploads. If enabed, an uploaded file will be split into equal sized blobs which are sequentially uploaded afterwards. In order to use this feature, be sure to enable it in the frontend. +Fine Uploader comes bundled with the possibility to use so called chunked uploads. If enabled, an uploaded file will be split into equal sized blobs which are sequentially uploaded afterwards. In order to use this feature, be sure to enable it in the frontend. ```js $(document).ready(function()
0
bf82ebc63684d3698ec020d2c9a96163815288db
1up-lab/OneupUploaderBundle
Whoopsi.
commit bf82ebc63684d3698ec020d2c9a96163815288db Author: Jim Schmid <[email protected]> Date: Wed Mar 13 12:07:34 2013 +0100 Whoopsi. diff --git a/Uploader/Orphanage/OrphanageInterface.php b/Uploader/Orphanage/OrphanageInterface.php index 07b5558..8e75e4e 100644 --- a/Uploader/Orphanage/OrphanageInterface.php +++ b/Uploader/Orphanage/OrphanageInterface.php @@ -6,5 +6,5 @@ use Symfony\Component\HttpFoundation\File\File; interface OrphanageInterface { - public function add(File $file, $name); + public function addFile(File $file, $name); }
0
559f4d3139e7e428fba7b972386ed45c2ab076ef
1up-lab/OneupUploaderBundle
Added TypeHinting for Controller constructor.
commit 559f4d3139e7e428fba7b972386ed45c2ab076ef Author: Jim Schmid <[email protected]> Date: Thu Mar 14 17:10:51 2013 +0100 Added TypeHinting for Controller constructor. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 09f386a..ebd2c39 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -5,12 +5,17 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Finder\Finder; use Oneup\UploaderBundle\UploadEvents; use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Controller\UploadControllerInterface; +use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; +use Oneup\UploaderBundle\Uploader\Chunk\ChunkManagerInterface; class UploaderController implements UploadControllerInterface { @@ -22,7 +27,7 @@ class UploaderController implements UploadControllerInterface protected $type; protected $chunkManager; - public function __construct($request, $namer, $storage, $dispatcher, $type, $config, $chunkManager) + public function __construct(Request $request, NamerInterface $namer, StorageInterface $storage, EventDispatcherInterface $dispatcher, $type, array $config, ChunkManagerInterface $chunkManager) { $this->request = $request; $this->namer = $namer;
0
2bcb029c5c94479fd0e6648945f29d31b084a55d
1up-lab/OneupUploaderBundle
removed PHP 5.3 support
commit 2bcb029c5c94479fd0e6648945f29d31b084a55d Author: Martin Aarhof <[email protected]> Date: Fri Jan 22 04:08:18 2016 +0100 removed PHP 5.3 support diff --git a/.travis.yml b/.travis.yml index 1564c0e..c044e39 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.3 - 5.4 - 5.5 - 5.6
0
62223478ae1cc07be69a1c7c98a4f9aaffeb7ff9
1up-lab/OneupUploaderBundle
Allow PHP 8.0 (#398) * Allow PHP 8.0 * Use shivammathur/[email protected] * Fix CS * PHPStan errors * Cast to string
commit 62223478ae1cc07be69a1c7c98a4f9aaffeb7ff9 Author: David Greminger <[email protected]> Date: Mon Feb 8 19:06:19 2021 +0100 Allow PHP 8.0 (#398) * Allow PHP 8.0 * Use shivammathur/[email protected] * Fix CS * PHPStan errors * Cast to string diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47757f4..6002249 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Setup PHP - uses: shivammathur/[email protected] + uses: shivammathur/[email protected] with: php-version: 7.4 extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo, zlib @@ -36,11 +36,11 @@ jobs: strategy: fail-fast: false matrix: - php: [7.2, 7.3, 7.4] + php: [7.2, 7.3, 7.4, 8.0] symfony: [4.4, 5.0] steps: - name: Setup PHP - uses: shivammathur/[email protected] + uses: shivammathur/[email protected] with: php-version: ${{ matrix.php }} extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib diff --git a/composer.json b/composer.json index 001ef57..63f1a46 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ } ], "require": { - "php": "^7.2.5", + "php": "^7.2.5 || ^8.0", "symfony/asset": "^4.4 || ^5.0", "symfony/event-dispatcher-contracts": "^1.0 || ^2.0", "symfony/finder": "^4.4 || ^5.0", diff --git a/src/DependencyInjection/OneupUploaderExtension.php b/src/DependencyInjection/OneupUploaderExtension.php index 756d672..889a698 100644 --- a/src/DependencyInjection/OneupUploaderExtension.php +++ b/src/DependencyInjection/OneupUploaderExtension.php @@ -67,8 +67,11 @@ class OneupUploaderExtension extends Extension protected function processOrphanageConfig(): void { + /** @var string $kernelCacheDir */ + $kernelCacheDir = $this->container->getParameter('kernel.cache_dir'); + if ('filesystem' === $this->config['chunks']['storage']['type']) { - $defaultDir = sprintf('%s/uploader/orphanage', $this->container->getParameter('kernel.cache_dir')); + $defaultDir = sprintf('%s/uploader/orphanage', $kernelCacheDir); } else { $defaultDir = 'orphanage'; } @@ -141,6 +144,8 @@ class OneupUploaderExtension extends Extension protected function createChunkStorageService(): void { + /** @var string $kernelCacheDir */ + $kernelCacheDir = $this->container->getParameter('kernel.cache_dir'); $config = &$this->config['chunks']['storage']; $storageClass = sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type']); @@ -148,7 +153,7 @@ class OneupUploaderExtension extends Extension switch ($config['type']) { case 'filesystem': $config['directory'] = null === $config['directory'] ? - sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : + sprintf('%s/uploader/chunks', $kernelCacheDir) : $this->normalizePath($config['directory']) ; @@ -335,9 +340,22 @@ class OneupUploaderExtension extends Extension protected function getTargetDir(): string { - $projectDir = $this->container->hasParameter('kernel.project_dir') ? - $this->container->getParameter('kernel.project_dir') : - $this->container->getParameter('kernel.root_dir') . '/..'; + $projectDir = ''; + + /** @var string $kernelProjectDir */ + $kernelProjectDir = $this->container->getParameter('kernel.project_dir'); + + /** @var string $kernelRootDir */ + $kernelRootDir = $this->container->getParameter('kernel.root_dir'); + + if ($this->container->hasParameter('kernel.project_dir')) { + $projectDir = $kernelProjectDir; + } + + if ($this->container->hasParameter('kernel.root_dir')) { + $projectDir = sprintf('%s/..', $kernelRootDir); + } + $publicDir = sprintf('%s/public', $projectDir); if (!is_dir($publicDir)) { diff --git a/src/Uploader/Chunk/Storage/FlysystemStorage.php b/src/Uploader/Chunk/Storage/FlysystemStorage.php index d551999..50d2d8b 100644 --- a/src/Uploader/Chunk/Storage/FlysystemStorage.php +++ b/src/Uploader/Chunk/Storage/FlysystemStorage.php @@ -102,8 +102,8 @@ class FlysystemStorage implements ChunkStorageInterface if (empty($chunks)) { $target = $filename; } else { - sort($chunks, SORT_STRING | SORT_FLAG_CASE); - $target = pathinfo($chunks[0]['path'], PATHINFO_BASENAME); + sort($chunks, \SORT_STRING | \SORT_FLAG_CASE); + $target = pathinfo($chunks[0]['path'], \PATHINFO_BASENAME); } $mode = 'ab'; diff --git a/src/Uploader/Chunk/Storage/GaufretteStorage.php b/src/Uploader/Chunk/Storage/GaufretteStorage.php index 881724d..581adea 100644 --- a/src/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/src/Uploader/Chunk/Storage/GaufretteStorage.php @@ -136,8 +136,8 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface * therefore the order will be decided depending on the filename * It is only case-insensitive to be overly-careful. */ - sort($chunks, SORT_STRING | SORT_FLAG_CASE); - $target = pathinfo($chunks[0], PATHINFO_BASENAME); + sort($chunks, \SORT_STRING | \SORT_FLAG_CASE); + $target = pathinfo($chunks[0], \PATHINFO_BASENAME); } $dst = $this->filesystem->createStream($path . $target); @@ -197,7 +197,13 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface * failed to upload it will not get mixed together with new one's chunks. */ - return preg_grep('/^.+\/(\d+)_/', $results['keys']); + $chunks = preg_grep('/^.+\/(\d+)_/', $results['keys']); + + if (false === $chunks) { + return []; + } + + return $chunks; } public function getFilesystem(): FilesystemInterface diff --git a/src/Uploader/File/FlysystemFile.php b/src/Uploader/File/FlysystemFile.php index a639923..1324347 100644 --- a/src/Uploader/File/FlysystemFile.php +++ b/src/Uploader/File/FlysystemFile.php @@ -33,12 +33,12 @@ class FlysystemFile extends File implements FileInterface public function getBasename(): string { - return pathinfo($this->getPath(), PATHINFO_BASENAME); + return pathinfo($this->getPath(), \PATHINFO_BASENAME); } public function getExtension(): string { - return pathinfo($this->getPath(), PATHINFO_EXTENSION); + return pathinfo($this->getPath(), \PATHINFO_EXTENSION); } public function getFilesystem(): FilesystemInterface diff --git a/src/Uploader/File/GaufretteFile.php b/src/Uploader/File/GaufretteFile.php index 4406422..82c7664 100644 --- a/src/Uploader/File/GaufretteFile.php +++ b/src/Uploader/File/GaufretteFile.php @@ -66,12 +66,12 @@ class GaufretteFile extends File implements FileInterface public function getPath(): string { - return pathinfo($this->getKey(), PATHINFO_DIRNAME); + return pathinfo($this->getKey(), \PATHINFO_DIRNAME); } public function getBasename(): string { - return pathinfo($this->getKey(), PATHINFO_BASENAME); + return pathinfo($this->getKey(), \PATHINFO_BASENAME); } public function getMimeType(): string @@ -81,7 +81,7 @@ class GaufretteFile extends File implements FileInterface if ($this->filesystem->getAdapter() instanceof StreamFactory && !$this->mimeType) { if ($this->streamWrapperPrefix) { /** @var resource $finfo */ - $finfo = finfo_open(FILEINFO_MIME_TYPE); + $finfo = finfo_open(\FILEINFO_MIME_TYPE); $this->mimeType = (string) finfo_file($finfo, $this->streamWrapperPrefix . $this->getKey()); finfo_close($finfo); } @@ -102,7 +102,7 @@ class GaufretteFile extends File implements FileInterface */ public function getExtension(): string { - return pathinfo($this->getKey(), PATHINFO_EXTENSION); + return pathinfo($this->getKey(), \PATHINFO_EXTENSION); } public function getFilesystem(): FilesystemInterface diff --git a/src/Uploader/Storage/FilesystemOrphanageStorage.php b/src/Uploader/Storage/FilesystemOrphanageStorage.php index 01c1b68..36c587b 100644 --- a/src/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/src/Uploader/Storage/FilesystemOrphanageStorage.php @@ -73,7 +73,9 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageS $return = []; foreach ($files as $file) { - $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), ltrim(str_replace($this->getFindPath(), '', $file), '/')); + $return[] = $this->storage->upload( + new FilesystemFile(new File($file->getPathname())), + ltrim(str_replace($this->getFindPath(), '', (string) $file), '/')); } return $return; diff --git a/tests/Controller/AbstractControllerTest.php b/tests/Controller/AbstractControllerTest.php index 90f84db..0748c6b 100644 --- a/tests/Controller/AbstractControllerTest.php +++ b/tests/Controller/AbstractControllerTest.php @@ -39,7 +39,7 @@ abstract class AbstractControllerTest extends WebTestCase */ protected $helper; - public function setUp(): void + protected function setUp(): void { $this->client = static::createClient(['debug' => false]); $this->client->catchExceptions(false); @@ -64,7 +64,7 @@ abstract class AbstractControllerTest extends WebTestCase $router->getRouteCollection()->all(); } - public function tearDown(): void + protected function tearDown(): void { foreach ($this->createdFiles as $file) { @unlink($file); @@ -155,7 +155,10 @@ abstract class AbstractControllerTest extends WebTestCase protected function getUploadedFiles(): Finder { + /** @var string $env */ $env = self::$container->getParameter('kernel.environment'); + + /** @var string $root */ $root = self::$container->getParameter('kernel.project_dir'); // assemble path diff --git a/tests/Controller/AbstractUploadTest.php b/tests/Controller/AbstractUploadTest.php index e28ed53..aef114a 100644 --- a/tests/Controller/AbstractUploadTest.php +++ b/tests/Controller/AbstractUploadTest.php @@ -12,7 +12,7 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; abstract class AbstractUploadTest extends AbstractControllerTest { - public function setUp(): void + protected function setUp(): void { parent::setUp(); diff --git a/tests/Controller/FileBagExtractorTest.php b/tests/Controller/FileBagExtractorTest.php index d3597fa..6b3d9d7 100644 --- a/tests/Controller/FileBagExtractorTest.php +++ b/tests/Controller/FileBagExtractorTest.php @@ -22,7 +22,7 @@ class FileBagExtractorTest extends TestCase */ protected $mock; - public function setUp(): void + protected function setUp(): void { $controller = AbstractController::class; $mock = $this->getMockBuilder($controller) diff --git a/tests/Uploader/Chunk/Storage/FilesystemStorageTest.php b/tests/Uploader/Chunk/Storage/FilesystemStorageTest.php index ed7df77..ee550a5 100644 --- a/tests/Uploader/Chunk/Storage/FilesystemStorageTest.php +++ b/tests/Uploader/Chunk/Storage/FilesystemStorageTest.php @@ -14,7 +14,7 @@ class FilesystemStorageTest extends ChunkStorageTest */ protected $tmpDir; - public function setUp(): void + protected function setUp(): void { // create a cache dir $tmpDir = sprintf('/tmp/%s', uniqid()); @@ -26,7 +26,7 @@ class FilesystemStorageTest extends ChunkStorageTest $this->storage = new FilesystemStorage($this->tmpDir); } - public function tearDown(): void + protected function tearDown(): void { $system = new Filesystem(); $system->remove($this->tmpDir); diff --git a/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php b/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php index f6656f0..c96f558 100644 --- a/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php +++ b/tests/Uploader/Chunk/Storage/FlysystemStorageTest.php @@ -28,7 +28,7 @@ class FlysystemStorageTest extends ChunkStorageTest */ protected $chunkDir; - public function setUp(): void + protected function setUp(): void { // create a cache dir $parentDir = sprintf('/tmp/%s', uniqid('', true)); @@ -51,7 +51,7 @@ class FlysystemStorageTest extends ChunkStorageTest $system->mkdir($this->tmpDir); } - public function tearDown(): void + protected function tearDown(): void { $system = new Filesystem(); $system->remove($this->parentDir); diff --git a/tests/Uploader/Chunk/Storage/GaufretteStorageTest.php b/tests/Uploader/Chunk/Storage/GaufretteStorageTest.php index c6055f4..3171224 100644 --- a/tests/Uploader/Chunk/Storage/GaufretteStorageTest.php +++ b/tests/Uploader/Chunk/Storage/GaufretteStorageTest.php @@ -26,7 +26,7 @@ class GaufretteStorageTest extends ChunkStorageTest */ protected $chunkDir; - public function setUp(): void + protected function setUp(): void { // create a cache dir $parentDir = sprintf('/tmp/%s', uniqid()); @@ -46,7 +46,7 @@ class GaufretteStorageTest extends ChunkStorageTest $system->mkdir($this->tmpDir); } - public function tearDown(): void + protected function tearDown(): void { $system = new Filesystem(); $system->remove($this->parentDir); diff --git a/tests/Uploader/File/FilesystemFileTest.php b/tests/Uploader/File/FilesystemFileTest.php index 4676772..d73ac35 100644 --- a/tests/Uploader/File/FilesystemFileTest.php +++ b/tests/Uploader/File/FilesystemFileTest.php @@ -9,7 +9,7 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; class FilesystemFileTest extends FileTest { - public function setUp(): void + protected function setUp(): void { $this->path = sys_get_temp_dir() . '/oneup_test_tmp'; @@ -29,7 +29,7 @@ class FilesystemFileTest extends FileTest $this->file = new FilesystemFile($file); } - public function tearDown(): void + protected function tearDown(): void { unlink($this->pathname); rmdir($this->path); diff --git a/tests/Uploader/File/GaufretteFileTest.php b/tests/Uploader/File/GaufretteFileTest.php index 95b96c8..45bd080 100644 --- a/tests/Uploader/File/GaufretteFileTest.php +++ b/tests/Uploader/File/GaufretteFileTest.php @@ -13,7 +13,7 @@ use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; class GaufretteFileTest extends FileTest { - public function setUp(): void + protected function setUp(): void { $adapter = new Adapter(sys_get_temp_dir(), true); $filesystem = new GaufretteFilesystem($adapter); @@ -39,7 +39,7 @@ class GaufretteFileTest extends FileTest $this->file = new GaufretteFile(new File($this->pathname, $filesystem), $filesystem, 'gaufrette://oneup/'); } - public function tearDown(): void + protected function tearDown(): void { unlink(sys_get_temp_dir() . '/' . $this->pathname); rmdir(sys_get_temp_dir() . '/' . $this->path); diff --git a/tests/Uploader/Naming/UrlSafeNamerTest.php b/tests/Uploader/Naming/UrlSafeNamerTest.php index a7da621..275ddd0 100644 --- a/tests/Uploader/Naming/UrlSafeNamerTest.php +++ b/tests/Uploader/Naming/UrlSafeNamerTest.php @@ -11,7 +11,7 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; class UrlSafeNamerTest extends FileTest { - public function setUp(): void + protected function setUp(): void { $this->path = sys_get_temp_dir() . '/oneup_namer_test'; @@ -31,7 +31,7 @@ class UrlSafeNamerTest extends FileTest $this->file = new FilesystemFile($file); } - public function tearDown(): void + protected function tearDown(): void { unlink($this->pathname); rmdir($this->path); diff --git a/tests/Uploader/Orphanage/OrphanageManagerTest.php b/tests/Uploader/Orphanage/OrphanageManagerTest.php index b0e7863..e75977a 100644 --- a/tests/Uploader/Orphanage/OrphanageManagerTest.php +++ b/tests/Uploader/Orphanage/OrphanageManagerTest.php @@ -33,7 +33,7 @@ class OrphanageManagerTest extends TestCase */ protected $mockConfig; - public function setUp(): void + protected function setUp(): void { $this->numberOfOrphans = 10; $this->orphanagePath = sys_get_temp_dir() . '/orphanage'; @@ -54,7 +54,7 @@ class OrphanageManagerTest extends TestCase $this->mockContainer = $this->getContainerMock(); } - public function tearDown(): void + protected function tearDown(): void { $filesystem = new Filesystem(); $filesystem->remove($this->orphanagePath); diff --git a/tests/Uploader/Storage/FilesystemOrphanageStorageTest.php b/tests/Uploader/Storage/FilesystemOrphanageStorageTest.php index d0b19b7..5701f75 100644 --- a/tests/Uploader/Storage/FilesystemOrphanageStorageTest.php +++ b/tests/Uploader/Storage/FilesystemOrphanageStorageTest.php @@ -15,7 +15,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; class FilesystemOrphanageStorageTest extends OrphanageTest { - public function setUp(): void + protected function setUp(): void { $this->numberOfPayloads = 5; $this->tempDirectory = sys_get_temp_dir() . '/orphanage'; diff --git a/tests/Uploader/Storage/FilesystemStorageTest.php b/tests/Uploader/Storage/FilesystemStorageTest.php index 3114849..0d1b49a 100644 --- a/tests/Uploader/Storage/FilesystemStorageTest.php +++ b/tests/Uploader/Storage/FilesystemStorageTest.php @@ -23,7 +23,7 @@ class FilesystemStorageTest extends TestCase */ protected $file; - public function setUp(): void + protected function setUp(): void { $this->directory = sys_get_temp_dir() . '/storage'; @@ -37,7 +37,7 @@ class FilesystemStorageTest extends TestCase fclose($pointer); } - public function tearDown(): void + protected function tearDown(): void { $filesystem = new Filesystem(); $filesystem->remove($this->directory); diff --git a/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index ff2b7b3..94529d6 100644 --- a/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -34,7 +34,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest */ protected $orphanageKey = 'orphanage'; - public function setUp(): void + protected function setUp(): void { $this->numberOfPayloads = 5; $this->realDirectory = sys_get_temp_dir() . '/storage'; @@ -82,7 +82,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest } } - public function tearDown(): void + protected function tearDown(): void { (new Filesystem())->remove($this->realDirectory); diff --git a/tests/Uploader/Storage/FlysystemStorageTest.php b/tests/Uploader/Storage/FlysystemStorageTest.php index e10b68b..42e6b1f 100644 --- a/tests/Uploader/Storage/FlysystemStorageTest.php +++ b/tests/Uploader/Storage/FlysystemStorageTest.php @@ -30,7 +30,7 @@ class FlysystemStorageTest extends TestCase */ protected $file; - public function setUp(): void + protected function setUp(): void { $this->directory = sys_get_temp_dir() . '/storage'; @@ -49,7 +49,7 @@ class FlysystemStorageTest extends TestCase $this->storage = new Storage($filesystem, 100000); } - public function tearDown(): void + protected function tearDown(): void { $filesystem = new Filesystem(); $filesystem->remove($this->directory); diff --git a/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php b/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php index 705462c..46cc9d1 100644 --- a/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php +++ b/tests/Uploader/Storage/GaufretteAmazonS3StorageTest.php @@ -39,7 +39,7 @@ class GaufretteAmazonS3StorageTest extends TestCase */ protected $storage; - public function setUp(): void + protected function setUp(): void { if ( false === getenv('AWS_ACCESS_KEY_ID') || @@ -74,7 +74,7 @@ class GaufretteAmazonS3StorageTest extends TestCase $this->storage = new GaufretteStorage($this->filesystem, 100000, null); } - public function tearDown(): void + protected function tearDown(): void { $files = $this->filesystem->listKeys($this->prefix); foreach ($files['keys'] as $filename) { diff --git a/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php b/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php index 3a5e734..58b6542 100644 --- a/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php +++ b/tests/Uploader/Storage/GaufretteOrphanageStorageTest.php @@ -32,7 +32,7 @@ class GaufretteOrphanageStorageTest extends OrphanageTest */ protected $orphanageKey = 'orphanage'; - public function setUp(): void + protected function setUp(): void { $this->numberOfPayloads = 5; $this->realDirectory = sys_get_temp_dir() . '/storage'; diff --git a/tests/Uploader/Storage/GaufretteStorageTest.php b/tests/Uploader/Storage/GaufretteStorageTest.php index cfc7952..9f0e240 100644 --- a/tests/Uploader/Storage/GaufretteStorageTest.php +++ b/tests/Uploader/Storage/GaufretteStorageTest.php @@ -30,7 +30,7 @@ class GaufretteStorageTest extends TestCase */ protected $storage; - public function setUp(): void + protected function setUp(): void { $this->directory = sys_get_temp_dir() . '/storage'; @@ -49,7 +49,7 @@ class GaufretteStorageTest extends TestCase $this->storage = new GaufretteStorage($filesystem, 100000); } - public function tearDown(): void + protected function tearDown(): void { $filesystem = new Filesystem(); $filesystem->remove($this->directory); diff --git a/tests/Uploader/Storage/OrphanageTest.php b/tests/Uploader/Storage/OrphanageTest.php index 65e9a0e..a596dfe 100644 --- a/tests/Uploader/Storage/OrphanageTest.php +++ b/tests/Uploader/Storage/OrphanageTest.php @@ -42,7 +42,7 @@ abstract class OrphanageTest extends TestCase */ protected $numberOfPayloads; - public function tearDown(): void + protected function tearDown(): void { $filesystem = new Filesystem(); $filesystem->remove($this->tempDirectory);
0
9a7ce2809083774dff173011509f9cf8b1e59749
1up-lab/OneupUploaderBundle
Merge pull request #2 from sheeep/release-1.0 Raised requirement of symfony/framework-bundle to >=2.2.
commit 9a7ce2809083774dff173011509f9cf8b1e59749 (from 80ba434c4bd4bbf0ae5f6fc9d8a0d2fc5726ac0e) Merge: 80ba434 50d14cc Author: mitom <[email protected]> Date: Fri Oct 11 10:33:53 2013 -0700 Merge pull request #2 from sheeep/release-1.0 Raised requirement of symfony/framework-bundle to >=2.2. diff --git a/composer.json b/composer.json index b4a4d15..a6be9f8 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ ], "require": { - "symfony/framework-bundle": "2.*", + "symfony/framework-bundle": ">=2.2", "symfony/finder": ">=2.2.0" },
0
ce217c617551127e198f643cf64236b21e9ecf8e
1up-lab/OneupUploaderBundle
Merge branch 'feature/file-extension-validation' of git://github.com/Lctrs/OneupUploaderBundle into Lctrs-feature/file-extension-validation
commit ce217c617551127e198f643cf64236b21e9ecf8e (from 03231b8e00cee33658243ec2071a1576280e86f5) Merge: 03231b8 60b054a Author: David Greminger <[email protected]> Date: Fri Dec 1 16:45:45 2017 +0100 Merge branch 'feature/file-extension-validation' of git://github.com/Lctrs/OneupUploaderBundle into Lctrs-feature/file-extension-validation diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index ef2d38e..58c295c 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -97,7 +97,16 @@ class Configuration implements ConfigurationInterface ->end() ->end() ->arrayNode('allowed_mimetypes') - ->prototype('scalar')->end() + ->normalizeKeys(false) + ->useAttributeAsKey('type') + ->prototype('array') + ->prototype('scalar') + ->beforeNormalization() + ->ifString() + ->then(function ($v) { return strtolower($v); }) + ->end() + ->end() + ->end() ->end() ->arrayNode('disallowed_mimetypes') ->prototype('scalar')->end() diff --git a/EventListener/AllowedMimetypeAndExtensionValidationListener.php b/EventListener/AllowedMimetypeAndExtensionValidationListener.php new file mode 100644 index 0000000..707563e --- /dev/null +++ b/EventListener/AllowedMimetypeAndExtensionValidationListener.php @@ -0,0 +1,34 @@ +<?php + +namespace Oneup\UploaderBundle\EventListener; + +use Oneup\UploaderBundle\Event\ValidationEvent; +use Oneup\UploaderBundle\Uploader\Exception\ValidationException; + +class AllowedMimetypeAndExtensionValidationListener +{ + public function onValidate(ValidationEvent $event) + { + $config = $event->getConfig(); + $file = $event->getFile(); + + if (empty($config['allowed_mimetypes'])) { + return; + } + + $mimetype = $file->getMimeType(); + $extension = strtolower($file->getExtension()); + + if (!isset($config['allowed_mimetypes'][$mimetype])) { + throw new ValidationException('error.whitelist'); + } + + if (empty($config['allowed_mimetypes'][$mimetype]) + || in_array($extension, $config['allowed_mimetypes'][$mimetype]) + ) { + return; + } + + throw new ValidationException('error.whitelist'); + } +} diff --git a/EventListener/AllowedMimetypeValidationListener.php b/EventListener/AllowedMimetypeValidationListener.php deleted file mode 100644 index 66aa7b9..0000000 --- a/EventListener/AllowedMimetypeValidationListener.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Oneup\UploaderBundle\Event\ValidationEvent; -use Oneup\UploaderBundle\Uploader\Exception\ValidationException; - -class AllowedMimetypeValidationListener -{ - public function onValidate(ValidationEvent $event) - { - $config = $event->getConfig(); - $file = $event->getFile(); - - if (count($config['allowed_mimetypes']) == 0) { - return; - } - - $mimetype = $file->getMimeType(); - - if (!in_array($mimetype, $config['allowed_mimetypes'])) { - throw new ValidationException('error.whitelist'); - } - } -} diff --git a/Resources/config/validators.xml b/Resources/config/validators.xml index 4c3fc73..fefc20e 100644 --- a/Resources/config/validators.xml +++ b/Resources/config/validators.xml @@ -8,7 +8,7 @@ <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - <service id="oneup_uploader.validation_listener.allowed_mimetype" class="Oneup\UploaderBundle\EventListener\AllowedMimetypeValidationListener"> + <service id="oneup_uploader.validation_listener.allowed_mimetype" class="Oneup\UploaderBundle\EventListener\AllowedMimetypeAndExtensionValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index a350ddb..382b566 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -24,7 +24,10 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] + disallowed_mimetypes: [ "image/gif" ] fancyupload: @@ -38,7 +41,9 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] disallowed_mimetypes: [ "image/gif" ] dropzone: @@ -52,7 +57,9 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] disallowed_mimetypes: [ "image/gif" ] yui3: @@ -66,7 +73,9 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] disallowed_mimetypes: [ "image/gif" ] plupload: @@ -80,7 +89,9 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] disallowed_mimetypes: [ "image/gif" ] uploadify: @@ -94,7 +105,9 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] disallowed_mimetypes: [ "image/gif" ] blueimp: @@ -110,7 +123,9 @@ oneup_uploader: directory: %kernel.root_dir%/cache/%kernel.environment%/upload error_handler: oneup_uploader.error_handler.blueimp - allowed_mimetypes: [ "image/jpg", "text/plain" ] + allowed_mimetypes: + image/jpeg : ['jpg', 'jpeg', 'jpe'] + text/plain : ['txt'] disallowed_mimetypes: [ "image/gif" ] mooupload: diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 3688213..fee2f35 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -8,6 +8,7 @@ use Oneup\UploaderBundle\UploadEvents; abstract class AbstractValidationTest extends AbstractControllerTest { abstract protected function getFileWithCorrectMimeType(); + abstract protected function getFileWithCorrectMimeTypeAndIncorrectExtension(); abstract protected function getFileWithIncorrectMimeType(); abstract protected function getOversizedFile(); @@ -85,6 +86,19 @@ abstract class AbstractValidationTest extends AbstractControllerTest } } + public function testAgainstCorrectMimeTypeAndIncorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeTypeAndIncorrectExtension()), $this->requestHeaders); + $response = $client->getResponse(); + + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + public function testAgainstIncorrectMimeType() { $this->markTestSkipped('Mock mime type getter.'); diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index 871e687..ca8c8bd 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -103,12 +103,22 @@ class BlueimpValidationTest extends AbstractValidationTest { return array('files' => array(new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', 128 ))); } + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', + 128 + ); + } + protected function getFileWithIncorrectMimeType() { return array(new UploadedFile( diff --git a/Tests/Controller/DropzoneValidationTest.php b/Tests/Controller/DropzoneValidationTest.php index abe7f06..4b5a87d 100644 --- a/Tests/Controller/DropzoneValidationTest.php +++ b/Tests/Controller/DropzoneValidationTest.php @@ -31,8 +31,18 @@ class DropzoneValidationTest extends AbstractValidationTest { return new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', 128 ); } diff --git a/Tests/Controller/FancyUploadValidationTest.php b/Tests/Controller/FancyUploadValidationTest.php index 1f78228..568f0ce 100644 --- a/Tests/Controller/FancyUploadValidationTest.php +++ b/Tests/Controller/FancyUploadValidationTest.php @@ -31,8 +31,18 @@ class FancyUploadValidationTest extends AbstractValidationTest { return new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', 128 ); } diff --git a/Tests/Controller/FineUploaderValidationTest.php b/Tests/Controller/FineUploaderValidationTest.php index a3b1a7e..fe4d6d9 100644 --- a/Tests/Controller/FineUploaderValidationTest.php +++ b/Tests/Controller/FineUploaderValidationTest.php @@ -31,8 +31,18 @@ class FineUploaderValidationTest extends AbstractValidationTest { return new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', 128 ); } diff --git a/Tests/Controller/PluploadValidationTest.php b/Tests/Controller/PluploadValidationTest.php index c9e9be9..f487f5c 100644 --- a/Tests/Controller/PluploadValidationTest.php +++ b/Tests/Controller/PluploadValidationTest.php @@ -31,8 +31,18 @@ class PluploadValidationTest extends AbstractValidationTest { return new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', 128 ); } diff --git a/Tests/Controller/UploadifyValidationTest.php b/Tests/Controller/UploadifyValidationTest.php index 086267f..de6747c 100644 --- a/Tests/Controller/UploadifyValidationTest.php +++ b/Tests/Controller/UploadifyValidationTest.php @@ -31,8 +31,18 @@ class UploadifyValidationTest extends AbstractValidationTest { return new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', 128 ); } diff --git a/Tests/Controller/YUI3ValidationTest.php b/Tests/Controller/YUI3ValidationTest.php index 2325c61..6977959 100644 --- a/Tests/Controller/YUI3ValidationTest.php +++ b/Tests/Controller/YUI3ValidationTest.php @@ -31,8 +31,18 @@ class YUI3ValidationTest extends AbstractValidationTest { return new UploadedFile( $this->createTempFile(128), - 'cat.ok', - 'image/jpg', + 'cat.txt', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeTypeAndIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txxt', + 'text/plain', 128 ); } commit ce217c617551127e198f643cf64236b21e9ecf8e (from 60b054aece831b7739c7ea7cd942eb01cc610576) Merge: 03231b8 60b054a Author: David Greminger <[email protected]> Date: Fri Dec 1 16:45:45 2017 +0100 Merge branch 'feature/file-extension-validation' of git://github.com/Lctrs/OneupUploaderBundle into Lctrs-feature/file-extension-validation diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 75d3518..487a972 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -113,7 +113,7 @@ abstract class AbstractController if (!($file instanceof FileInterface)) { $file = new FilesystemFile($file); } - $this->validate($file); + $this->validate($file, $request, $response); $this->dispatchPreUploadEvent($file, $response, $request); @@ -169,10 +169,10 @@ abstract class AbstractController } } - protected function validate(FileInterface $file) + protected function validate(FileInterface $file, Request $request, ResponseInterface $response = null) { $dispatcher = $this->container->get('event_dispatcher'); - $event = new ValidationEvent($file, $this->getRequest(), $this->config, $this->type); + $event = new ValidationEvent($file, $request, $this->config, $this->type, $response); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::VALIDATION, $this->type), $event); diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index b4fdc99..feab508 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -2,11 +2,12 @@ namespace Oneup\UploaderBundle\Controller; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; - use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\File\Exception\UploadException; -class DropzoneController extends AbstractController +class DropzoneController extends AbstractChunkedController { public function upload() { @@ -14,9 +15,15 @@ class DropzoneController extends AbstractController $response = new EmptyResponse(); $files = $this->getFiles($request->files); $statusCode = 200; + + $chunked = !is_null($request->request->get('dzchunkindex')); + foreach ($files as $file) { try { - $this->handleUpload($file, $response, $request); + $chunked ? + $this->handleChunkedUpload($file, $response, $request) : + $this->handleUpload($file, $response, $request) + ; } catch (UploadException $e) { $statusCode = 500; //Dropzone displays error if HTTP response is 40x or 50x $this->errorHandler->addException($response, $e); @@ -24,10 +31,26 @@ class DropzoneController extends AbstractController $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); $response = $this->createSupportedJsonResponse(array('error'=>$message )); $response->setStatusCode(400); - return $response; + return $response; } } return $this->createSupportedJsonResponse($response->assemble(), $statusCode); } + + protected function parseChunkedRequest(Request $request) + { + $totalChunkCount = $request->get('dztotalchunkcount'); + $index = $request->get('dzchunkindex'); + $last = ($index + 1) === (int) $totalChunkCount; + $uuid = $request->get('dzuuid'); + + /** + * @var UploadedFile $file + */ + $file = $request->files->get('file')->getClientOriginalName(); + $orig = $file; + + return [$last, $uuid, $index, $orig]; + } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index a26cdde..58c295c 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -75,6 +75,27 @@ class Configuration implements ConfigurationInterface ->end() ->end() ->scalarNode('route_prefix')->defaultValue('')->end() + ->arrayNode('endpoints') + ->beforeNormalization() + ->ifString() + ->then(function ($v) { + if (substr($v, -1) != '/') { + $v .= '/'; + } + return [ + 'upload' => $v.'upload', + 'progress' => $v.'progress', + 'cancel' => $v.'cancel', + ]; + }) + ->end() + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('upload')->defaultNull()->end() + ->scalarNode('progress')->defaultNull()->end() + ->scalarNode('cancel')->defaultNull()->end() + ->end() + ->end() ->arrayNode('allowed_mimetypes') ->normalizeKeys(false) ->useAttributeAsKey('type') diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index c2c14eb..61dc35f 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -84,7 +84,8 @@ class OneupUploaderExtension extends Extension return array($controllerName, array( 'enable_progress' => $mapping['enable_progress'], 'enable_cancelation' => $mapping['enable_cancelation'], - 'route_prefix' => $mapping['route_prefix'] + 'route_prefix' => $mapping['route_prefix'], + 'endpoints' => $mapping['endpoints'], )); } diff --git a/Event/ValidationEvent.php b/Event/ValidationEvent.php index 15e1c18..cff3c99 100644 --- a/Event/ValidationEvent.php +++ b/Event/ValidationEvent.php @@ -3,6 +3,7 @@ namespace Oneup\UploaderBundle\Event; use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\Request; @@ -12,13 +13,15 @@ class ValidationEvent extends Event protected $config; protected $type; protected $request; + protected $response; - public function __construct(FileInterface $file, Request $request, array $config, $type) + public function __construct(FileInterface $file, Request $request, array $config, $type, ResponseInterface $response = null) { $this->file = $file; $this->config = $config; $this->type = $type; $this->request = $request; + $this->response = $response; } public function getFile() @@ -40,4 +43,10 @@ class ValidationEvent extends Event { return $this->request; } + + public function getResponse() + { + return $this->response; + } + } diff --git a/README.md b/README.md index 1daa930..377fb9d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ OneupUploaderBundle =================== -The OneupUploaderBundle for Symfony2 adds support for handling file uploads using one of the following JavaScript libraries, or [your own implementation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_uploader.md). +The OneupUploaderBundle for Symfony adds support for handling file uploads using one of the following JavaScript libraries, or [your own implementation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_uploader.md). * [Dropzone](http://www.dropzonejs.com/) * [jQuery File Upload](http://blueimp.github.io/jQuery-File-Upload/) diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index 1f51fb2..d6aefe2 100644 --- a/Resources/config/errorhandler.xml +++ b/Resources/config/errorhandler.xml @@ -6,6 +6,7 @@ <parameters> <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter> <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter> + <parameter key="oneup_uploader.error_handler.plupload.class">Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler</parameter> <parameter key="oneup_uploader.error_handler.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter> </parameters> @@ -19,8 +20,8 @@ <service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> - <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.dropzone.class%" public="false" /> + <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.plupload.class%" public="false" /> <service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" /> </services> diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index a7cee8a..5e89c4a 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -35,6 +35,10 @@ oneup_uploader: stream_wrapper: ~ sync_buffer_size: 100K route_prefix: + endpoints: + upload: ~ + progress: ~ + cancel: ~ allowed_mimetypes: [] disallowed_mimetypes: [] error_handler: oneup_uploader.error_handler.noop diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 3471492..421b66a 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -53,7 +53,7 @@ And register it in your `services.xml`. ```yml services: - acme_hello.upload_listener: + app.upload_listener: class: AppBundle\EventListener\UploadListener arguments: ["@doctrine.orm.entity_manager"] tags: diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 3942d44..2e5f82e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -34,7 +34,7 @@ Perform the following steps to install and use the basic functionality of the On Add OneupUploaderBundle to your composer.json using the following construct: - $ composer require oneup/uploader-bundle "~1.4" + $ composer require oneup/uploader-bundle Composer will install the bundle to your project's ``vendor/oneup/uploader-bundle`` directory. diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index cd8c070..6dbdc4a 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -30,7 +30,7 @@ class RouteLoader extends Loader $options = $controllerArray[1]; $upload = new Route( - sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), + $options['endpoints']['upload'] ?: sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), array('_controller' => $service . ':upload', '_format' => 'json'), array(), array(), @@ -41,7 +41,7 @@ class RouteLoader extends Loader if ($options['enable_progress'] === true) { $progress = new Route( - sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), + $options['endpoints']['progress'] ?: sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), array('_controller' => $service . ':progress', '_format' => 'json'), array(), array(), @@ -55,7 +55,7 @@ class RouteLoader extends Loader if ($options['enable_cancelation'] === true) { $progress = new Route( - sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), + $options['endpoints']['cancel'] ?: sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), array('_controller' => $service . ':cancel', '_format' => 'json'), array(), array(), diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 95b35ab..d462101 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -15,12 +15,22 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase 'cat' => array($cat, array( 'enable_progress' => false, 'enable_cancelation' => false, - 'route_prefix' => '' + 'route_prefix' => '', + 'endpoints' => array( + 'upload' => null, + 'progress' => null, + 'cancel' => null, + ), )), 'dog' => array($dog, array( 'enable_progress' => true, 'enable_cancelation' => true, - 'route_prefix' => '' + 'route_prefix' => '', + 'endpoints' => array( + 'upload' => null, + 'progress' => null, + 'cancel' => null, + ), )), )); @@ -47,7 +57,12 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase 'cat' => array($cat, array( 'enable_progress' => false, 'enable_cancelation' => false, - 'route_prefix' => $prefix + 'route_prefix' => $prefix, + 'endpoints' => array( + 'upload' => null, + 'progress' => null, + 'cancel' => null, + ), )) )); @@ -61,4 +76,33 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals(0, strpos($route->getPath(), $prefix)); } } + + public function testCustomEndpointRoutes() + { + $customEndpointUpload = '/grumpy/cats/upload'; + $cat = 'GrumpyCatController'; + + $routeLoader = new RouteLoader(array( + 'cat' => array($cat, array( + 'enable_progress' => false, + 'enable_cancelation' => false, + 'route_prefix' => '', + 'endpoints' => array( + 'upload' => $customEndpointUpload, + 'progress' => null, + 'cancel' => null, + ), + )) + )); + + $routes = $routeLoader->load(null); + + foreach ($routes as $route) { + $this->assertInstanceOf('Symfony\Component\Routing\Route', $route); + $this->assertEquals('json', $route->getDefault('_format')); + $this->assertContains('POST', $route->getMethods()); + + $this->assertEquals($customEndpointUpload, $route->getPath()); + } + } } diff --git a/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php index af1f32f..ca14e11 100644 --- a/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php +++ b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php @@ -2,18 +2,22 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\ChunkStorageInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase { protected $tmpDir; + /** + * @var ChunkStorageInterface + */ protected $storage; public function testExistanceOfTmpDir() { $this->assertTrue(is_dir($this->tmpDir)); - $this->assertTrue(is_writeable($this->tmpDir)); + $this->assertTrue(is_writable($this->tmpDir)); } public function testFillOfTmpDir() @@ -30,7 +34,7 @@ abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase public function testChunkCleanup() { // get a manager configured with a max-age of 5 minutes - $maxage = 5 * 60; + $maxage = 5 * 60; $numberOfFiles = 10; $finder = new Finder(); @@ -42,7 +46,7 @@ abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase $this->storage->clear($maxage); $this->assertTrue(is_dir($this->tmpDir)); - $this->assertTrue(is_writeable($this->tmpDir)); + $this->assertTrue(is_writable($this->tmpDir)); $this->assertCount(5, $finder); @@ -66,8 +70,8 @@ abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase { $system = new Filesystem(); - for ($i = 0; $i < $number; $i ++) { - $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid()), time() - $i * 60); + for ($i = 0; $i < $number; ++$i) { + $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid('', true)), time() - $i * 60); } } } diff --git a/Tests/Uploader/Chunk/Storage/FlysystemStorageTest.php b/Tests/Uploader/Chunk/Storage/FlysystemStorageTest.php new file mode 100644 index 0000000..8d553a1 --- /dev/null +++ b/Tests/Uploader/Chunk/Storage/FlysystemStorageTest.php @@ -0,0 +1,48 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; + +use League\Flysystem\Adapter\Local as Adapter; +use League\Flysystem\Filesystem as LeagueFilesystem; +use League\Flysystem\Plugin\ListFiles; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage; +use Symfony\Component\Filesystem\Filesystem; +use Twistor\FlysystemStreamWrapper; + +class FlysystemStorageTest extends ChunkStorageTest +{ + protected $parentDir; + protected $chunkKey = 'chunks'; + protected $chunkDir; + + public function setUp() + { + // create a cache dir + $parentDir = sprintf('/tmp/%s', uniqid('', true)); + + $system = new Filesystem(); + $system->mkdir($parentDir); + + $this->parentDir = $parentDir; + + $adapter = new Adapter($this->parentDir); + + $filesystem = new LeagueFilesystem($adapter); + $filesystem->addPlugin(new ListFiles()); + + FlysystemStreamWrapper::register('tests', $filesystem); + + $this->storage = new FlysystemStorage($filesystem, 100000, 'tests:/', $this->chunkKey); + $this->tmpDir = $this->parentDir.'/'.$this->chunkKey; + + $system->mkdir($this->tmpDir); + } + + public function tearDown() + { + $system = new Filesystem(); + $system->remove($this->parentDir); + + FlysystemStreamWrapper::unregister('tests'); + } +} diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index 102e954..af5a194 100644 --- a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -14,6 +14,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use League\Flysystem\Adapter\Local as Adapter; use League\Flysystem\Filesystem as FSAdapter; use Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage as Storage; +use Twistor\FlysystemStreamWrapper; class FlysystemOrphanageStorageTest extends OrphanageTest { @@ -34,16 +35,14 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $filesystem->mkdir($this->chunkDirectory); $filesystem->mkdir($this->tempDirectory); - if (!$this->checkIfTempnameMatchesAfterCreation()) { - $this->markTestSkipped('Temporary directories do not match'); - } - - $adapter = new Adapter($this->realDirectory, true); + $adapter = new Adapter($this->realDirectory); $filesystem = new FSAdapter($adapter); + FlysystemStreamWrapper::register('tests', $filesystem); + $this->storage = new Storage($filesystem, 100000); - $chunkStorage = new ChunkStorage($filesystem, 100000, null, 'chunks'); + $chunkStorage = new ChunkStorage($filesystem, 100000, 'tests:/', 'chunks'); // create orphanage $session = new Session(new MockArraySessionStorage()); @@ -68,6 +67,13 @@ class FlysystemOrphanageStorageTest extends OrphanageTest } } + public function tearDown() + { + (new Filesystem())->remove($this->realDirectory); + + FlysystemStreamWrapper::unregister('tests'); + } + public function testUpload() { for ($i = 0; $i < $this->numberOfPayloads; $i ++) { @@ -95,9 +101,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $this->assertCount($this->numberOfPayloads, $finder); $finder = new Finder(); - $finder->in($this->realDirectory) - ->exclude(array($this->orphanageKey, $this->chunksKey)) - ->files(); + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); $this->assertCount(0, $finder); $files = $this->orphanage->uploadFiles(); @@ -113,13 +117,4 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $finder->in($this->realDirectory)->files(); $this->assertCount($this->numberOfPayloads, $finder); } - - public function checkIfTempnameMatchesAfterCreation() - { - $testName = tempnam($this->chunkDirectory, 'uploader'); - $result = strpos($testName, $this->chunkDirectory) === 0; - unlink($testName); - - return $result; - } } diff --git a/Uploader/Chunk/Storage/FlysystemStorage.php b/Uploader/Chunk/Storage/FlysystemStorage.php index 19e7a44..77eabc6 100644 --- a/Uploader/Chunk/Storage/FlysystemStorage.php +++ b/Uploader/Chunk/Storage/FlysystemStorage.php @@ -1,13 +1,14 @@ <?php + namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; -use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use League\Flysystem\FileNotFoundException; use League\Flysystem\Filesystem; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; use Symfony\Component\HttpFoundation\File\UploadedFile; class FlysystemStorage implements ChunkStorageInterface { - protected $unhandledChunk; protected $prefix; protected $streamWrapperPrefix; @@ -21,12 +22,8 @@ class FlysystemStorage implements ChunkStorageInterface public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) { - if ( - ! method_exists($filesystem, 'readStream') - || - ! method_exists($filesystem, 'putStream') - ) { - throw new \InvalidArgumentException('The filesystem used as chunk storage must streamable'); + if (null === $streamWrapperPrefix) { + throw new \InvalidArgumentException('Stream wrapper must be configured.'); } $this->filesystem = $filesystem; @@ -37,8 +34,8 @@ class FlysystemStorage implements ChunkStorageInterface public function clear($maxAge, $prefix = null) { - $prefix = $prefix ? :$this->prefix; - $matches = $this->filesystem->listFiles($prefix); + $prefix = $prefix ?: $this->prefix; + $matches = $this->filesystem->listContents($prefix, true); $now = time(); $toDelete = array(); @@ -47,24 +44,20 @@ class FlysystemStorage implements ChunkStorageInterface // this also means the files inside are old // but after the files are deleted the dirs // would remain - foreach ($matches['dirs'] as $key) { - if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { - $toDelete[] = $key; - } - } - // The same directory is returned for every file it contains - array_unique($toDelete); - foreach ($matches['keys'] as $key) { - if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { - $this->filesystem->delete($key); + foreach ($matches as $key) { + $path = $key['path']; + $timestamp = isset($key['timestamp']) ? $key['timestamp'] : $this->filesystem->getTimestamp($path); + + if ($maxAge <= $now - $timestamp) { + $toDelete[] = $path; } } - foreach ($toDelete as $key) { + foreach ($toDelete as $path) { // The filesystem will throw exceptions if // a directory is not empty try { - $this->filesystem->delete($key); + $this->filesystem->delete($path); } catch (\Exception $e) { continue; } @@ -77,7 +70,7 @@ class FlysystemStorage implements ChunkStorageInterface 'uuid' => $uuid, 'index' => $index, 'chunk' => $chunk, - 'original' => $original + 'original' => $original, ); } @@ -91,21 +84,26 @@ class FlysystemStorage implements ChunkStorageInterface $target = $filename; } else { sort($chunks, SORT_STRING | SORT_FLAG_CASE); - $target = pathinfo($chunks[0], PATHINFO_BASENAME); + $target = pathinfo($chunks[0]['path'], PATHINFO_BASENAME); } - - if ($this->unhandledChunk['index'] === 0) { + $mode = 'ab'; + if (0 === $this->unhandledChunk['index']) { // if it's the first chunk overwrite the already existing part // to avoid appending to earlier failed uploads - $handle = fopen($path . '/' . $target, 'w'); - } else { - $handle = fopen($path . '/' . $target, 'a'); + $mode = 'wb'; } - $this->filesystem->putStream($path . $target, $handle); + $file = fopen($this->unhandledChunk['chunk']->getPathname(), 'rb'); + $dest = fopen($this->streamWrapperPrefix.'/'.$path.$target, $mode); + + stream_copy_to_stream($file, $dest); + + fclose($file); + fclose($dest); + if ($renameChunk) { - $name = preg_replace('/^(\d+)_/', '', $target); + $name = $this->unhandledChunk['original']; /* The name can only match if the same user in the same session is * trying to upload a file under the same name AND the previous upload failed, * somewhere between this function, and the cleanup call. If that happened @@ -130,13 +128,16 @@ class FlysystemStorage implements ChunkStorageInterface public function cleanup($path) { - $this->filesystem->delete($path); + try { + $this->filesystem->delete($path); + } catch (FileNotFoundException $e) { + // File already gone. + } } public function getChunks($uuid) { - $results = $this->filesystem->listFiles($this->prefix.'/'.$uuid); - return preg_grep('/^.+\/(\d+)_/', $results['keys']); + return $this->filesystem->listFiles($this->prefix.'/'.$uuid); } public function getFilesystem() @@ -148,5 +149,4 @@ class FlysystemStorage implements ChunkStorageInterface { return $this->streamWrapperPrefix; } - } diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index 9d22fd6..d7f581b 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -3,10 +3,10 @@ namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; use Gaufrette\Adapter\StreamFactory; +use Gaufrette\Filesystem; +use Gaufrette\FilesystemInterface; use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; -use Gaufrette\Filesystem; - use Oneup\UploaderBundle\Uploader\Gaufrette\StreamManager; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -16,13 +16,27 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface protected $prefix; protected $streamWrapperPrefix; - public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) + /** + * @param FilesystemInterface|Filesystem $filesystem + * @param int $bufferSize + * @param string $streamWrapperPrefix + * @param string $prefix + */ + public function __construct($filesystem, $bufferSize, $streamWrapperPrefix, $prefix) { + $base = interface_exists('Gaufrette\FilesystemInterface') + ? 'Gaufrette\FilesystemInterface' + : 'Gaufrette\Filesystem'; + + if (!$filesystem instanceof $base) { + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, is_object($filesystem) ? get_class($filesystem) : gettype($filesystem))); + } + if (!($filesystem->getAdapter() instanceof StreamFactory)) { throw new \InvalidArgumentException('The filesystem used as chunk storage must implement StreamFactory'); } $this->filesystem = $filesystem; - $this->bufferSize = $bufferSize; + $this->buffersize = $bufferSize; $this->prefix = $prefix; $this->streamWrapperPrefix = $streamWrapperPrefix; } diff --git a/Uploader/ErrorHandler/PluploadErrorHandler.php b/Uploader/ErrorHandler/PluploadErrorHandler.php new file mode 100644 index 0000000..6716c87 --- /dev/null +++ b/Uploader/ErrorHandler/PluploadErrorHandler.php @@ -0,0 +1,19 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Exception; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class PluploadErrorHandler implements ErrorHandlerInterface +{ + public function addException(AbstractResponse $response, Exception $exception) + { + /* Plupload only needs an error message so it can be handled client side */ + $message = $exception->getMessage(); + $response['error'] = $message; + } +} + +?> diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php index 39c9234..1d38ab8 100644 --- a/Uploader/File/GaufretteFile.php +++ b/Uploader/File/GaufretteFile.php @@ -4,16 +4,30 @@ namespace Oneup\UploaderBundle\Uploader\File; use Gaufrette\Adapter\StreamFactory; use Gaufrette\File; -use Gaufrette\Filesystem; use Gaufrette\Adapter\AwsS3; +use Gaufrette\Filesystem; +use Gaufrette\FilesystemInterface; class GaufretteFile extends File implements FileInterface { protected $streamWrapperPrefix; protected $mimeType; - public function __construct(File $file, Filesystem $filesystem, $streamWrapperPrefix = null) + /** + * @param File $file + * @param FilesystemInterface|Filesystem $filesystem + * @param string|null $streamWrapperPrefix + */ + public function __construct(File $file, $filesystem, $streamWrapperPrefix = null) { + $base = interface_exists('Gaufrette\FilesystemInterface') + ? 'Gaufrette\FilesystemInterface' + : 'Gaufrette\Filesystem'; + + if (!$filesystem instanceof $base) { + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, is_object($filesystem) ? get_class($filesystem) : gettype($filesystem))); + } + parent::__construct($file->getKey(), $filesystem); $this->streamWrapperPrefix = $streamWrapperPrefix; } diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php index 7fcc83a..e745eef 100644 --- a/Uploader/Gaufrette/StreamManager.php +++ b/Uploader/Gaufrette/StreamManager.php @@ -46,7 +46,7 @@ class StreamManager $this->openStream($src, 'r'); while (!$src->eof()) { - $data = $src->read($this->bufferSize); + $data = $src->read($this->buffersize); $dst->write($data); } diff --git a/Uploader/Storage/FlysystemOrphanageStorage.php b/Uploader/Storage/FlysystemOrphanageStorage.php index 376deb5..6cc00ab 100644 --- a/Uploader/Storage/FlysystemOrphanageStorage.php +++ b/Uploader/Storage/FlysystemOrphanageStorage.php @@ -40,8 +40,9 @@ class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageSto public function upload(FileInterface $file, $name, $path = null) { - if(!$this->session->isStarted()) + if (!$this->session->isStarted()) { throw new \RuntimeException('You need a running session in order to run the Orphanage.'); + } return parent::upload($file, $name, $this->getPath()); } diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index 08e6206..c3783ac 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -3,13 +3,14 @@ namespace Oneup\UploaderBundle\Uploader\Storage; use League\Flysystem\Filesystem; +use League\Flysystem\MountManager; use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Oneup\UploaderBundle\Uploader\File\FlysystemFile; use Symfony\Component\Filesystem\Filesystem as LocalFilesystem; class FlysystemStorage implements StorageInterface { - /** * @var null|string */ @@ -34,32 +35,37 @@ class FlysystemStorage implements StorageInterface public function upload(FileInterface $file, $name, $path = null) { - $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); + $path = null === $path ? $name : sprintf('%s/%s', $path, $name); - if ($file instanceof FlysystemFile) { - if ($file->getFilesystem() == $this->filesystem) { - $file->getFilesystem()->rename($file->getPath(), $path); + if ($file instanceof FilesystemFile) { + $stream = fopen($file->getPathname(), 'rb+'); + $this->filesystem->putStream($path, $stream, array( + 'mimetype' => $file->getMimeType() + )); - return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + if (is_resource($stream)) { + fclose($stream); } - } - - $stream = fopen($file->getPathname(), 'r+'); - $this->filesystem->putStream($path, $stream, array( - 'mimetype' => $file->getMimeType() - )); - if (is_resource($stream)) { - fclose($stream); - } - if ($file instanceof FlysystemFile) { - $file->delete(); - } else { $filesystem = new LocalFilesystem(); $filesystem->remove($file->getPathname()); + + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); } + if ($file instanceof FlysystemFile && $file->getFilesystem() === $this->filesystem) { + $file->getFilesystem()->rename($file->getPath(), $path); + + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + } + + $manager = new MountManager([ + 'chunks' => $file->getFilesystem(), + 'dest' => $this->filesystem, + ]); + + $manager->move(sprintf('chunks://%s', $file->getPathname()), sprintf('dest://%s', $path)); + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); } - } diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index 4be4daa..b003236 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -4,7 +4,6 @@ namespace Oneup\UploaderBundle\Uploader\Storage; use Gaufrette\File; use Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage as GaufretteChunkStorage; -use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; use Symfony\Component\HttpFoundation\Session\SessionInterface; @@ -30,7 +29,7 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto * initiate the storage on the chunk storage's filesystem * the stream wrapper is useful for metadata. */ - parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, $chunkStorage->getStreamWrapperPrefix()); + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->buffersize, $chunkStorage->getStreamWrapperPrefix()); $this->storage = $storage; $this->chunkStorage = $chunkStorage; diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 7b9bc7e..d83687e 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; +use Gaufrette\FilesystemInterface; use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; use Gaufrette\Filesystem; @@ -13,10 +14,23 @@ class GaufretteStorage extends StreamManager implements StorageInterface { protected $streamWrapperPrefix; - public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix = null) + /** + * @param FilesystemInterface|Filesystem $filesystem + * @param int $bufferSize + * @param string|null $streamWrapperPrefix + */ + public function __construct($filesystem, $bufferSize, $streamWrapperPrefix = null) { + $base = interface_exists('Gaufrette\FilesystemInterface') + ? 'Gaufrette\FilesystemInterface' + : 'Gaufrette\Filesystem'; + + if (!$filesystem instanceof $base) { + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, is_object($filesystem) ? get_class($filesystem) : gettype($filesystem))); + } + $this->filesystem = $filesystem; - $this->bufferSize = $bufferSize; + $this->buffersize = $bufferSize; $this->streamWrapperPrefix = $streamWrapperPrefix; } diff --git a/composer.json b/composer.json index ab88f2d..d68b779 100644 --- a/composer.json +++ b/composer.json @@ -27,17 +27,19 @@ "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", "knplabs/gaufrette": "0.2.*@dev", - "symfony/class-loader": "2.*|^3.0", - "symfony/security-bundle": "2.*|^3.0", + "oneup/flysystem-bundle": "^1.2", + "phpunit/phpunit": "^4.4", "sensio/framework-extra-bundle": "2.*|^3.0", "symfony/browser-kit": "2.*|^3.0", - "phpunit/phpunit": "^4.4", - "oneup/flysystem-bundle": "^1.2" + "symfony/class-loader": "2.*|^3.0", + "symfony/security-bundle": "2.*|^3.0", + "twistor/flysystem-stream-wrapper": "^1.0" }, "suggest": { "knplabs/knp-gaufrette-bundle": "0.1.*", - "oneup/flysystem-bundle": "^1.2" + "oneup/flysystem-bundle": "^1.2", + "twistor/flysystem-stream-wrapper": "^1.0 (Required when using Flysystem)" }, "autoload": {
0
4edc094ed4988aee1fca6f19a67ca8649341c761
1up-lab/OneupUploaderBundle
Update frontend_dropzone.md
commit 4edc094ed4988aee1fca6f19a67ca8649341c761 Author: darthf1 <[email protected]> Date: Wed Mar 2 15:20:46 2016 +0100 Update frontend_dropzone.md diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md index 66fc318..b0fd9b1 100644 --- a/Resources/doc/frontend_dropzone.md +++ b/Resources/doc/frontend_dropzone.md @@ -4,7 +4,7 @@ Use Dropzone in your Symfony2 application Download [Dropzone](http://www.dropzonejs.com/) and include it in your template. Connect the `action` property of the form to the dynamic route `_uploader_{mapping_name}`. ```html -<script type="text/javascript" src="https://rawgithub.com/enyo/dropzone/master/downloads/dropzone.js"></script> +<script type="text/javascript" src="https://raw.githubusercontent.com/enyo/dropzone/master/dist/dropzone.js"></script> <form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone"> </form>
0
e3026276c3009cd92bb77726beae4144444ca53d
1up-lab/OneupUploaderBundle
Added service_container to the list of arguments of the default UploaderController.
commit e3026276c3009cd92bb77726beae4144444ca53d Author: Jim Schmid <[email protected]> Date: Mon Mar 11 19:09:38 2013 +0100 Added service_container to the list of arguments of the default UploaderController. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index c33e281..a511e00 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -5,14 +5,20 @@ namespace Oneup\UploaderBundle\Controller; class UploaderController { protected $mappings; + protected $container; - public function __construct($mappings) + public function __construct($mappings, $container) { - $this->mappings = $mappings; + $this->mappings = $mappings; + $this->container = $container; } public function upload($mapping) { + $container = $this->container; + $config = $this->mappings[$mapping]; + if(!$container->has($config['storage'])) + throw new \InvalidArgumentException(sprintf('The storage service "%s" must be defined.')); } } \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index e440170..dc79a38 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -17,6 +17,7 @@ <!-- controller --> <service id="oneup_uploader.controller" class="%oneup_uploader.controller.class%"> <argument>%oneup_uploader.mappings%</argument> + <argument type="service" id="service_container" /> </service> <!-- routing -->
0
44c64391b5901555d66b508f64802731cefee7b7
1up-lab/OneupUploaderBundle
Implemented FancyUpload.
commit 44c64391b5901555d66b508f64802731cefee7b7 Author: Jim Schmid <[email protected]> Date: Thu Apr 11 22:31:15 2013 +0200 Implemented FancyUpload. diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php new file mode 100644 index 0000000..ee69af0 --- /dev/null +++ b/Controller/FancyUploadController.php @@ -0,0 +1,40 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\Controller\AbstractController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class FancyUploadController extends AbstractController +{ + public function upload() + { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new EmptyResponse(); + $files = $request->files; + + foreach($files as $file) + { + try + { + $uploaded = $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + } + + return new JsonResponse($response->assemble()); + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 7298bec..b97806e 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/Resources/config/frontend_fancyupload.md b/Resources/config/frontend_fancyupload.md new file mode 100644 index 0000000..bad221a --- /dev/null +++ b/Resources/config/frontend_fancyupload.md @@ -0,0 +1,106 @@ +Use FancyUpload +============= + +Download [FancyUpload](http://digitarald.de/project/fancyupload/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}` and include the FlashUploader file (`path`). + +```html + +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.2/mootools.js"></script> +<script type="text/javascript" src="{{ asset('bundles/acmedemo/js/Swiff.Uploader.js') }}"></script> +<script type="text/javascript" src="{{ asset('bundles/acmedemo/js/Fx.ProgressBar.js') }}"></script> +<script type="text/javascript" src="{{ asset('bundles/acmedemo/js/FancyUpload2.js') }}"></script> + +<script type="text/javascript"> +window.addEvent('domready', function() +{ + var uploader = new FancyUpload2($('demo-status'), $('demo-list'), + { + url: $('form-demo').action, + fieldName: 'photoupload', + path: "{{ asset('bundles/acmedemo/js/Swiff.Uploader.swf') }}", + limitSize: 2 * 1024 * 1024, + onLoad: function() { + $('demo-status').removeClass('hide'); + $('demo-fallback').destroy(); + }, + debug: true, + target: 'demo-browse' + }); + + $('demo-browse').addEvent('click', function() + { + swiffy.browse(); + return false; + }); + + $('demo-select-images').addEvent('change', function() + { + var filter = null; + if (this.checked) { + filter = {'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'}; + } + uploader.options.typeFilter = filter; + }); + + $('demo-clear').addEvent('click', function() + { + uploader.removeFile(); + return false; + }); + + $('demo-upload').addEvent('click', function() + { + uploader.upload(); + return false; + }); +}); +</script> + + +<form action="{{ path('_uploader_gallery') }}" method="post" enctype="multipart/form-data" id="form-demo"> + <fieldset id="demo-fallback"> + <legend>File Upload</legend> + <p> + Selected your photo to upload.<br /> + <strong>This form is just an example fallback for the unobtrusive behaviour of FancyUpload.</strong> + </p> + <label for="demo-photoupload"> + Upload Photos: + <input type="file" name="photoupload" id="demo-photoupload" /> + </label> + </fieldset> + + <div id="demo-status" class="hide"> + <p> + <a href="#" id="demo-browse">Browse Files</a> | + <input type="checkbox" id="demo-select-images" /> Images Only | + <a href="#" id="demo-clear">Clear List</a> | + <a href="#" id="demo-upload">Upload</a> + </p> + <div> + <strong class="overall-title">Overall progress</strong><br /> + <img src="{{ asset('bundles/acmedemo/images/progress-bar/bar.gif') }}" class="progress overall-progress" /> + </div> + <div> + <strong class="current-title">File Progress</strong><br /> + <img src="{{ asset('bundles/acmedemo/images/progress-bar/bar.gif') }}" class="progress current-progress" /> + </div> + <div class="current-text"></div> + </div> + <ul id="demo-list"></ul> +</form> + +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: fancyupload +``` + +Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 6933114..1a1108d 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -15,6 +15,7 @@ <parameter key="oneup_uploader.controller.blueimp.class">Oneup\UploaderBundle\Controller\BlueimpController</parameter> <parameter key="oneup_uploader.controller.uploadify.class">Oneup\UploaderBundle\Controller\UploadifyController</parameter> <parameter key="oneup_uploader.controller.yui3.class">Oneup\UploaderBundle\Controller\YUI3Controller</parameter> + <parameter key="oneup_uploader.controller.fancyupload.class">Oneup\UploaderBundle\Controller\FancyUploadController</parameter> </parameters> <services>
0
3deab3fb31c81f71beb2101fe71218eb9d80eec1
1up-lab/OneupUploaderBundle
Short link to PR
commit 3deab3fb31c81f71beb2101fe71218eb9d80eec1 Author: David Greminger <[email protected]> Date: Thu Jan 28 16:05:48 2016 +0100 Short link to PR diff --git a/README.md b/README.md index 8e23bc0..3384dae 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- -* Version **1.5.0** supports now [Flysystem](https://github.com/1up-lab/OneupFlysystemBundle) (Thank you @[lsv](https://github.com/lsv)! PR is [here](https://github.com/1up-lab/OneupUploaderBundle/pull/213)) and is no longer compatible with PHP 5.3 (it's [EOL](http://php.net/eol.php) since August 2014 anyway). +* Version **1.5.0** supports now [Flysystem](https://github.com/1up-lab/OneupFlysystemBundle) (Thank you @[lsv](https://github.com/lsv)! PR #213) and is no longer compatible with PHP 5.3 (it's [EOL](http://php.net/eol.php) since August 2014 anyway). * Version **v1.0.0** introduced some backward compatibility breaks. For a full list of changes, head to the [dedicated pull request](https://github.com/1up-lab/OneupUploaderBundle/pull/57). * If you're using chunked uploads consider upgrading from **v0.9.6** to **v0.9.7**. A critical issue was reported regarding the assembly of chunks. More information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21#issuecomment-21560320). * Error management [changed](https://github.com/1up-lab/OneupUploaderBundle/pull/25) in Version **0.9.6**. You can now register an `ErrorHandler` per configured frontend. This comes bundled with some adjustments to the `blueimp` controller. More information is available in [the documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_error_handler.md).
0
131ad19813cd2be8ee6a8e81391c984da90b74aa
1up-lab/OneupUploaderBundle
XML services translated to yml
commit 131ad19813cd2be8ee6a8e81391c984da90b74aa Author: Martin Aarhof <[email protected]> Date: Thu Dec 17 18:52:36 2015 +0100 XML services translated to yml diff --git a/Resources/doc/custom_error_handler.md b/Resources/doc/custom_error_handler.md index 4110836..69bedfa 100644 --- a/Resources/doc/custom_error_handler.md +++ b/Resources/doc/custom_error_handler.md @@ -33,6 +33,12 @@ Define a service for your class. </services> ``` +```yml +services: + acme_demo.custom_error_handler: + class: Acme\DemoBundle\ErrorHandler\CustomErrorHandler +``` + And configure the mapping to use your shiny new service. ```yml diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 88c6d71..b91091e 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -40,6 +40,15 @@ And register it in your `services.xml`. </services> ``` +```yml +services: + acme_hello.upload_listener: + class: Acme\HelloBundle\EventListener\UploadListener + argument: ["@doctrine"] + tags: + - { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload } +``` + You can now implement you custom logic in the `onUpload` method of your EventListener. ## Use custom input data diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index 9b59e58..ffc7a03 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -34,13 +34,19 @@ Next, register your created namer as a service in your `services.xml` </services> ``` +```yml +acme_demo.custom_namer: + class: Acme\DemoBundle\CatNamer +``` + Now you can use your custom service by adding it to your configuration: ```yml -oneup_uploader: - mappings: - gallery: - namer: acme_demo.custom_namer +services: + oneup_uploader: + mappings: + gallery: + namer: acme_demo.custom_namer ``` Every file uploaded through the `Controller` of this mapping will be named with your custom namer. diff --git a/Resources/doc/custom_validator.md b/Resources/doc/custom_validator.md index 1f0ef03..2d5b5f0 100644 --- a/Resources/doc/custom_validator.md +++ b/Resources/doc/custom_validator.md @@ -45,3 +45,11 @@ After that register your new `EventListener` in the `services.xml` of your appli </services> </container> ``` + +```yml +services: + acme_demo.always_false_listener: + class: Acme\DemoBundle\EventListener\AlwaysFalseValidationListener + tags: + - { name: kernel.event_listener, event: oneup_uploader.validation, method: onValidate } +```
0
a456bb6062bb18dedb2c2487def53a875561cd75
1up-lab/OneupUploaderBundle
Reintroducing POST_UPLOAD event.
commit a456bb6062bb18dedb2c2487def53a875561cd75 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 11:37:44 2013 +0100 Reintroducing POST_UPLOAD event. diff --git a/Event/PostUploadEvent.php b/Event/PostUploadEvent.php new file mode 100644 index 0000000..76d4e70 --- /dev/null +++ b/Event/PostUploadEvent.php @@ -0,0 +1,30 @@ +<?php + +namespace Oneup\UploaderBundle\Event; + +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\HttpFoundation\Request; + +use Symfony\Component\HttpFoundation\File\File; + +class PostUploadEvent extends Event +{ + protected $file; + protected $request; + + public function __construct(File $file, Request $request) + { + $this->file = $file; + $this->request = $request; + } + + public function getFile() + { + return $this->file; + } + + public function getRequest() + { + return $this->request; + } +} \ No newline at end of file diff --git a/UploadEvents.php b/UploadEvents.php index c319ce9..4e90860 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -4,5 +4,6 @@ namespace Oneup\UploaderBundle; final class UploadEvents { - const POST_PERSIST = 'oneup.uploader.post.perist'; + const POST_PERSIST = 'oneup.uploader.post.persist'; + const POST_UPLOAD = 'oneup.uploader.post.upload': } \ No newline at end of file
0
ced5635c00f4bb9db4f76804b9e5d3345f54c948
1up-lab/OneupUploaderBundle
Added validator to validate allowed extensions.
commit ced5635c00f4bb9db4f76804b9e5d3345f54c948 Author: Jim Schmid <[email protected]> Date: Mon Apr 22 19:22:43 2013 +0200 Added validator to validate allowed extensions. diff --git a/EventListener/AllowedExtensionValidationListener.php b/EventListener/AllowedExtensionValidationListener.php new file mode 100644 index 0000000..69ab16a --- /dev/null +++ b/EventListener/AllowedExtensionValidationListener.php @@ -0,0 +1,21 @@ +<?php + +namespace Oneup\UploaderBundle\EventListener; + +use Oneup\UploaderBundle\Event\ValidationEvent; +use Oneup\UploaderBundle\Uploader\Exception\ValidationException; + +class AllowedExtensionValidationListener +{ + public function onValidate(ValidationEvent $event) + { + $config = $event->getConfig(); + $file = $event->getFile(); + + $extension = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); + + if(count($config['allowed_extensions']) > 0 && !in_array($extension, $config['allowed_extensions'])) { + throw new ValidationException('error.whitelist'); + } + } +} \ No newline at end of file diff --git a/Resources/config/validation.xml b/Resources/config/validation.xml index ac5322b..a272a48 100644 --- a/Resources/config/validation.xml +++ b/Resources/config/validation.xml @@ -6,7 +6,11 @@ <services> - <service id="oneup_uploader.validation.max_size_listener" class="Oneup\UploaderBundle\EventListener\MaxSizeValidationListener"> + <service id="oneup_uploader.validation_listener.max_size" class="Oneup\UploaderBundle\EventListener\MaxSizeValidationListener"> + <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> + </service> + + <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service>
0
00bff0181fc1592134f1aa36469ea44d69585a9a
1up-lab/OneupUploaderBundle
Merge pull request #115 from mvrhov/filteredOrphanege Allow uploading only of specific files
commit 00bff0181fc1592134f1aa36469ea44d69585a9a (from 223e4369af3adc417bdeb7bc2c5a34e831022232) Merge: 223e436 9ec857a Author: Jim Schmid <[email protected]> Date: Fri Jul 4 16:58:01 2014 +0200 Merge pull request #115 from mvrhov/filteredOrphanege Allow uploading only of specific files diff --git a/Uploader/Storage/FilesystemOrphanageStorage.php b/Uploader/Storage/FilesystemOrphanageStorage.php index 8a2e0e4..ed6e4f6 100644 --- a/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -39,10 +39,12 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageS return parent::upload($file, $name, $this->getPath()); } - public function uploadFiles() + public function uploadFiles(array $files = null) { try { - $files = $this->getFiles(); + if (null === $files) { + $files = $this->getFiles(); + } $return = array(); foreach ($files as $file) { diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index d5a9489..4be4daa 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -47,10 +47,12 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto return parent::upload($file, $name, $this->getPath()); } - public function uploadFiles() + public function uploadFiles(array $files = null) { try { - $files = $this->getFiles(); + if (null === $files) { + $files = $this->getFiles(); + } $return = array(); foreach ($files as $key => $file) { diff --git a/Uploader/Storage/OrphanageStorageInterface.php b/Uploader/Storage/OrphanageStorageInterface.php index 35e275f..82be28c 100644 --- a/Uploader/Storage/OrphanageStorageInterface.php +++ b/Uploader/Storage/OrphanageStorageInterface.php @@ -6,5 +6,5 @@ use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; interface OrphanageStorageInterface extends StorageInterface { - public function uploadFiles(); + public function uploadFiles(array $files = null); } commit 00bff0181fc1592134f1aa36469ea44d69585a9a (from 9ec857a0224d0278712462f9ecbc52507e3d5ebe) Merge: 223e436 9ec857a Author: Jim Schmid <[email protected]> Date: Fri Jul 4 16:58:01 2014 +0200 Merge pull request #115 from mvrhov/filteredOrphanege Allow uploading only of specific files diff --git a/.gitignore b/.gitignore index 7c766c7..6b0fe35 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,6 @@ phpunit.xml vendor log Tests/App/cache -Tests/App/logs \ No newline at end of file +Tests/App/logs + +.idea \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 3381bd6..e3c5391 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,9 +5,9 @@ php: - 5.4 env: - - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* - SYMFONY_VERSION=2.4.* + - SYMFONY_VERSION=2.5.* before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source diff --git a/Resources/doc/index.md b/Resources/doc/index.md index e9469ad..2e90a51 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -34,7 +34,7 @@ Add OneupUploaderBundle to your composer.json using the following construct: ```js { "require": { - "oneup/uploader-bundle": "1.0.*@dev" + "oneup/uploader-bundle": "~1.3" } } ``` diff --git a/Resources/doc/orphanage.md b/Resources/doc/orphanage.md index b489535..6848615 100644 --- a/Resources/doc/orphanage.md +++ b/Resources/doc/orphanage.md @@ -53,7 +53,7 @@ class AcmeController extends Controller You will get an array containing the moved files. -> If you are using Gaufrette, these files are instances of `Gaufrette\File`, otherwise `Symfony\Component\HttpFoundation\File\File`. +> If you are using Gaufrette, these files are instances of `Gaufrette\File`, otherwise `SplFileInfo`. ## Configure the Orphanage You can configure the `Orphanage` by using the following configuration parameters. diff --git a/Uploader/Storage/FilesystemOrphanageStorage.php b/Uploader/Storage/FilesystemOrphanageStorage.php index 03981f7..ed6e4f6 100644 --- a/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -60,7 +60,15 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageS public function getFiles() { $finder = new Finder(); - $finder->in($this->getFindPath())->files(); + try { + $finder->in($this->getFindPath())->files(); + } catch (\InvalidArgumentException $e) { + //catch non-existing directory exception. + //This can happen if getFiles is called and no file has yet been uploaded + + //push empty array into the finder so we can emulate no files found + $finder->append(array()); + } return $finder; } diff --git a/composer.json b/composer.json index a6be9f8..aa66e5d 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,7 @@ "symfony/security-bundle": "2.*", "sensio/framework-extra-bundle": "2.*", "symfony/browser-kit": "2.*", - "phpunit/phpunit": "3.7.*" + "phpunit/phpunit": "~4.1" }, "suggest": {
0
fa28731786627e4378a205e6c2a265c404e19204
1up-lab/OneupUploaderBundle
Update bundle configuration for Symfony 4.2 change, see https://github.com/symfony/symfony/blob/master/UPGRADE-4.2.md#config)
commit fa28731786627e4378a205e6c2a265c404e19204 Author: David Greminger <[email protected]> Date: Mon Dec 3 09:32:12 2018 +0100 Update bundle configuration for Symfony 4.2 change, see https://github.com/symfony/symfony/blob/master/UPGRADE-4.2.md#config) diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index cf88563..cb39ca1 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -9,8 +9,14 @@ class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('oneup_uploader'); + $treeBuilder = new TreeBuilder('oneup_uploader'); + + if (method_exists($treeBuilder, 'getRootNode')) { + $rootNode = $treeBuilder->getRootNode(); + } else { + // BC layer for symfony/config 4.1 and older + $rootNode = $treeBuilder->root('oneup_uploader'); + } $rootNode ->children()
0
3d711a21d4a983443797b83bd763557067e72b85
1up-lab/OneupUploaderBundle
Swap order of condition (#402)
commit 3d711a21d4a983443797b83bd763557067e72b85 Author: David Greminger <[email protected]> Date: Thu Feb 11 12:45:51 2021 +0100 Swap order of condition (#402) diff --git a/src/DependencyInjection/OneupUploaderExtension.php b/src/DependencyInjection/OneupUploaderExtension.php index b688707..ab33a88 100644 --- a/src/DependencyInjection/OneupUploaderExtension.php +++ b/src/DependencyInjection/OneupUploaderExtension.php @@ -342,13 +342,6 @@ class OneupUploaderExtension extends Extension { $projectDir = ''; - if ($this->container->hasParameter('kernel.project_dir')) { - /** @var string $kernelProjectDir */ - $kernelProjectDir = $this->container->getParameter('kernel.project_dir'); - - $projectDir = $kernelProjectDir; - } - if ($this->container->hasParameter('kernel.root_dir')) { /** @var string $kernelRootDir */ $kernelRootDir = $this->container->getParameter('kernel.root_dir'); @@ -356,6 +349,13 @@ class OneupUploaderExtension extends Extension $projectDir = sprintf('%s/..', $kernelRootDir); } + if ($this->container->hasParameter('kernel.project_dir')) { + /** @var string $kernelProjectDir */ + $kernelProjectDir = $this->container->getParameter('kernel.project_dir'); + + $projectDir = $kernelProjectDir; + } + $publicDir = sprintf('%s/public', $projectDir); if (!is_dir($publicDir)) {
0
a36b9a0cd8aaf6774efffc6c00b3519fb050a8db
1up-lab/OneupUploaderBundle
Test on PHP 7.3/7.4 (#369) * Test on PHP 7.3 * Try/catch filesystem call * Test even on PHP 7.4
commit a36b9a0cd8aaf6774efffc6c00b3519fb050a8db Author: David Greminger <[email protected]> Date: Tue Feb 4 15:24:29 2020 +0100 Test on PHP 7.3/7.4 (#369) * Test on PHP 7.3 * Try/catch filesystem call * Test even on PHP 7.4 diff --git a/.travis.yml b/.travis.yml index f5b74fe..dda0dda 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,8 @@ language: php php: - 7.1 - 7.2 + - 7.3 + - 7.4 env: - SYMFONY_VERSION=^3.4 diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index 619dc66..4fbc98c 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -3,6 +3,7 @@ namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; use Gaufrette\Adapter\StreamFactory; +use Gaufrette\Exception\FileNotFound; use Gaufrette\Filesystem; use Gaufrette\FilesystemInterface; use Oneup\UploaderBundle\Uploader\File\FilesystemFile; @@ -62,15 +63,24 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface // but after the files are deleted the dirs // would remain foreach ($matches['dirs'] as $key) { - if ($maxAge <= $now - $this->filesystem->mtime($key)) { - $toDelete[] = $key; + try { + if ($maxAge <= $now - $this->filesystem->mtime($key)) { + $toDelete[] = $key; + } + } catch (FileNotFound $exception) { + // ignore } } // The same directory is returned for every file it contains array_unique($toDelete); + foreach ($matches['keys'] as $key) { - if ($maxAge <= $now - $this->filesystem->mtime($key)) { - $this->filesystem->delete($key); + try { + if ($maxAge <= $now - $this->filesystem->mtime($key)) { + $this->filesystem->delete($key); + } + } catch (FileNotFound $exception) { + // ignore } } diff --git a/composer.json b/composer.json index fe94046..6da9463 100644 --- a/composer.json +++ b/composer.json @@ -33,7 +33,7 @@ "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", - "knplabs/gaufrette": "0.2.*@dev", + "knplabs/gaufrette": "^0.9", "oneup/flysystem-bundle": "^1.2|^2.0|^3.0", "phpunit/phpunit": "^7.5", "sensio/framework-extra-bundle": "^5.0",
0
687dc14ee3f292d438adbc88c3dd913d7e09d815
1up-lab/OneupUploaderBundle
Added MooUpload tag to composer.json
commit 687dc14ee3f292d438adbc88c3dd913d7e09d815 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 14:59:44 2013 +0200 Added MooUpload tag to composer.json diff --git a/composer.json b/composer.json index a8ae808..36f6e82 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,8 @@ { "name": "oneup/uploader-bundle", "type": "symfony-bundle", - "description": "Handle multi file uploads. Features included: Chunked upload, Orphans management, Gaufrette support...", - "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload"], + "description": "Handle multi file uploads. Features included: Chunked upload, Orphans management, Gaufrette support.", + "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload"], "homepage": "http://1up.io", "license": "MIT", "authors": [
0
52205e6275347a3f1bfe3f607687a2921cef4487
1up-lab/OneupUploaderBundle
Update travis test matrix
commit 52205e6275347a3f1bfe3f607687a2921cef4487 Author: Jérémy M <[email protected]> Date: Fri Aug 21 15:45:54 2015 +0200 Update travis test matrix diff --git a/.travis.yml b/.travis.yml index 5a3affa..0af42e4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,22 +5,29 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 - hhvm env: - - SYMFONY_VERSION=2.3.* + - SYMFONY_VERSION=2.7.* matrix: + include: + - php: 5.6 + env: SYMFONY_VERSION=2.3.* + - php: 5.6 + env: SYMFONY_VERSION=2.6.* + - php: 5.6 + env: SYMFONY_VERSION=2.7.* + - php: 5.6 + env: SYMFONY_VERSION=2.8.*@dev + - php: 5.6 + env: SYMFONY_VERSION="3.0.x-dev as 2.8" allow_failures: - - env: SYMFONY_VERSION=dev-master + - php: 7.0 - php: hhvm - include: - - php: 5.5 - env: SYMFONY_VERSION=2.4.* - - php: 5.5 - env: SYMFONY_VERSION=2.5.* - - php: 5.5 - env: SYMFONY_VERSION=dev-master + - env: SYMFONY_VERSION=2.8.*@dev + - env: SYMFONY_VERSION="3.0.x-dev as 2.8" before_script: - composer selfupdate
0
141e0ca71fb6ff5e8a807199aac2982ee429c17b
1up-lab/OneupUploaderBundle
Fix .gitignore
commit 141e0ca71fb6ff5e8a807199aac2982ee429c17b Author: David Greminger <[email protected]> Date: Fri Oct 23 11:28:52 2020 +0200 Fix .gitignore diff --git a/.gitignore b/.gitignore index 99971d8..0204479 100644 --- a/.gitignore +++ b/.gitignore @@ -3,8 +3,9 @@ phpunit.xml vendor log var -Tests/App/cache -Tests/App/logs +tests/App/cache +tests/App/logs +tests/var .idea .phpunit.result.cache
0
7d12167454c398c99ed155b2524ac163df265e80
1up-lab/OneupUploaderBundle
Fixes wrong variable name.
commit 7d12167454c398c99ed155b2524ac163df265e80 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 10:59:18 2013 +0200 Fixes wrong variable name. diff --git a/Uploader/Response/UploaderResponse.php b/Uploader/Response/UploaderResponse.php index 4a0511e..d7ae71a 100644 --- a/Uploader/Response/UploaderResponse.php +++ b/Uploader/Response/UploaderResponse.php @@ -44,7 +44,7 @@ class UploaderResponse implements \ArrayAccess public function offsetGet($offset) { - return isset($this->data[$offset]) ? $this->container[$offset] : null; + return isset($this->data[$offset]) ? $this->data[$offset] : null; } public function setSuccess($success)
0
343bc34a0ea8922bf4c206f2b80137da3487933f
1up-lab/OneupUploaderBundle
Fixed a bug where chunked uploads where validated twice. Fixes #36.
commit 343bc34a0ea8922bf4c206f2b80137da3487933f Author: Jim Schmid <[email protected]> Date: Thu Jul 25 19:57:15 2013 +0200 Fixed a bug where chunked uploads where validated twice. Fixes #36. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index d7b0365..beabd2e 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -75,9 +75,6 @@ abstract class AbstractChunkedController extends AbstractController // create a temporary uploaded file to meet the interface restrictions $uploadedFile = new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, null, null, true); - - // validate this entity and upload on success - $this->validate($uploadedFile); $uploaded = $this->handleUpload($uploadedFile, $response, $request); $chunkManager->cleanup($path); diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index bbc4bc9..e7c207d 100644 --- a/Tests/Controller/AbstractChunkedUploadTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -6,6 +6,7 @@ use Symfony\Component\EventDispatcher\Event; use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; use Oneup\UploaderBundle\Event\PostChunkUploadEvent; use Oneup\UploaderBundle\Event\PreUploadEvent; +use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\UploadEvents; abstract class AbstractChunkedUploadTest extends AbstractUploadTest @@ -21,6 +22,7 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $me = $this; $endpoint = $this->helper->endpoint($this->getConfigKey()); $basename = ''; + $validationCount = 0; for ($i = 0; $i < $this->total; $i ++) { $file = $this->getNextFile($i); @@ -38,12 +40,18 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $me->assertEquals($file->getBasename(), $basename); }); + $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + ++ $validationCount; + }); + $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($file)); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); } + + $this->assertEquals(1, $validationCount); foreach ($this->getUploadedFiles() as $file) { $this->assertTrue($file->isFile());
0
f95413e20d9b28ae8cd5856f3e458b882f2c1d61
1up-lab/OneupUploaderBundle
Documentation: Process uploaded files using custom logic.
commit f95413e20d9b28ae8cd5856f3e458b882f2c1d61 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 10:44:57 2013 +0200 Documentation: Process uploaded files using custom logic. diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md new file mode 100644 index 0000000..4d66237 --- /dev/null +++ b/Resources/doc/custom_logic.md @@ -0,0 +1,41 @@ +Process uploaded files using custom logic +========================================= + +In almost every use case you need to further process uploaded files. For example if you want to add them to a Doctrine Entity or the like. To cover this, the OneupUploaderBundle provides some useful Events you can listen to. + +* `PostUploadEvent`: Will be dispatched after a file has been uploaded and moved. +* `PostPersistEvent`: The same as `PostUploadEvent` but will only be dispatched if no `Orphanage` is used. + +To listen to one of these events you need to create an `EventListener`. + +```php +namespace Acme\HelloBundle\EventListener; + +use Oneup\UploaderBundle\Event\PostPersistEvent; + +class UploadListener +{ + public function __construct($doctrine) + { + $this->doctrine = $doctrine; + } + + public function onUpload(PostPersistEvent $event) + { + //... + } +} +``` + +And register it in your `services.xml`. + +```xml +<services> + <service id="acme_hello.upload_listener" class="Acme\HelloBundle\EventListener"> + <argument type="service" id="doctrine" /> + <tag name="kernel.event_listener" event="oneup.uploader.post.persist" method="onUpload" /> + </service> +</services> +``` + +You can now implement you custom logic in the `onUpload` method of your EventListener. \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 1d44c18..5688e52 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -113,6 +113,7 @@ This is of course a very minimal setup. Be sure to include stylesheets for Fine After installing and setting up the basic functionality of this bundle you can move on and integrate some more advanced features. +* [Process uploaded files using custom logic](custom_logic.md) * [Return custom data to frontend](response.md) * [Enable chunked uploads](chunked_uploads.md) * [Using the Orphanage](orphanage.md)
0
59fc81f467dde376f02d4f38913ce834dacdf878
1up-lab/OneupUploaderBundle
Added a Command for clearing chunks: oneup:uploader:clear-chunks
commit 59fc81f467dde376f02d4f38913ce834dacdf878 Author: Jim Schmid <[email protected]> Date: Mon Mar 11 13:40:26 2013 +0100 Added a Command for clearing chunks: oneup:uploader:clear-chunks diff --git a/Command/ClearChunkCommand.php b/Command/ClearChunkCommand.php new file mode 100644 index 0000000..50bca9f --- /dev/null +++ b/Command/ClearChunkCommand.php @@ -0,0 +1,24 @@ +<?php + +namespace Oneup\UploaderBundle\Command; + +use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class ClearChunkCommand extends ContainerAwareCommand +{ + protected function configure() + { + $this + ->setName('oneup:uploader:clear-chunks') + ->setDescription('Clear chunks according to the max-age you defined in your configuration.') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $manager = $this->getContainer()->get('oneup_uploader.chunks.manager'); + $manager->clear(); + } +} \ No newline at end of file
0
977c9c0022c03d2eceed63eb49fae6c5ad84290f
1up-lab/OneupUploaderBundle
Fix exception when parameter does not exist (#400)
commit 977c9c0022c03d2eceed63eb49fae6c5ad84290f Author: David Greminger <[email protected]> Date: Tue Feb 9 18:25:30 2021 +0100 Fix exception when parameter does not exist (#400) diff --git a/src/DependencyInjection/OneupUploaderExtension.php b/src/DependencyInjection/OneupUploaderExtension.php index 889a698..b688707 100644 --- a/src/DependencyInjection/OneupUploaderExtension.php +++ b/src/DependencyInjection/OneupUploaderExtension.php @@ -342,17 +342,17 @@ class OneupUploaderExtension extends Extension { $projectDir = ''; - /** @var string $kernelProjectDir */ - $kernelProjectDir = $this->container->getParameter('kernel.project_dir'); - - /** @var string $kernelRootDir */ - $kernelRootDir = $this->container->getParameter('kernel.root_dir'); - if ($this->container->hasParameter('kernel.project_dir')) { + /** @var string $kernelProjectDir */ + $kernelProjectDir = $this->container->getParameter('kernel.project_dir'); + $projectDir = $kernelProjectDir; } if ($this->container->hasParameter('kernel.root_dir')) { + /** @var string $kernelRootDir */ + $kernelRootDir = $this->container->getParameter('kernel.root_dir'); + $projectDir = sprintf('%s/..', $kernelRootDir); }
0
f28f251a6c8c5501db38af2a2b6e1a8337e079f5
1up-lab/OneupUploaderBundle
Fix link
commit f28f251a6c8c5501db38af2a2b6e1a8337e079f5 Author: David Greminger <[email protected]> Date: Tue Sep 22 15:30:54 2015 +0200 Fix link diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md index deb1ce0..0c2e01d 100644 --- a/Resources/doc/frontend_plupload.md +++ b/Resources/doc/frontend_plupload.md @@ -1,7 +1,7 @@ Use Plupload in your Symfony2 application ========================================= -Download [Plupload](http://http://www.plupload.com/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}`. +Download [Plupload](http://www.plupload.com/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}`. ```html <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
0
fc9d5c10e27136dad7865807c584db6471cfb658
1up-lab/OneupUploaderBundle
Fix PHP 7.1 Notice: A non well formed numeric value Notice: A non well formed numeric value encountered in /var/www/symfony/vendor/oneup/uploader-bundle/Oneup/UploaderBundle/DependencyInjection/OneupUploaderExtension.php on line 297
commit fc9d5c10e27136dad7865807c584db6471cfb658 Author: Martin Hlaváč <[email protected]> Date: Thu Dec 15 09:22:48 2016 +0100 Fix PHP 7.1 Notice: A non well formed numeric value Notice: A non well formed numeric value encountered in /var/www/symfony/vendor/oneup/uploader-bundle/Oneup/UploaderBundle/DependencyInjection/OneupUploaderExtension.php on line 297 diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 0d472ff..86fd9f6 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -292,7 +292,7 @@ class OneupUploaderExtension extends Extension protected function getValueInBytes($input) { // see: http://www.php.net/manual/en/function.ini-get.php - $input = trim($input); + $input = (float) trim($input); $last = strtolower($input[strlen($input) - 1]); $numericInput = substr($input, 0, -1);
0
088378f427206d1a292d7a57691af903d3bd97d2
1up-lab/OneupUploaderBundle
Test validation of allowed_extensions.
commit 088378f427206d1a292d7a57691af903d3bd97d2 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 14:46:31 2013 +0200 Test validation of allowed_extensions. diff --git a/Tests/Controller/ControllerValidationTest.php b/Tests/Controller/ControllerValidationTest.php index 20dd449..e33c096 100644 --- a/Tests/Controller/ControllerValidationTest.php +++ b/Tests/Controller/ControllerValidationTest.php @@ -96,6 +96,53 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase // yey, no exception thrown $this->assertTrue(true); } + + /** + * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException + */ + public function testDisallowedExtensionValidationFails() + { + // create a config + $config = array(); + $config['max_size'] = 20; + $config['allowed_extensions'] = array(); + $config['disallowed_extensions'] = array('jpeg'); + + // prepare mock + $file = $this->getUploadedFileMock(); + $method = $this->getValidationMethod(); + + $container = $this->getContainerMock(); + $storage = $this->getStorageMock(); + + $controller = new UploaderController($container, $storage, $config, 'cat'); + $method->invoke($controller, $file); + + // yey, no exception thrown + $this->assertTrue(true); + } + + public function testDisallowedExtensionValidationPasses() + { + // create a config + $config = array(); + $config['max_size'] = 20; + $config['allowed_extensions'] = array(); + $config['disallowed_extensions'] = array('exe', 'bat'); + + // prepare mock + $file = $this->getUploadedFileMock(); + $method = $this->getValidationMethod(); + + $container = $this->getContainerMock(); + $storage = $this->getStorageMock(); + + $controller = new UploaderController($container, $storage, $config, 'cat'); + $method->invoke($controller, $file); + + // yey, no exception thrown + $this->assertTrue(true); + } protected function getUploadedFileMock() {
0
d64d4f36b11f1fc3cd78a772fa5609ff2157f15f
1up-lab/OneupUploaderBundle
Renamed test.
commit d64d4f36b11f1fc3cd78a772fa5609ff2157f15f Author: Jim Schmid <[email protected]> Date: Sat Apr 6 16:49:49 2013 +0200 Renamed test. diff --git a/Tests/Routing/RoutingTest.php b/Tests/Routing/RouteLoaderTest.php similarity index 100% rename from Tests/Routing/RoutingTest.php rename to Tests/Routing/RouteLoaderTest.php
0
8c884df291a903202824f60e19971fe86dbd11b2
1up-lab/OneupUploaderBundle
Added a ResponseInterface because every frontend has to use its own.
commit 8c884df291a903202824f60e19971fe86dbd11b2 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:44:53 2013 +0200 Added a ResponseInterface because every frontend has to use its own. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 9c9cf30..cc02d77 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -31,6 +31,75 @@ class BlueimpController implements UploadControllerInterface public function upload() { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new UploaderResponse(); + $files = $request->files; + + foreach($files as $file) + { + $file = $file[0]; + + try + { + $uploaded = $this->handleUpload($file); + + $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config); + $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); + + if(!$this->config['use_orphanage']) + { + // dispatch post upload event + $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); + $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); + } + } + catch(UploadException $e) + { + $response->setSuccess(false); + $response->setError($translator->trans($e->getMessage(), array(), 'OneupUploaderBundle')); + + // an error happended, return this error message. + return new JsonResponse(array()); + } + } + + return new JsonResponse(array('files' => array())); + } + + protected function handleUpload(UploadedFile $file) + { + $this->validate($file); + + // no error happend, proceed + $namer = $this->container->get($this->config['namer']); + $name = $namer->name($file); + + // perform the real upload + $uploaded = $this->storage->upload($file, $name); + + return $uploaded; + } + + protected function validate(UploadedFile $file) + { + // check if the file size submited by the client is over the max size in our config + if($file->getClientSize() > $this->config['max_size']) + throw new UploadException('error.maxsize'); + + $extension = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); + + // if this mapping defines at least one type of an allowed extension, + // test if the current is in this array + if(count($this->config['allowed_extensions']) > 0 && !in_array($extension, $this->config['allowed_extensions'])) + throw new UploadException('error.whitelist'); + + // check if the current extension is mentioned in the disallowed types + // and if so, throw an exception + if(count($this->config['disallowed_extensions']) > 0 && in_array($extension, $this->config['disallowed_extensions'])) + throw new UploadException('error.blacklist'); } } \ No newline at end of file diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index 35996c0..178378e 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -12,7 +12,7 @@ use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Controller\UploadControllerInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; +use Oneup\UploaderBundle\Uploader\Response\FineUploaderResponse; class FineUploaderController implements UploadControllerInterface { @@ -35,7 +35,7 @@ class FineUploaderController implements UploadControllerInterface $dispatcher = $this->container->get('event_dispatcher'); $translator = $this->container->get('translator'); - $response = new UploaderResponse(); + $response = new FineUploaderResponse(); $totalParts = $request->get('qqtotalparts', 1); $files = $request->files; $chunked = $totalParts > 1; diff --git a/Event/PostPersistEvent.php b/Event/PostPersistEvent.php index 6fed87f..a25dc19 100644 --- a/Event/PostPersistEvent.php +++ b/Event/PostPersistEvent.php @@ -4,7 +4,7 @@ namespace Oneup\UploaderBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; class PostPersistEvent extends Event { @@ -14,7 +14,7 @@ class PostPersistEvent extends Event protected $response; protected $config; - public function __construct($file, UploaderResponse $response, Request $request, $type, array $config) + public function __construct($file, ResponseInterface $response, Request $request, $type, array $config) { $this->file = $file; $this->request = $request; diff --git a/Event/PostUploadEvent.php b/Event/PostUploadEvent.php index 9dfd6ce..872a131 100644 --- a/Event/PostUploadEvent.php +++ b/Event/PostUploadEvent.php @@ -4,7 +4,7 @@ namespace Oneup\UploaderBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; class PostUploadEvent extends Event { @@ -14,7 +14,7 @@ class PostUploadEvent extends Event protected $response; protected $config; - public function __construct($file, UploaderResponse $response, Request $request, $type, array $config) + public function __construct($file, ResponseInterface $response, Request $request, $type, array $config) { $this->file = $file; $this->request = $request; diff --git a/Uploader/Response/ResponseInterface.php b/Uploader/Response/ResponseInterface.php new file mode 100644 index 0000000..b1e835e --- /dev/null +++ b/Uploader/Response/ResponseInterface.php @@ -0,0 +1,8 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Response; + +interface ResponseInterface extends \ArrayAccess +{ + public function assemble(); +} \ No newline at end of file diff --git a/Uploader/Response/UploaderResponse.php b/Uploader/Response/UploaderResponse.php deleted file mode 100644 index 090df34..0000000 --- a/Uploader/Response/UploaderResponse.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Response; - -class UploaderResponse implements \ArrayAccess -{ - protected $success; - protected $error; - protected $data; - - public function __construct() - { - $this->success = true; - $this->error = null; - $this->data = array(); - } - - public function assemble() - { - // explicitly overwrite success and error key - // as these keys are used internaly by the - // frontend uploader - $data = $this->data; - $data['success'] = $this->success; - - if($this->success) - unset($data['error']); - - if(!$this->success) - $data['error'] = $this->error; - - return $data; - } - - public function offsetSet($offset, $value) - { - is_null($offset) ? $this->data[] = $value : $this->data[$offset] = $value; - } - public function offsetExists($offset) - { - return isset($this->data[$offset]); - } - public function offsetUnset($offset) - { - unset($this->data[$offset]); - } - - public function offsetGet($offset) - { - return isset($this->data[$offset]) ? $this->data[$offset] : null; - } - - public function setSuccess($success) - { - $this->success = (bool) $success; - - return $this; - } - - public function getSuccess() - { - return $this->success; - } - - public function setError($msg) - { - $this->error = $msg; - - return $this; - } - - public function getError() - { - return $this->error; - } -} \ No newline at end of file
0
09f78d50e30bc70221010f84d36a8bfd00da8b4d
1up-lab/OneupUploaderBundle
Removed DeletableListener as it is not used anymore.
commit 09f78d50e30bc70221010f84d36a8bfd00da8b4d Author: Jim Schmid <[email protected]> Date: Wed Mar 27 17:54:58 2013 +0100 Removed DeletableListener as it is not used anymore. diff --git a/EventListener/DeletableListener.php b/EventListener/DeletableListener.php deleted file mode 100644 index 38c752b..0000000 --- a/EventListener/DeletableListener.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; - -use Oneup\UploaderBundle\Event\PostUploadEvent; -use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Uploader\Deletable\DeletableManagerInterface; - -class DeletableListener implements EventSubscriberInterface -{ - protected $manager; - - public function __construct(DeletableManagerInterface $manager) - { - $this->manager = $manager; - } - - public function register(PostUploadEvent $event) - { - $options = $event->getOptions(); - $request = $event->getRequest(); - $file = $event->getFile(); - $type = $event->getType(); - - if(!array_key_exists('deletable', $options) || !$options['deletable']) - return; - - if(!array_key_exists('file_name', $options)) - return; - - $uuid = $request->get('qquuid'); - - $this->manager->addFile($type, $uuid, $options['file_name']); - } - - public static function getSubscribedEvents() - { - return array( - UploadEvents::POST_UPLOAD => 'register', - ); - } -}
0
49ea4703d2ee7d92a605ab24deb6d888069b83e7
1up-lab/OneupUploaderBundle
Merge pull request #91 from mitom/master use the stream wrapper prefix when available
commit 49ea4703d2ee7d92a605ab24deb6d888069b83e7 (from c8d119534029226b874ae8ccaef5e265fa137d06) Merge: c8d1195 243f216 Author: Jim Schmid <[email protected]> Date: Fri Feb 21 17:17:30 2014 +0100 Merge pull request #91 from mitom/master use the stream wrapper prefix when available diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index dec76ce..9d22fd6 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -169,4 +169,9 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface { return $this->filesystem; } + + public function getStreamWrapperPrefix() + { + return $this->streamWrapperPrefix; + } } diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index ea5379f..d5a9489 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -26,9 +26,11 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto */ public function __construct(StorageInterface $storage, SessionInterface $session, GaufretteChunkStorage $chunkStorage, $config, $type) { - // initiate the storage on the chunk storage's filesystem - // the prefix and stream wrapper are unnecessary. - parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, null, null); + /* + * initiate the storage on the chunk storage's filesystem + * the stream wrapper is useful for metadata. + */ + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, $chunkStorage->getStreamWrapperPrefix()); $this->storage = $storage; $this->chunkStorage = $chunkStorage;
0
1903a267fd643201b0664cfe24e599ae848e795b
1up-lab/OneupUploaderBundle
Fixed a bug in RouteLoader and created frontend helpers.
commit 1903a267fd643201b0664cfe24e599ae848e795b Author: Jim Schmid <[email protected]> Date: Mon Jun 24 21:07:08 2013 +0200 Fixed a bug in RouteLoader and created frontend helpers. diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 7771274..62c3cab 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -41,9 +41,11 @@ class RouteLoader extends Loader array('_controller' => $service . ':progress', '_format' => 'json'), array('_method' => 'POST') ); + + $routes->add(sprintf('_uploader_progress_%s', $type), $progress); } - $routes->add(sprintf('_uploader_%s', $type), $upload); + $routes->add(sprintf('_uploader_upload_%s', $type), $upload); } return $routes; diff --git a/Templating/Helper/UploaderHelper.php b/Templating/Helper/UploaderHelper.php index 1882766..ffdfd91 100644 --- a/Templating/Helper/UploaderHelper.php +++ b/Templating/Helper/UploaderHelper.php @@ -21,6 +21,11 @@ class UploaderHelper extends Helper public function endpoint($key) { - return $this->router->generate(sprintf('_uploader_%s', $key)); + return $this->router->generate(sprintf('_uploader_upload_%s', $key)); + } + + public function progress($key) + { + return $this->router->generate(sprintf('_uploader_progress_%s', $key)); } } diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 77da381..2299750 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -26,6 +26,7 @@ oneup_uploader: fineuploader: frontend: fineuploader + use_upload_progress: true storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index 8849b79..3e7d5da 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -20,11 +20,19 @@ class UploaderExtension extends \Twig_Extension public function getFunctions() { - return array('oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint')); + return array( + 'oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint') + 'oneup_uploader_progress' => new \Twig_Function_Method($this, 'progress') + ); } public function endpoint($key) { return $this->helper->endpoint($key); } + + public function progress($key) + { + return $this->helper->progress($key); + } }
0
a057ab926314260f635862e02bca6aae73275aeb
1up-lab/OneupUploaderBundle
Merge pull request #9 from 1up-lab/frontend_agnostic Added Uploadify and YUI3 backend.
commit a057ab926314260f635862e02bca6aae73275aeb (from 72671ee9b9ca21bfe16741048caf5155ba16084f) Merge: 72671ee b808587 Author: Jim Schmid <[email protected]> Date: Thu Apr 11 11:34:16 2013 -0700 Merge pull request #9 from 1up-lab/frontend_agnostic Added Uploadify and YUI3 backend. diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php new file mode 100644 index 0000000..7c94966 --- /dev/null +++ b/Controller/UploadifyController.php @@ -0,0 +1,40 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\Controller\AbstractController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class UploadifyController extends AbstractController +{ + public function upload() + { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new EmptyResponse(); + $files = $request->files; + + foreach($files as $file) + { + try + { + $uploaded = $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + } + + return new JsonResponse($response->assemble()); + } +} \ No newline at end of file diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php new file mode 100644 index 0000000..8ade2ec --- /dev/null +++ b/Controller/YUI3Controller.php @@ -0,0 +1,40 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\Controller\AbstractController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class YUI3Controller extends AbstractController +{ + public function upload() + { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new EmptyResponse(); + $files = $request->files; + + foreach($files as $file) + { + try + { + $uploaded = $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + } + + return new JsonResponse($response->assemble()); + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 8848e0d..7298bec 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 7083edf..6933114 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -13,6 +13,8 @@ <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> <parameter key="oneup_uploader.controller.fineuploader.class">Oneup\UploaderBundle\Controller\FineUploaderController</parameter> <parameter key="oneup_uploader.controller.blueimp.class">Oneup\UploaderBundle\Controller\BlueimpController</parameter> + <parameter key="oneup_uploader.controller.uploadify.class">Oneup\UploaderBundle\Controller\UploadifyController</parameter> + <parameter key="oneup_uploader.controller.yui3.class">Oneup\UploaderBundle\Controller\YUI3Controller</parameter> </parameters> <services>
0
968548264758fa5bce66659730f57ca6582c7f3e
1up-lab/OneupUploaderBundle
Typo
commit 968548264758fa5bce66659730f57ca6582c7f3e Author: David Greminger <[email protected]> Date: Mon Dec 4 09:51:45 2017 +0100 Typo diff --git a/README.md b/README.md index 2a54218..c5c5b05 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- -* Version **2.0.0** supports now Symfony 4 (Thank you @[istvancsabakis](https://github.com/istvancsabakis), see [#295](https://github.com/1up-lab/OneupUploaderBundle/pull/295))! Symfony 2.x support was dropped. You can also configure now a file extension validation whitelist (PR [#262](https://github.com/1up-lab/OneupUploaderBundle/pull/262)) +* Version **2.0.0** supports now Symfony 4 (Thank you @[istvancsabakis](https://github.com/istvancsabakis), see [#295](https://github.com/1up-lab/OneupUploaderBundle/pull/295))! Symfony 2.x support was dropped. You can also configure a file extension validation whitelist now (PR [#262](https://github.com/1up-lab/OneupUploaderBundle/pull/262)). * Version **1.5.0** supports now [Flysystem](https://github.com/1up-lab/OneupFlysystemBundle) (Thank you @[lsv](https://github.com/lsv)! PR [#213](https://github.com/1up-lab/OneupUploaderBundle/pull/213)) and is no longer compatible with PHP 5.3 (it's [EOL](http://php.net/eol.php) since August 2014 anyway). * Version **v1.0.0** introduced some backward compatibility breaks. For a full list of changes, head to the [dedicated pull request](https://github.com/1up-lab/OneupUploaderBundle/pull/57). * If you're using chunked uploads consider upgrading from **v0.9.6** to **v0.9.7**. A critical issue was reported regarding the assembly of chunks. More information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21#issuecomment-21560320).
0
f8198be7c695defe8eb1df40a08f08d6efe0d559
1up-lab/OneupUploaderBundle
Fixed configuring of frontend and classname of BlueimpController
commit f8198be7c695defe8eb1df40a08f08d6efe0d559 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:10:07 2013 +0200 Fixed configuring of frontend and classname of BlueimpController diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 064b95f..9c9cf30 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -14,7 +14,7 @@ use Oneup\UploaderBundle\Controller\UploadControllerInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; -class FineUploaderController implements UploadControllerInterface +class BlueimpController implements UploadControllerInterface { protected $container; protected $storage; diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 3355be5..a9747a1 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -105,7 +105,7 @@ class OneupUploaderExtension extends Extension } $controllerName = sprintf('oneup_uploader.controller.%s', $key); - $controllerType = sprintf('oneup_uploader.controller.%s.class', $mapping['frontend']); + $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $mapping['frontend']); // create controllers based on mapping $container
0
9a3189ec012fb0c240bd83dfed0c8447794322ce
1up-lab/OneupUploaderBundle
Code highlighter bricks on GitHub, give it another try.
commit 9a3189ec012fb0c240bd83dfed0c8447794322ce Author: Jim Schmid <[email protected]> Date: Tue Apr 9 10:15:24 2013 +0200 Code highlighter bricks on GitHub, give it another try. diff --git a/Resources/doc/response.md b/Resources/doc/response.md index a438956..6cb75f4 100644 --- a/Resources/doc/response.md +++ b/Resources/doc/response.md @@ -4,3 +4,31 @@ Return custom data to the Frontend There are some use cases where you need custom data to be returned to the frontend. For example the id of a generated Doctrine Entity or the like. To cover this, you can use `UploaderResponse` passed through all `Events`. ```php +namespace Acme\HelloBundle\EventListener; + +use Oneup\UploaderBundle\Event\PostPersistEvent; + +class UploadListener +{ + public function onUpload(PostPersistEvent $event) + { + $response = $event->getResponse(); + } +} +``` + +The `UploaderResponse` class implements the `ArrayAccess` interface, so you can just add data using it like an array: + +´´´php +$response['id'] = $uploadedImage->getId(); +$response['url'] = $uploadedImage->getUrl(); +``` + +If you like to indicate an error, be sure to set the `success` property to `false` and provide an error message: + +```php +$response->setSuccess(false); +$response->setError($msg); +``` + +> Do not use the keys `success` and `error` if you provide custom data, they will be overwritten by the internal properties of `UploaderResponse`. \ No newline at end of file
0
1db282127c8f43c664e714a51b4d7fe8ddaec453
1up-lab/OneupUploaderBundle
Update AbstractController.php
commit 1db282127c8f43c664e714a51b4d7fe8ddaec453 Author: DomoJonux <[email protected]> Date: Thu Jan 7 09:14:44 2016 +0100 Update AbstractController.php diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 01ae713..75d3518 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -175,6 +175,7 @@ abstract class AbstractController $event = new ValidationEvent($file, $this->getRequest(), $this->config, $this->type); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::VALIDATION, $this->type), $event); } /**
0
342886efc6e8f5040ebb0cc898540d7a905864eb
1up-lab/OneupUploaderBundle
Update flysystem_storage.md
commit 342886efc6e8f5040ebb0cc898540d7a905864eb Author: David Greminger <[email protected]> Date: Fri May 15 14:35:42 2020 +0200 Update flysystem_storage.md diff --git a/doc/flysystem_storage.md b/doc/flysystem_storage.md index 76aa1ea..eba9543 100644 --- a/doc/flysystem_storage.md +++ b/doc/flysystem_storage.md @@ -16,7 +16,7 @@ Add the OneupFlysystemBundle to your composer.json file. ```js { "require": { - "oneup/flysystem-bundle": "1.4.*" + "oneup/flysystem-bundle": "^3.4" } } ```
0
e7aa4fb68e8c58af19887439b79ceb796bf70e8e
1up-lab/OneupUploaderBundle
Added an UploadHandlerInterface
commit e7aa4fb68e8c58af19887439b79ceb796bf70e8e Author: Jim Schmid <[email protected]> Date: Tue Mar 12 16:14:00 2013 +0100 Added an UploadHandlerInterface diff --git a/Uploader/Handler/HandlerInterface.php b/Uploader/Handler/HandlerInterface.php new file mode 100644 index 0000000..ec7cb5f --- /dev/null +++ b/Uploader/Handler/HandlerInterface.php @@ -0,0 +1,8 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Handler; + +interface HandlerInterface +{ + public function perform(); +} \ No newline at end of file
0
fc2ed9a6b798c71951806c8c9ed6e1366856272e
1up-lab/OneupUploaderBundle
Added Request object to ValidationEvent This current implementation (as of v0.9.8) was made without breaking backwards compatibility. This means constructor's parameter $request of ValidationEvent defaults to null. Should be fixed in the next major version. Details in #23.
commit fc2ed9a6b798c71951806c8c9ed6e1366856272e Author: Jim Schmid <[email protected]> Date: Sat Sep 14 15:27:12 2013 +0200 Added Request object to ValidationEvent This current implementation (as of v0.9.8) was made without breaking backwards compatibility. This means constructor's parameter $request of ValidationEvent defaults to null. Should be fixed in the next major version. Details in #23. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 0ab6eec..30b0519 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -164,7 +164,7 @@ abstract class AbstractController protected function validate(UploadedFile $file) { $dispatcher = $this->container->get('event_dispatcher'); - $event = new ValidationEvent($file, $this->config, $this->type); + $event = new ValidationEvent($file, $this->config, $this->type, $this->container->get('request')); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); } diff --git a/Event/ValidationEvent.php b/Event/ValidationEvent.php index a3ecef1..0fa90b0 100644 --- a/Event/ValidationEvent.php +++ b/Event/ValidationEvent.php @@ -4,17 +4,21 @@ namespace Oneup\UploaderBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\Request; class ValidationEvent extends Event { protected $file; protected $config; + protected $type; + protected $request; - public function __construct(UploadedFile $file, array $config, $type) + public function __construct(UploadedFile $file, array $config, $type, Request $request = null) { $this->file = $file; $this->config = $config; $this->type = $type; + $this->request = $request; } public function getFile() @@ -31,4 +35,9 @@ class ValidationEvent extends Event { return $this->type; } + + public function getRequest() + { + return $this->request; + } } diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index d0e1e60..5461c6b 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -65,6 +65,27 @@ abstract class AbstractValidationTest extends AbstractControllerTest $this->assertEquals(1, $validationCount); } + public function testIfRequestIsAvailableInEvent() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + // event data + $validationCount = 0; + + $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $event->getRequest()); + + // to be sure this listener is called + ++ $validationCount; + }); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectExtension())); + + $this->assertEquals(1, $validationCount); + } + public function testAgainstIncorrectExtension() { // assemble a request
0
a0996504bacb1130d780c3b346098c9962ac51c2
1up-lab/OneupUploaderBundle
Set correct link
commit a0996504bacb1130d780c3b346098c9962ac51c2 Author: David Greminger <[email protected]> Date: Thu Jan 28 16:04:15 2016 +0100 Set correct link diff --git a/README.md b/README.md index 12ae19a..8e23bc0 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- -* Version **1.5.0** supports now [Flysystem](https://github.com/1up-lab/OneupFlysystemBundle) (Thank you @lsv! PR is [here](https://github.com/1up-lab/OneupUploaderBundle/pull/213)) and is no longer compatible with PHP 5.3 (it's [EOL](http://php.net/eol.php) since August 2014 anyway). +* Version **1.5.0** supports now [Flysystem](https://github.com/1up-lab/OneupFlysystemBundle) (Thank you @[lsv](https://github.com/lsv)! PR is [here](https://github.com/1up-lab/OneupUploaderBundle/pull/213)) and is no longer compatible with PHP 5.3 (it's [EOL](http://php.net/eol.php) since August 2014 anyway). * Version **v1.0.0** introduced some backward compatibility breaks. For a full list of changes, head to the [dedicated pull request](https://github.com/1up-lab/OneupUploaderBundle/pull/57). * If you're using chunked uploads consider upgrading from **v0.9.6** to **v0.9.7**. A critical issue was reported regarding the assembly of chunks. More information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21#issuecomment-21560320). * Error management [changed](https://github.com/1up-lab/OneupUploaderBundle/pull/25) in Version **0.9.6**. You can now register an `ErrorHandler` per configured frontend. This comes bundled with some adjustments to the `blueimp` controller. More information is available in [the documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_error_handler.md).
0
155aca367c31eaed594f45ff88b8ce9de2adfd01
1up-lab/OneupUploaderBundle
gaufrette orphanage fixes and tests
commit 155aca367c31eaed594f45ff88b8ce9de2adfd01 Author: mitom <[email protected]> Date: Fri Oct 11 14:25:00 2013 +0200 gaufrette orphanage fixes and tests diff --git a/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php index 2278b96..d647848 100644 --- a/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php @@ -5,7 +5,6 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Oneup\UploaderBundle\Uploader\Storage\FilesystemOrphanageStorage; use Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage as FilesystemChunkStorage; -use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Session\Session; @@ -13,15 +12,8 @@ use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; -class FilesystemOrphanageStorageTest extends \PHPUnit_Framework_TestCase +class FilesystemOrphanageStorageTest extends OrphanageTest { - protected $tempDirectory; - protected $realDirectory; - protected $orphanage; - protected $storage; - protected $payloads; - protected $numberOfPayloads; - public function setUp() { $this->numberOfPayloads = 5; @@ -57,72 +49,4 @@ class FilesystemOrphanageStorageTest extends \PHPUnit_Framework_TestCase $this->orphanage = new FilesystemOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat'); } - - public function testUpload() - { - for ($i = 0; $i < $this->numberOfPayloads; $i ++) { - $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); - } - - $finder = new Finder(); - $finder->in($this->tempDirectory)->files(); - $this->assertCount($this->numberOfPayloads, $finder); - - $finder = new Finder(); - $finder->in($this->realDirectory)->files(); - $this->assertCount(0, $finder); - } - - public function testUploadAndFetching() - { - for ($i = 0; $i < $this->numberOfPayloads; $i ++) { - $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); - } - - $finder = new Finder(); - $finder->in($this->tempDirectory)->files(); - $this->assertCount($this->numberOfPayloads, $finder); - - $finder = new Finder(); - $finder->in($this->realDirectory)->files(); - $this->assertCount(0, $finder); - - $files = $this->orphanage->uploadFiles(); - - $this->assertTrue(is_array($files)); - $this->assertCount($this->numberOfPayloads, $files); - - $finder = new Finder(); - $finder->in($this->tempDirectory)->files(); - $this->assertCount(0, $finder); - - $finder = new Finder(); - $finder->in($this->realDirectory)->files(); - $this->assertCount($this->numberOfPayloads, $finder); - } - - public function testUploadAndFetchingIfDirectoryDoesNotExist() - { - $filesystem = new Filesystem(); - $filesystem->remove($this->tempDirectory); - - $files = $this->orphanage->uploadFiles(); - - $this->assertTrue(is_array($files)); - $this->assertCount(0, $files); - } - - public function testIfGetFilesMethodIsAccessible() - { - // since ticket #48, getFiles has to be public - $method = new \ReflectionMethod($this->orphanage, 'getFiles'); - $this->assertTrue($method->isPublic()); - } - - public function tearDown() - { - $filesystem = new Filesystem(); - $filesystem->remove($this->tempDirectory); - $filesystem->remove($this->realDirectory); - } } diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index ec02d6b..e087c1b 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -55,13 +55,9 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto try { $return[] = $this->storage->upload($file, str_replace($this->getPath(), '', $key)); } catch (\Exception $e) { - // don't delete the file, if the upload failed because - // 1, it may not exist and deleting would throw another exception; - // 2, don't lose it on network related errors + // well, we tried. continue; } - - $this->chunkStorage->getFilesystem()->delete($key); } return $return;
0
cdc567739906d0e7f42dbc06a005774589ec03af
1up-lab/OneupUploaderBundle
Merge branch 'm47730-patch-1'
commit cdc567739906d0e7f42dbc06a005774589ec03af (from e2b21d4245bf70ccd5aa7cf4f38ab7884f490c79) Merge: e2b21d4 74453d4 Author: David Greminger <[email protected]> Date: Mon Oct 23 17:47:06 2017 +0200 Merge branch 'm47730-patch-1' diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 3942d44..2e5f82e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -34,7 +34,7 @@ Perform the following steps to install and use the basic functionality of the On Add OneupUploaderBundle to your composer.json using the following construct: - $ composer require oneup/uploader-bundle "~1.4" + $ composer require oneup/uploader-bundle Composer will install the bundle to your project's ``vendor/oneup/uploader-bundle`` directory.
0
b776e4998bb96c49ec9db5899b19ea407d94040b
1up-lab/OneupUploaderBundle
Update custom_validator.md Reordered sentences.
commit b776e4998bb96c49ec9db5899b19ea407d94040b Author: Jim Schmid <[email protected]> Date: Fri Aug 16 08:44:44 2013 +0200 Update custom_validator.md Reordered sentences. diff --git a/Resources/doc/custom_validator.md b/Resources/doc/custom_validator.md index 3b63823..37fa8c1 100644 --- a/Resources/doc/custom_validator.md +++ b/Resources/doc/custom_validator.md @@ -3,6 +3,7 @@ Writing custom Validators File validations in the OneupUploaderBundle were made using the [EventDispatcher](http://symfony.com/doc/current/components/event_dispatcher/introduction.html) component. If you want to enhance file validations in your application, you can register your own `EventListener` like in the example below. +To fail a validation, throw a `ValidationException`. This will be catched up by the `Controller`. ```php namespace Acme\DemoBundle\EventListener; @@ -23,7 +24,6 @@ class AlwaysFalseValidationListener } ``` -If you want your validation to fail, throw a `ValidationException`. This will be catched up by the `Controller`. After that register your new `EventListener` in the `services.xml` of your application. ```xml
0
50d14ccfdd25c3bc9ea97ee5d4d585ffc8f55242
1up-lab/OneupUploaderBundle
Raised requirement of symfony/framework-bundle to >=2.2.
commit 50d14ccfdd25c3bc9ea97ee5d4d585ffc8f55242 Author: Jim Schmid <[email protected]> Date: Fri Oct 11 19:29:27 2013 +0200 Raised requirement of symfony/framework-bundle to >=2.2. diff --git a/composer.json b/composer.json index b4a4d15..a6be9f8 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ ], "require": { - "symfony/framework-bundle": "2.*", + "symfony/framework-bundle": ">=2.2", "symfony/finder": ">=2.2.0" },
0
9a1b5cb2350dc83e1863c68ef07104494a7ce977
1up-lab/OneupUploaderBundle
Tested chunked upload. Bhuuu, that was a hard one.
commit 9a1b5cb2350dc83e1863c68ef07104494a7ce977 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 19:10:16 2013 +0200 Tested chunked upload. Bhuuu, that was a hard one. diff --git a/Tests/Controller/ControllerChunkedUploadTest.php b/Tests/Controller/ControllerChunkedUploadTest.php new file mode 100644 index 0000000..3c57240 --- /dev/null +++ b/Tests/Controller/ControllerChunkedUploadTest.php @@ -0,0 +1,175 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; +use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; +use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; +use Oneup\UploaderBundle\Controller\UploaderController; + +class ControllerChunkedUploadTest extends \PHPUnit_Framework_TestCase +{ + protected $tempChunks; + protected $currentChunk; + protected $chunkUuid; + protected $numberOfChunks; + + public function setUp() + { + $this->numberOfChunks = 10; + + // create 10 chunks + for($i = 0; $i < $this->numberOfChunks; $i++) + { + // create temporary file + $chunk = tempnam(sys_get_temp_dir(), 'uploader'); + + $pointer = fopen($chunk, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + $this->tempChunks[] = $chunk; + } + + $this->currentChunk = 0; + $this->chunkUuid = uniqid(); + } + + public function testUpload() + { + $container = $this->getContainerMock(); + $storage = new FilesystemStorage(sys_get_temp_dir() . '/uploader'); + $config = array( + 'use_orphanage' => false, + 'namer' => 'namer', + 'max_size' => 2048, + 'allowed_extensions' => array(), + 'disallowed_extensions' => array() + ); + + $responses = array(); + $controller = new UploaderController($container, $storage, $config, 'cat'); + + // mock as much requests as there are parts to assemble + for($i = 0; $i < $this->numberOfChunks; $i ++) + { + $responses[] = $controller->upload(); + + // will be used internaly + $this->currentChunk++; + } + + for($i = 0; $i < $this->numberOfChunks; $i ++) + { + // check if original file has been moved + $this->assertFalse(file_exists($this->tempChunks[$i])); + + $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $responses[$i]); + $this->assertEquals(200, $responses[$i]->getStatusCode()); + } + + // check if assembled file is here + $finder = new Finder(); + $finder->in(sys_get_temp_dir() . '/uploader')->files(); + $this->assertCount(1, $finder); + + // and check if chunks are gone + $finder = new Finder(); + $finder->in(sys_get_temp_dir() . '/chunks')->files(); + $this->assertCount(0, $finder); + } + + protected function getContainerMock() + { + $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); + $mock + ->expects($this->any()) + ->method('get') + ->will($this->returnCallback(array($this, 'containerGetCb'))) + ; + + return $mock; + } + + public function containerGetCb($inp) + { + if($inp == 'request') + return $this->getRequestMock(); + + if($inp == 'event_dispatcher') + return $this->getEventDispatcherMock(); + + if($inp == 'namer') + return new UniqidNamer(); + + if($inp == 'oneup_uploader.chunk_manager') + return $this->getChunkManager(); + } + + protected function getEventDispatcherMock() + { + $mock = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); + $mock + ->expects($this->any()) + ->method('dispatch') + ->will($this->returnValue(true)) + ; + + return $mock; + } + + protected function getRequestMock() + { + $mock = $this->getMock('Symfony\Component\HttpFoundation\Request'); + $mock + ->expects($this->any()) + ->method('get') + ->will($this->returnCallback(array($this, 'requestGetCb'))) + ; + + $mock->files = array( + $this->getUploadedFile() + ); + + return $mock; + } + + public function requestGetCb($inp) + { + if($inp == 'qqtotalparts') + return $this->numberOfChunks; + + if($inp == 'qqpartindex') + return $this->currentChunk; + + if($inp == 'qquuid') + return $this->chunkUuid; + + if($inp == 'qqfilename') + return 'grumpy-cat.jpeg'; + } + + protected function getUploadedFile() + { + return new UploadedFile($this->tempChunks[$this->currentChunk], 'grumpy-cat.jpeg', 'image/jpeg', 1024, null, true); + } + + protected function getChunkManager() + { + return new ChunkManager(array( + 'directory' => sys_get_temp_dir() . '/chunks' + )); + } + + public function tearDown() + { + // remove all files in tmp folder + $filesystem = new Filesystem(); + $filesystem->remove(sys_get_temp_dir() . '/uploader'); + $filesystem->remove(sys_get_temp_dir() . '/chunks'); + } +} \ No newline at end of file
0
80ba434c4bd4bbf0ae5f6fc9d8a0d2fc5726ac0e
1up-lab/OneupUploaderBundle
Merge pull request #1 from sheeep/release-1.0 Documentation fixes.
commit 80ba434c4bd4bbf0ae5f6fc9d8a0d2fc5726ac0e (from 71d6118a7598701727b72b2d712ad231184a8778) Merge: 71d6118 207d2f1 Author: mitom <[email protected]> Date: Fri Oct 11 10:29:14 2013 -0700 Merge pull request #1 from sheeep/release-1.0 Documentation fixes. diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index b6c560d..7eefd95 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -38,7 +38,7 @@ oneup_uploader: You can choose a custom directory to save the chunks temporarily while uploading by changing the parameter `directory`. Since version 1.0 you can also use a Gaufrette filesystem as the chunk storage. To do this you must first -set up [Gaufrette](gaufrette_storage.md).There are however some additional things to keep in mind. +set up [Gaufrette](gaufrette_storage.md). There are however some additional things to keep in mind. The configuration for the Gaufrette chunk storage should look as the following: ``` oneup_uploader: @@ -46,14 +46,14 @@ oneup_uploader: maxage: 86400 storage: type: gaufrette - filesystem: gaufrette.gallery_filesystem + filesystem: gaufrette.gallery_filesystem prefix: 'chunks' stream_wrapper: 'gaufrette://gallery/' ``` -> Setting the stream_wrapper is heavily recommended for better performance, see the reasons in the [gaufrette configuration](gaufrette_storage.md#configure-your-mappings) +> Setting the `stream_wrapper` is heavily recommended for better performance, see the reasons in the [gaufrette configuration](gaufrette_storage.md#configure-your-mappings) -As you can see there are is a new option, ```prefix```. It represents the directory +As you can see there are is a new option, `prefix`. It represents the directory *relative* to the filesystem's directory which the chunks are stored in. Gaufrette won't allow it to be outside of the filesystem. @@ -61,16 +61,16 @@ Gaufrette won't allow it to be outside of the filesystem. only the Local filesystem is capable of streaming directly. This will give you a better structured directory, -as the chunk's folders and the uploaded files won't mix with each other. -> You can set it to an empty string (```''```), if you don't need it. Otherwise it defaults to ```chunks```. +as the chunk's folders and the uploaded files won't mix with each other. +> You can set it to an empty string (`''`), if you don't need it. Otherwise it defaults to `chunks`. -The chunks will be read directly from the tmp and appended to the already existing part on the given filesystem, +The chunks will be read directly from the temporary directory and appended to the already existing part on the given filesystem, resulting in only 1 read and 1 write operation. -You can achieve the biggest improvement if you use the same filesystem as your storage, as if you do so, the assembled -file only has to be moved out of the chunk directory, which on the same filesystem takes almost not time. +You can achieve the biggest improvement if you use the same filesystem as your storage. If you do so, the assembled +file only has to be moved out of the chunk directory, which takes no time on a local filesystem. -> The ```load distribution``` is forcefully turned on, if you use gaufrette as the chunk storage. +> The load distribution is forcefully turned on, if you use Gaufrette as the chunk storage. ## Clean up diff --git a/Resources/doc/gaufrette_storage.md b/Resources/doc/gaufrette_storage.md index c03ba84..2e74a3c 100644 --- a/Resources/doc/gaufrette_storage.md +++ b/Resources/doc/gaufrette_storage.md @@ -53,7 +53,7 @@ knp_gaufrette: local: directory: %kernel.root_dir%/../web/uploads create: true - + filesystems: gallery: adapter: gallery @@ -71,7 +71,7 @@ oneup_uploader: gallery: storage: type: gaufrette - filesystem: gaufrette.gallery_filesystem + filesystem: gaufrette.gallery_filesystem ``` You can specify the buffer size used for syncing files from your filesystem to the gaufrette storage by changing the property `sync_buffer_size`. @@ -84,7 +84,7 @@ oneup_uploader: gallery: storage: type: gaufrette - filesystem: gaufrette.gallery_filesystem + filesystem: gaufrette.gallery_filesystem sync_buffer_size: 1M ``` @@ -97,18 +97,18 @@ oneup_uploader: gallery: storage: type: gaufrette - filesystem: gaufrette.gallery_filesystem + filesystem: gaufrette.gallery_filesystem stream_wrapper: gaufrette://gallery/ ``` -> This is only useful if you are using a stream capable adapter, at the time of this writing only +> This is only useful if you are using a stream-capable adapter. At the time of this writing, only the local adapter is capable of streaming directly. -The first part (```gaufrette```) in the example above ```MUST``` be the same as ```knp_gaufrette.stream_wrapper.protocol```, -the second part (```gallery```) in the example, ```MUST``` be the key of the filesytem (```knp_gaufette.filesystems.key```). -It also must end with a slash (```/```). +The first part (`gaufrette`) in the example above `MUST` be the same as `knp_gaufrette.stream_wrapper.protocol`, +the second part (`gallery`) in the example, `MUST` be the key of the filesytem (`knp_gaufette.filesystems.key`). +It also must end with a slash (`/`). This is particularly useful if you want to get exact informations about your files. Gaufrette offers you every functionality to do this without relying on the stream wrapper, however it will have to download the file and load it into memory -to operate on it. If ```stream_wrapper``` is specified the bundle will try to open the file as streams when such operation -is requested.(e.g. getting the size of the file, the mime-type based on content) +to operate on it. If `stream_wrapper` is specified, the bundle will try to open the file as streams when such operation +is requested. (e.g. getting the size of the file, the mime-type based on content) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index fe69b15..430fc08 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -124,6 +124,7 @@ some more advanced features. * [Validate your uploads](custom_validator.md) * [General/Generic Events](events.md) * [Enable Session upload progress / upload cancelation](progress.md) +* [Use Chunked Uploads behind Load Balancers](load_balancers.md) * [Configuration Reference](configuration_reference.md) * [Testing this bundle](testing.md) diff --git a/Resources/doc/load_balancers.md b/Resources/doc/load_balancers.md new file mode 100644 index 0000000..0667b94 --- /dev/null +++ b/Resources/doc/load_balancers.md @@ -0,0 +1,6 @@ +Use Chunked Uploads behind Load Balancers +========================================= + +If you want to use Chunked Uploads behind load balancers that is not configured to use sticky sessions you'll eventually end up with a bunch of chunks on every instance and the bundle is not able to reassemble the file on the server. + +You can avoid this problem by using Gaufrette as an abstract filesystem. \ No newline at end of file
0
310ad454b8a23450f2a32b63a9c8f712daaa3934
1up-lab/OneupUploaderBundle
Fix test suite by disabling the two failing tests.
commit 310ad454b8a23450f2a32b63a9c8f712daaa3934 Author: Jim Schmid <[email protected]> Date: Sun Jul 6 10:27:24 2014 +0200 Fix test suite by disabling the two failing tests. diff --git a/.travis.yml b/.travis.yml index e3c5391..bd24695 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,7 @@ language: php php: - 5.3 - 5.4 + - 5.5 env: - SYMFONY_VERSION=2.3.* diff --git a/Tests/Uploader/Naming/UniqidNamerTest.php b/Tests/Uploader/Naming/UniqidNamerTest.php index d20df0a..38c9b75 100644 --- a/Tests/Uploader/Naming/UniqidNamerTest.php +++ b/Tests/Uploader/Naming/UniqidNamerTest.php @@ -8,6 +8,9 @@ class UniqidNamerTest extends \PHPUnit_Framework_TestCase { public function testNamerReturnsName() { + // TODO Reenable this test. + $this->markTestSkipped('Details: https://github.com/Ocramius/Instantiator/pull/8#issuecomment-47446963'); + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') ->disableOriginalConstructor() ->getMock() @@ -25,6 +28,9 @@ class UniqidNamerTest extends \PHPUnit_Framework_TestCase public function testNamerReturnsUniqueName() { + // TODO Reenable this test. + $this->markTestSkipped('Details: https://github.com/Ocramius/Instantiator/pull/8#issuecomment-47446963'); + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') ->disableOriginalConstructor() ->getMock()
0
15f3614144d72b166d82a3e1586c2e66a357c0d1
1up-lab/OneupUploaderBundle
Test against php71
commit 15f3614144d72b166d82a3e1586c2e66a357c0d1 Author: David Greminger <[email protected]> Date: Thu Dec 15 12:25:03 2016 +0100 Test against php71 diff --git a/.travis.yml b/.travis.yml index 7884714..0e69924 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ php: - 5.5 - 5.6 - 7.0 + - 7.1 - hhvm env:
0
ba5679ec441b4e85ae1655f722186396cc9e1a09
1up-lab/OneupUploaderBundle
Test the story if directories dont exist.
commit ba5679ec441b4e85ae1655f722186396cc9e1a09 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 21:57:30 2013 +0200 Test the story if directories dont exist. diff --git a/Tests/Uploader/Chunk/ChunkManagerTest.php b/Tests/Uploader/Chunk/ChunkManagerTest.php index 85967a9..995b9c2 100644 --- a/Tests/Uploader/Chunk/ChunkManagerTest.php +++ b/Tests/Uploader/Chunk/ChunkManagerTest.php @@ -25,15 +25,6 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase public function tearDown() { $system = new Filesystem(); - $finder = new Finder(); - - // first remove every file in temporary directory - foreach($finder->in($this->tmpDir) as $file) - { - $system->remove($file); - } - - // and finally remove the directory itself $system->remove($this->tmpDir); } @@ -80,6 +71,18 @@ class ChunkManagerTest extends \PHPUnit_Framework_TestCase } } + public function testClearIfDirectoryDoesNotExist() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->tmpDir); + + $manager = $this->getManager(10); + $manager->clear(); + + // yey, no exception + $this->assertTrue(true); + } + protected function getManager($maxage) { return new ChunkManager(array( diff --git a/Tests/Uploader/Orphanage/OrphanageManagerTest.php b/Tests/Uploader/Orphanage/OrphanageManagerTest.php index 2c331b8..2404d37 100644 --- a/Tests/Uploader/Orphanage/OrphanageManagerTest.php +++ b/Tests/Uploader/Orphanage/OrphanageManagerTest.php @@ -78,6 +78,18 @@ class OrphanageManagerTest extends \PHPUnit_Framework_TestCase $this->assertCount($this->numberOfOrphans / 2, $finder); } + public function testClearIfDirectoryDoesNotExist() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->mockConfig['directory']); + + $manager = new OrphanageManager($this->mockContainer, $this->mockConfig); + $manager->clear(); + + // yey, no exception + $this->assertTrue(true); + } + protected function getContainerMock() { $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
0
58b77cf8b2250009543983015708a8b1de372d8d
1up-lab/OneupUploaderBundle
Correctly cast to int (see #316)
commit 58b77cf8b2250009543983015708a8b1de372d8d Author: David Greminger <[email protected]> Date: Wed Feb 7 15:18:09 2018 +0100 Correctly cast to int (see #316) diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index e026473..563bb94 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -68,7 +68,7 @@ class BlueimpController extends AbstractChunkedController // any idea to fix this without fetching information about // previously saved files, let me know. $size = ($endByte + 1 - $startByte); - $last = ($endByte + 1) === $totalBytes; + $last = ((int) $endByte + 1) === (int) $totalBytes; $index = $last ? \PHP_INT_MAX : floor($startByte / $size); // it is possible, that two clients send a file with the diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index a3783f5..95d7784 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -43,7 +43,7 @@ class DropzoneController extends AbstractChunkedController { $totalChunkCount = $request->get('dztotalchunkcount'); $index = $request->get('dzchunkindex'); - $last = ($index + 1) === (int) $totalChunkCount; + $last = ((int) $index + 1) === (int) $totalChunkCount; $uuid = $request->get('dzuuid'); /** diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index a2ba606..3357cb7 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -44,7 +44,7 @@ class FineUploaderController extends AbstractChunkedController $total = $request->get('qqtotalparts'); $uuid = $request->get('qquuid'); $orig = $request->get('qqfilename'); - $last = ($total - 1) === $index; + $last = ((int) $total - 1) === (int) $index; return [$last, $uuid, $index, $orig]; } diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index 6d8082c..16d22ac 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -76,7 +76,7 @@ class MooUploadController extends AbstractChunkedController // size is 0 } - $last = $headers->get('x-file-size') === ($size + $headers->get('content-length')); + $last = (int) $headers->get('x-file-size') === ($size + (int) $headers->get('content-length')); // store also to response object $this->response->setFinish($last); diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index 0250ae7..4697d38 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -36,7 +36,7 @@ class PluploadController extends AbstractChunkedController $orig = $request->get('name'); $index = $request->get('chunk'); - $last = $request->get('chunks') - 1 === $request->get('chunk'); + $last = (int) $request->get('chunks') - 1 === (int) $request->get('chunk'); // it is possible, that two clients send a file with the // exact same filename, therefore we have to add the session
0
4cf73508bf6676454fcaed4b1d63f59817317153
1up-lab/OneupUploaderBundle
Minor improvements * Updated Dropzone's url * Added style to make dropzone visible immediately
commit 4cf73508bf6676454fcaed4b1d63f59817317153 Author: Thomas Landauer <[email protected]> Date: Sun Oct 25 19:53:32 2015 +0100 Minor improvements * Updated Dropzone's url * Added style to make dropzone visible immediately diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md index 66fc318..875fb3d 100644 --- a/Resources/doc/frontend_dropzone.md +++ b/Resources/doc/frontend_dropzone.md @@ -4,9 +4,9 @@ Use Dropzone in your Symfony2 application Download [Dropzone](http://www.dropzonejs.com/) and include it in your template. Connect the `action` property of the form to the dynamic route `_uploader_{mapping_name}`. ```html -<script type="text/javascript" src="https://rawgithub.com/enyo/dropzone/master/downloads/dropzone.js"></script> +<script type="text/javascript" src="https://raw.github.com/enyo/dropzone/master/dist/dropzone.js"></script> -<form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone"> +<form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone" style="width:200px; height:200px; border:4px dashed black"> </form> ```
0
9dce81dd52fef5195e16113de8443c62531e9234
1up-lab/OneupUploaderBundle
Merge pull request #120 from umpirsky/patch-1 Filesystem is already in parent class
commit 9dce81dd52fef5195e16113de8443c62531e9234 (from 4967f7c84a6847a4802cb2b808f807bde95aae46) Merge: 4967f7c 32a4efa Author: Jim Schmid <[email protected]> Date: Fri Jul 18 15:07:48 2014 +0200 Merge pull request #120 from umpirsky/patch-1 Filesystem is already in parent class diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php index 446ae14..39c9234 100644 --- a/Uploader/File/GaufretteFile.php +++ b/Uploader/File/GaufretteFile.php @@ -9,14 +9,12 @@ use Gaufrette\Adapter\AwsS3; class GaufretteFile extends File implements FileInterface { - protected $filesystem; protected $streamWrapperPrefix; protected $mimeType; public function __construct(File $file, Filesystem $filesystem, $streamWrapperPrefix = null) { parent::__construct($file->getKey(), $filesystem); - $this->filesystem = $filesystem; $this->streamWrapperPrefix = $streamWrapperPrefix; } commit 9dce81dd52fef5195e16113de8443c62531e9234 (from 32a4efa1a87d5c7caa65d7d2a1a28d533fbc2738) Merge: 4967f7c 32a4efa Author: Jim Schmid <[email protected]> Date: Fri Jul 18 15:07:48 2014 +0200 Merge pull request #120 from umpirsky/patch-1 Filesystem is already in parent class diff --git a/.travis.yml b/.travis.yml index bd24695..1d74818 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,27 @@ language: php php: - - 5.3 - - 5.4 - - 5.5 + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - hhvm env: - SYMFONY_VERSION=2.3.* - - SYMFONY_VERSION=2.4.* - - SYMFONY_VERSION=2.5.* + +matrix: + allow_failures: + - env: SYMFONY_VERSION=dev-master + - php: hhvm + include: + - php: 5.5 + env: SYMFONY_VERSION=2.4.* + - php: 5.5 + env: SYMFONY_VERSION=2.5.* + - php: 5.5 + env: SYMFONY_VERSION=dev-master before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source - - composer install --dev --prefer-source \ No newline at end of file + - composer install --dev --prefer-source
0
ae80b3658e05ad1dcdd96bff6ca5de364f21556f
1up-lab/OneupUploaderBundle
Documented the four supported frontend libraries.
commit ae80b3658e05ad1dcdd96bff6ca5de364f21556f Author: Jim Schmid <[email protected]> Date: Thu Apr 11 21:47:36 2013 +0200 Documented the four supported frontend libraries. diff --git a/README.md b/README.md index f22a936..f87ca55 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ The OneupUploaderBundle adds support for handling file uploads using one of the Features included: -* Multiple file uploads handled by Fine Uploader +* Multiple file uploads handled by your chosen frontend library * Chunked uploads * Supports [Gaufrette](https://github.com/KnpLabs/Gaufrette) and/or local filesystem * Provides an orphanage for cleaning up orphaned files diff --git a/Resources/doc/frontend_blueimp.md b/Resources/doc/frontend_blueimp.md new file mode 100644 index 0000000..1b4e63a --- /dev/null +++ b/Resources/doc/frontend_blueimp.md @@ -0,0 +1,32 @@ +Use jQuery File Upload +====================== + +Download [jQuery File Upload](http://blueimp.github.io/jQuery-File-Upload/) and include it in your template. Connect the `data-url` property on the HTML element to the dynamic route `_uploader_{mapping_name}`. + +```html +<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> +<script type="text/javascript" src="js/jquery.ui.widget.js"></script> +<script type="text/javascript" src="js/jquery.iframe-transport.js"></script> +<script type="text/javascript" src="js/jquery.fileupload.js"></script> +<script type="text/javascript"> +$(document).ready(function() +{ + $('#fileupload').fileupload({}); +}); +</script> + +<input id="fileupload" type="file" name="files[]" data-url="{{ path('_uploader_gallery') }}" multiple /> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: blueimp +``` + +Be sure to check out the [official manual](https://github.com/blueimp/jQuery-File-Upload#jquery-file-upload-plugin) for details on the configuration. \ No newline at end of file diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md new file mode 100644 index 0000000..dbe3d67 --- /dev/null +++ b/Resources/doc/frontend_fineuploader.md @@ -0,0 +1,37 @@ +Use FineUploader +================ + +Download [FineUploader](http://fineuploader.com/) and include it in your template. Connect the `endpoint` property to the dynamic route `_uploader_{mapping_name}`. + +```html +<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> +<script type="text/javascript" src="js/jquery.fineuploader-3.4.1.js"></script> +<script type="text/javascript"> +$(document).ready(function() +{ + var uploader = new qq.FineUploader({ + element: $('#uploader'), + request: { + endpoint: "{{ path('_uploader_gallery') }}" + } + }); +}); +</script> + +<div id="uploader"></div> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: fineuploader +``` + +> Actually, `fineuploader` is the default value, so you don't have to provide it manually. + +Be sure to check out the [official manual](https://github.com/Widen/fine-uploader/blob/master/readme.md) for details on the configuration. \ No newline at end of file diff --git a/Resources/doc/frontend_uploadify.md b/Resources/doc/frontend_uploadify.md new file mode 100644 index 0000000..78a3dbe --- /dev/null +++ b/Resources/doc/frontend_uploadify.md @@ -0,0 +1,37 @@ +Use Uploadify +============= + +Download [Uploadify](http://www.uploadify.com/download/) and include it in your template. Connect the `uploader` property to the dynamic route `_uploader_{mapping_name}` and include the FlashUploader file. + +> If you are using UploadiFive, please drop me a note. I'd like to know if this bundle also works works for the HTML5-Version of this frontend library. + +```html + +<script type="text/javascript" src="{{ asset('bundles/acmedemo/js/jquery.uploadify.js') }}"></script> +<script type="text/javascript"> +$(document).ready(function() +{ + $('#fileupload').uploadify( + { + swf: "{{ asset('bundles/acmedemo/js/uploadify.swf') }}", + uploader: "{{ path('_uploader_gallery') }}" + }); + +}); +</script> + +<div id="fileupload" /> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: uploadify +``` + +Be sure to check out the [official manual](http://www.uploadify.com/documentation/) for details on the configuration. \ No newline at end of file diff --git a/Resources/doc/frontend_yui3.md b/Resources/doc/frontend_yui3.md new file mode 100644 index 0000000..5b267fd --- /dev/null +++ b/Resources/doc/frontend_yui3.md @@ -0,0 +1,39 @@ +Use YUI3 Upload +=============== + +Download [YUI3 Upload](http://yuilibrary.com/yui/docs/uploader/) and include it in your template. Connect the `uploadURL` property to the dynamic route `_uploader_{mapping_name}`. + +```html +<script src="http://yui.yahooapis.com/3.9.1/build/yui/yui-min.js"></script> +<script> +YUI().use('uploader', function (Y) { + + var uploader = new Y.Uploader( + { + multipleFiles: true, + uploadURL: "{{ path('_uploader_gallery') }}" + }).render("#fileupload"); + + uploader.on('fileselect', function() + { + uploader.uploadAll(); + }); + +}); +</script> + +<div id="fileupload" /> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: yui3 +``` + +Be sure to check out the [official manual](http://yuilibrary.com/yui/docs/uploader/) for details on the configuration. \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index d6c9855..6cd7a2c 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -84,27 +84,16 @@ oneup_uploader: ### Step 4: Prepare your frontend -As this is a server implementation for Fine Uploader, you have to include this library in order to upload files through this bundle. You can find them on the [official page](http://fineuploader.com) of Fine Uploader. Be sure to connect the endpoint property to the dynamic route created from your mapping. It has the following form: +Currently the OneupUploaderBundle supports four different kind of frontends. ([FineUploader](http://fineuploader.com/), [jQuery File Uploader](http://blueimp.github.io/jQuery-File-Upload/), [YUI3 Uploader](http://yuilibrary.com/yui/docs/uploader/), [Uploadify](http://www.uploadify.com/)) No matter what library you choose, be sure to connect the corresponding endpoint property to the dynamic route created from your mapping. It has the following form: _uploader_{mapping_key} + +So if you take the mapping described before, the generated route name would be `_uploader_gallery`. Follow one of the listed guides to include your frontend: -```html -<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> -<script type="text/javascript" src="js/jquery.fineuploader-3.4.1.js"></script> -<script type="text/javascript"> -$(document).ready(function() -{ - var uploader = new qq.FineUploader({ - element: $('#uploader'), - request: { - endpoint: "{{ path('_uploader_gallery') }}" - } - }); -}); -</script> - -<div id="uploader"></div> -``` +* [Use FineUploader](frontend_fineuploader.md) +* [Use jQuery File Upload](frontend_blueimp.md) +* [Use YUI3 Uploader](frontend_yui3.md) +* [Use Uploadify](frontend_uploadify.md) This is of course a very minimal setup. Be sure to include stylesheets for Fine Uploader if you want to use them.
0
5cb66bed0c0aa9f889ad767944de0ed74357e564
1up-lab/OneupUploaderBundle
Test Symfony 3.x
commit 5cb66bed0c0aa9f889ad767944de0ed74357e564 Author: David Greminger <[email protected]> Date: Fri Sep 15 17:34:01 2017 +0200 Test Symfony 3.x diff --git a/.travis.yml b/.travis.yml index 0e69924..537eef5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,12 +6,13 @@ php: - 5.6 - 7.0 - 7.1 - - hhvm env: - - SYMFONY_VERSION=2.4.* - SYMFONY_VERSION=2.7.* - SYMFONY_VERSION=2.8.* + - SYMFONY_VERSION=3.2.* + - SYMFONY_VERSION=3.3.* + - SYMFONY_VERSION=dev-master cache: directories: @@ -19,27 +20,8 @@ cache: matrix: allow_failures: - - php: hhvm - - php: 7.0 - - php: 7.1 - env: SYMFONY_VERSION=dev-master - include: - - php: 5.6 - env: SYMFONY_VERSION=2.4.* - - php: 5.6 - env: SYMFONY_VERSION=2.5.* - - php: 5.6 - env: SYMFONY_VERSION=2.6.* - - php: 5.6 - env: SYMFONY_VERSION=2.7.* - - php: 5.6 - env: SYMFONY_VERSION=2.8.* - - php: 5.6 - env: SYMFONY_VERSION=3.0.* - - php: 5.6 - env: SYMFONY_VERSION=dev-master - before_script: - composer selfupdate - composer require symfony/http-kernel:${SYMFONY_VERSION} --prefer-source diff --git a/composer.json b/composer.json index a5cea42..f3ebce1 100644 --- a/composer.json +++ b/composer.json @@ -16,19 +16,22 @@ "require": { "php":">=5.4", - "symfony/framework-bundle": "^2.4.0|~3.0", - "symfony/finder": "^2.4.0|~3.0", + "symfony/framework-bundle": "^2.8|^3.0", + "symfony/finder": "^2.4.0|^3.0", + "symfony/translation": "^2.4.0|^3.0", + "symfony/asset": "^2.4.0|^3.0", + "symfony/templating": "^2.4.0|^3.0", "paragonie/random_compat": "^1.1" }, "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", "knplabs/gaufrette": "0.2.*@dev", - "symfony/class-loader": "2.*|~3.0", - "symfony/security-bundle": "2.*|~3.0", - "sensio/framework-extra-bundle": "2.*|~3.0", - "symfony/browser-kit": "2.*|~3.0", - "phpunit/phpunit": "~4.4", + "symfony/class-loader": "2.*|^3.0", + "symfony/security-bundle": "2.*|^3.0", + "sensio/framework-extra-bundle": "2.*|^3.0", + "symfony/browser-kit": "2.*|^3.0", + "phpunit/phpunit": "^4.4", "oneup/flysystem-bundle": "^1.2" },
0
b068ec3854b32a62367b56bab04d773628aad895
1up-lab/OneupUploaderBundle
Added a per-frontend configurable ErrorHandler.
commit b068ec3854b32a62367b56bab04d773628aad895 Author: Jim Schmid <[email protected]> Date: Sun Jul 14 23:08:43 2013 +0200 Added a per-frontend configurable ErrorHandler. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index c72861e..4adb51e 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -16,6 +16,7 @@ use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Oneup\UploaderBundle\Uploader\Exception\ValidationException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; abstract class AbstractController { @@ -24,8 +25,9 @@ abstract class AbstractController protected $config; protected $type; - public function __construct(ContainerInterface $container, StorageInterface $storage, array $config, $type) + public function __construct(ContainerInterface $container, StorageInterface $storage, ErrorHandlerInterface $errorHandler, array $config, $type) { + $this->errorHandler = $errorHandler; $this->container = $container; $this->storage = $storage; $this->config = $config; diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 607797b..7ab6fe0 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -28,8 +28,7 @@ class BlueimpController extends AbstractChunkedController $this->handleUpload($file, $response, $request) ; } catch (UploadException $e) { - // return nothing - return new JsonResponse(array()); + $this->errorHandler->addException($response, $e); } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 9b4c457..6a1736f 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -70,6 +70,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('disallowed_mimetypes') ->prototype('scalar')->end() ->end() + ->scalarNode('error_handler')->defaultValue('oneup_uploader.error_handler.noop')->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->booleanNode('use_orphanage')->defaultFalse()->end() ->booleanNode('enable_progress')->defaultFalse()->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index d1435fa..b83a59a 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -23,6 +23,7 @@ class OneupUploaderExtension extends Extension $loader->load('uploader.xml'); $loader->load('templating.xml'); $loader->load('validators.xml'); + $loader->load('errorhandler.xml'); if ($config['twig']) { $loader->load('twig.xml'); @@ -115,6 +116,8 @@ class OneupUploaderExtension extends Extension if(empty($controllerName) || empty($controllerType)) throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); } + + $errorHandler = new Reference($mapping['error_handler']); // create controllers based on mapping $container @@ -122,6 +125,7 @@ class OneupUploaderExtension extends Extension ->addArgument(new Reference('service_container')) ->addArgument($storageService) + ->addArgument($errorHandler) ->addArgument($mapping) ->addArgument($key) diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml new file mode 100644 index 0000000..025e38a --- /dev/null +++ b/Resources/config/errorhandler.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="utf-8" ?> +<container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + + <parameters> + <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter> + <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter> + </parameters> + + <services> + <service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false" /> + </services> + +</container> diff --git a/Resources/config/validators.xml b/Resources/config/validators.xml index 8f435c5..5b2ffe0 100644 --- a/Resources/config/validators.xml +++ b/Resources/config/validators.xml @@ -8,7 +8,7 @@ <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener" > + <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> diff --git a/Uploader/ErrorHandler/BlueimpErrorHandler.php b/Uploader/ErrorHandler/BlueimpErrorHandler.php new file mode 100644 index 0000000..5187f90 --- /dev/null +++ b/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -0,0 +1,15 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class BlueimpErrorHandler implements ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception) + { + $response->addToOffset($exception->getMessage(), 'files'); + } +} diff --git a/Uploader/ErrorHandler/ErrorHandlerInterface.php b/Uploader/ErrorHandler/ErrorHandlerInterface.php new file mode 100644 index 0000000..9b7a50a --- /dev/null +++ b/Uploader/ErrorHandler/ErrorHandlerInterface.php @@ -0,0 +1,11 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +interface ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception); +} diff --git a/Uploader/ErrorHandler/NoopErrorHandler.php b/Uploader/ErrorHandler/NoopErrorHandler.php new file mode 100644 index 0000000..e131408 --- /dev/null +++ b/Uploader/ErrorHandler/NoopErrorHandler.php @@ -0,0 +1,15 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class NoopErrorHandler implements ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception) + { + // noop + } +}
0
50b4e960d836b403c1623c130bd59431f084f07c
1up-lab/OneupUploaderBundle
The orphanage is now always on your local filesystem due to some restrictions found.
commit 50b4e960d836b403c1623c130bd59431f084f07c Author: Jim Schmid <[email protected]> Date: Fri Apr 5 18:03:30 2013 +0200 The orphanage is now always on your local filesystem due to some restrictions found. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 6fc060c..b59d866 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -25,7 +25,6 @@ class Configuration implements ConfigurationInterface ->arrayNode('orphanage') ->addDefaultsIfNotSet() ->children() - ->booleanNode('enabled')->defaultFalse()->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->scalarNode('directory')->defaultNull()->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index bf67881..c90c5cd 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -20,12 +20,12 @@ class OneupUploaderExtension extends Extension $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); - $config['chunks']['directory'] = !array_key_exists('directory', $config['chunks']) ? + $config['chunks']['directory'] = is_null($config['chunks']['directory']) ? sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')) : $this->normalizePath($config['chunks']['directory']) ; - $config['orphanage']['directory'] = !array_key_exists('directory', $config['orphanage']) ? + $config['orphanage']['directory'] = is_null($config['orphanage']['directory']) ? sprintf('%s/uploader/orphanage', $container->getParameter('kernel.cache_dir')) : $this->normalizePath($config['orphanage']['directory']) ; @@ -74,6 +74,24 @@ class OneupUploaderExtension extends Extension } $storageService = new Reference($storageName); + + if($mapping['use_orphanage']) + { + $orphanageName = sprintf('oneup_uploader.orphanage.%s', $key); + + // this mapping wants to use the orphanage, so create + // a masked filesystem for the controller + $container + ->register($orphanageName, $container->getParameter('oneup_uploader.orphanage.class')) + ->addArgument($storageService) + ->addArgument(new Reference('session')) + ->addArgument($config['orphanage']) + ->addArgument($key) + ; + + // switch storage of mapping to orphanage + $storageService = new Reference($orphanageName); + } } // create controllers based on mapping diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index e8f6be2..c252a84 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -8,7 +8,7 @@ <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> - <parameter key="oneup_uploader.storage.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> + <parameter key="oneup_uploader.storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> <parameter key="oneup_uploader.storage.filesystem.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\OrphanageStorage</parameter> <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> @@ -16,9 +16,6 @@ <services> - <!-- storage --> - <service id="oneup_uploader.filesystem_storage" class="%oneup_uploader.storage.filesystem.class%" /> - <!-- managers --> <service id="oneup_uploader.chunk_manager" class="%oneup_uploader.chunks.manager.class%"> <argument>%oneup_uploader.chunks%</argument> diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/OrphanageStorage.php index 3d9fae7..f048df2 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -4,25 +4,25 @@ namespace Oneup\UploaderBundle\Uploader\Storage; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\File\File; -use Gaufrette\Filesystem as GaufretteFilesystem; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; -use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; +use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Storage\OrphanageStorageInterface; -class OrphanageStorage extends GaufretteStorage implements OrphanageStorageInterface +class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInterface { - protected $orphanage; - protected $masked; + protected $storage; protected $session; protected $config; protected $type; - public function __construct(GaufretteFilesystem $orphanage, GaufretteFilesystem $filesystem, SessionInterface $session, $config, $type) + public function __construct(StorageInterface $storage, SessionInterface $session, $config, $type) { - parent::__construct($orphanage); + parent::__construct($config['directory']); - $this->orphanage = $orphanage; - $this->masked = $filesystem; + $this->storage = $storage; $this->session = $session; $this->config = $config; $this->type = $type; @@ -33,48 +33,38 @@ class OrphanageStorage extends GaufretteStorage implements OrphanageStorageInter if(!$this->session->isStarted()) throw new \RuntimeException('You need a running session in order to run the Orphanage.'); - // generate a path based on session id - $path = $this->getPath(); - - return parent::upload($file, $name, $path); + return parent::upload($file, $name, $this->getPath()); } - public function uploadFiles($keep = false) + public function uploadFiles() { - // switch orphanage with masked filesystem - $this->filesystem = $this->masked; + $filesystem = new Filesystem(); + $files = $this->getFiles(); + $return = array(); - $uploaded = array(); - foreach($this->getFiles() as $file) + foreach($files as $file) { - $uploaded[] = parent::upload(new File($this->getWrapper($file)), str_replace($this->getPath(), '', $file)); - - if(!$keep) - { - $this->orphanage->delete($file); - } + $return[] = $this->storage->upload(new File($file->getPathname()), str_replace($this->getFindPath(), '', $file)); } - return $uploaded; + return $return; } - public function getFiles() + protected function getFiles() { - $keys = $this->orphanage->listKeys($this->getPath()); + $finder = new Finder(); + $finder->in($this->getFindPath())->files(); - return $keys['keys']; + return $finder; } protected function getPath() { - $id = $this->session->getId(); - $path = sprintf('%s/%s/%s', $this->config['directory'], $id, $this->type); - - return $path; + return sprintf('%s/%s', $this->session->getId(), $this->type); } - protected function getWrapper($key) + protected function getFindPath() { - return sprintf('gaufrette://%s/%s', $this->config['domain'], $key); + return sprintf('%s/%s', $this->config['directory'], $this->getPath()); } } \ No newline at end of file diff --git a/Uploader/Storage/OrphanageStorageInterface.php b/Uploader/Storage/OrphanageStorageInterface.php index de0eb47..cfd9acb 100644 --- a/Uploader/Storage/OrphanageStorageInterface.php +++ b/Uploader/Storage/OrphanageStorageInterface.php @@ -7,5 +7,5 @@ use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; interface OrphanageStorageInterface extends StorageInterface { - public function uploadFiles($keep = false); + public function uploadFiles(); }
0
223e4369af3adc417bdeb7bc2c5a34e831022232
1up-lab/OneupUploaderBundle
Added Symfony2 version 2.5 to automated tests and dropped 2.2
commit 223e4369af3adc417bdeb7bc2c5a34e831022232 Author: Jim Schmid <[email protected]> Date: Wed Jun 25 13:55:25 2014 +0200 Added Symfony2 version 2.5 to automated tests and dropped 2.2 diff --git a/.travis.yml b/.travis.yml index 3381bd6..e3c5391 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,9 +5,9 @@ php: - 5.4 env: - - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* - SYMFONY_VERSION=2.4.* + - SYMFONY_VERSION=2.5.* before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source
0
a9baa108d35267b8625c8f704361a99ad43e15d9
1up-lab/OneupUploaderBundle
Added a CompilerPass for tagged Controllers.
commit a9baa108d35267b8625c8f704361a99ad43e15d9 Author: Jim Schmid <[email protected]> Date: Tue Mar 12 16:07:01 2013 +0100 Added a CompilerPass for tagged Controllers. diff --git a/DependencyInjection/Compiler/ControllerCompilerPass.php b/DependencyInjection/Compiler/ControllerCompilerPass.php new file mode 100644 index 0000000..a56ea90 --- /dev/null +++ b/DependencyInjection/Compiler/ControllerCompilerPass.php @@ -0,0 +1,25 @@ +<?php + +namespace Oneup\UploaderBundle\DependencyInjection\Compiler; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +class ControllerCompilerPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container) + { + $tags = $container->findTaggedServiceIds('oneup_uploader.routable'); + + if(count($tags) > 0 && $container->hasDefinition('oneup_uploader.routing.loader')) + { + $loader = $container->getDefinition('oneup_uploader.routing.loader'); + + foreach($tags as $id => $tag) + { + $loader->addMethodCall('addController', array($tag[0]['type'], $id)); + } + } + } +} \ No newline at end of file
0
587936016b1d4b906b7d27401cb3ba4c1aa9d609
1up-lab/OneupUploaderBundle
Changed link to issue tracker
commit 587936016b1d4b906b7d27401cb3ba4c1aa9d609 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 09:50:10 2013 +0300 Changed link to issue tracker diff --git a/README.md b/README.md index 79d7905..857764b 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ This bundle is under the MIT license. See the complete license in the bundle: Reporting an issue or a feature request --------------------------------------- -Issues and feature requests are tracked in the [Github issue tracker](https://github.com/Spea/SpBowerBundle/issues). +Issues and feature requests are tracked in the [Github issue tracker](https://github.com/1up-lab/OneupUploaderBundle/issues). When reporting a bug, it may be a good idea to reproduce it in a basic project built using the [Symfony Standard Edition](https://github.com/symfony/symfony-standard)
0
baac8e0db1250efaab681237e1f9cc48269e7270
1up-lab/OneupUploaderBundle
personalize upload path
commit baac8e0db1250efaab681237e1f9cc48269e7270 Author: MEDIA.figaro <[email protected]> Date: Wed Jun 22 18:03:44 2016 +0200 personalize upload path diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 0c18f92..5af1774 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -92,6 +92,19 @@ oneup_uploader: > It was reported that in some cases this directory was not created automatically. Please double check its existance if the upload does not work for you. > You can improve the directory structure checking the "[Change the directory structure](custom_namer.md#change-the-directory-structure)". +If you want to use your own path, for example /data/uploads : + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: dropzone + storage: + directory: "%kernel.root_dir%/../data/uploads/" +``` + ### Step 4: Prepare your frontend No matter what library you choose, be sure to connect the corresponding endpoint property to the dynamic route created from your mapping. To get a url for a specific mapping you can use the `oneup_uploader.templating.uploader_helper` service as follows:
0
a6c0d14eda9a30197178da8a9ba3cc81339bb90f
1up-lab/OneupUploaderBundle
Catch incoming InvalidArgumentExceptions which Finder will throw if the chunk-directory does not exist.
commit a6c0d14eda9a30197178da8a9ba3cc81339bb90f Author: Jim Schmid <[email protected]> Date: Mon Mar 11 13:39:15 2013 +0100 Catch incoming InvalidArgumentExceptions which Finder will throw if the chunk-directory does not exist. diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 1b184f5..4d1077d 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -25,7 +25,18 @@ class ChunkManager implements ChunkManagerInterface $system = new Filesystem(); $finder = new Finder(); - $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds'); + try + { + $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds'); + } + catch(\InvalidArgumentException $e) + { + // the finder will throw an exception of type InvalidArgumentException + // if the directory he should search in does not exist + // in that case we don't have anything to clean + return; + } + foreach($finder as $file) {
0
3b8ee6a453e57d6ce8fbd9635bcfcae517bea237
1up-lab/OneupUploaderBundle
Respect HTTP_ACCEPT header for content type of response. This was introduced in #55. I've moved this function up to the AbstractController and updated the upload controllers to use this function instead of forge a JsonResponse directly. Addresses #66.
commit 3b8ee6a453e57d6ce8fbd9635bcfcae517bea237 Author: Jim Schmid <[email protected]> Date: Wed Oct 30 16:04:02 2013 +0100 Respect HTTP_ACCEPT header for content type of response. This was introduced in #55. I've moved this function up to the AbstractController and updated the upload controllers to use this function instead of forge a JsonResponse directly. Addresses #66. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 03e14cb..fd78592 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -175,4 +175,27 @@ abstract class AbstractController $dispatcher->dispatch(UploadEvents::VALIDATION, $event); } + + /** + * Creates and returns a JsonResponse with the given data. + * + * On top of that, if the client does not support the application/json type, + * then the content type of the response will be set to text/plain instead. + * + * @param mixed $data + * + * @return JsonResponse + */ + protected function createSupportedJsonResponse($data) + { + $request = $this->container->get('request'); + $response = new JsonResponse($data); + $response->headers->set('Vary', 'Accept'); + + if (!in_array('application/json', $request->getAcceptableContentTypes())) { + $response->headers->set('Content-type', 'text/plain'); + } + + return $response; + } } diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 64e1b88..f9186c7 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Oneup\UploaderBundle\Controller\AbstractChunkedController; @@ -82,26 +81,4 @@ class BlueimpController extends AbstractChunkedController return array($last, $uuid, $index, $orig); } - - /** - * Creates and returns a JsonResponse with the given data. - * - * On top of that, if the client does not support the application/json type, - * then the content type of the response will be set to text/plain instead. - * - * @param mixed $data - * - * @return JsonResponse - */ - private function createSupportedJsonResponse($data) - { - $request = $this->container->get('request'); - $response = new JsonResponse($data); - $response->headers->set('Vary', 'Accept'); - if (!in_array('application/json', $request->getAcceptableContentTypes())) { - $response->headers->set('Content-type', 'text/plain'); - } - - return $response; - } } diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index b7b6e94..0c8a5b0 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; @@ -24,6 +23,6 @@ class DropzoneController extends AbstractController } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } } diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index e36979e..bc21006 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; @@ -24,6 +23,6 @@ class FancyUploadController extends AbstractController } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } } diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index e279e8b..246b7f6 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Oneup\UploaderBundle\Controller\AbstractChunkedController; @@ -34,11 +33,11 @@ class FineUploaderController extends AbstractChunkedController $this->errorHandler->addException($response, $e); // an error happended, return this error message. - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } protected function parseChunkedRequest(Request $request) diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index a33ee43..e4f055b 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -4,7 +4,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Oneup\UploaderBundle\Controller\AbstractChunkedController; @@ -50,10 +49,10 @@ class MooUploadController extends AbstractChunkedController $this->errorHandler->addException($response, $e); // return nothing - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } protected function parseChunkedRequest(Request $request) diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index 9f06c18..56cb151 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Oneup\UploaderBundle\Controller\AbstractChunkedController; @@ -30,7 +29,7 @@ class PluploadController extends AbstractChunkedController } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } protected function parseChunkedRequest(Request $request) diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index 8b8fcf3..ea68396 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; @@ -24,6 +23,6 @@ class UploadifyController extends AbstractController } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } } diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index 05d3bcb..c79e72b 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -3,7 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\JsonResponse; use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; @@ -24,6 +23,6 @@ class YUI3Controller extends AbstractController } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } } diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index 8043d1c..e3566d6 100644 --- a/Tests/Controller/AbstractChunkedUploadTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -46,7 +46,7 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($file)); + $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($file), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -89,7 +89,7 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest ++ $uploadCount; }); - $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($this->getNextFile($i))); + $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($this->getNextFile($i)), $this->requestHeaders); } $this->assertEquals($this->total, $chunkCount); diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index c584b7f..9e6d26a 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -10,6 +10,7 @@ abstract class AbstractControllerTest extends WebTestCase protected $createdFiles; protected $client; protected $container; + protected $requestHeaders; public function setUp() { @@ -17,6 +18,9 @@ abstract class AbstractControllerTest extends WebTestCase $this->container = $this->client->getContainer(); $this->helper = $this->container->get('oneup_uploader.templating.uploader_helper'); $this->createdFiles = array(); + $this->requestHeaders = array( + 'HTTP_ACCEPT' => 'application/json' + ); $this->container->get('router')->getRouteCollection()->all(); } @@ -63,13 +67,26 @@ abstract class AbstractControllerTest extends WebTestCase $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, array(), array(), array('HTTP_ACCEPT' => 'application/json')); + $client->request('POST', $endpoint, array(), array(), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); } + public function testEmptyHttpAcceptHeader() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + // empty HTTP_ACCEPT header + $client->request('POST', $endpoint, array(), array(), array()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'text/plain; charset=UTF-8'); + } + protected function createTempFile($size = 128) { $file = tempnam(sys_get_temp_dir(), 'uploader_'); diff --git a/Tests/Controller/AbstractUploadTest.php b/Tests/Controller/AbstractUploadTest.php index e84dd20..dd98b5e 100644 --- a/Tests/Controller/AbstractUploadTest.php +++ b/Tests/Controller/AbstractUploadTest.php @@ -25,7 +25,7 @@ abstract class AbstractUploadTest extends AbstractControllerTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile()), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 77a5bac..3688213 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -17,7 +17,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getOversizedFile())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getOversizedFile()), $this->requestHeaders); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful()); @@ -38,7 +38,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType()), $this->requestHeaders); $this->assertEquals(1, $validationCount); } @@ -60,7 +60,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType()), $this->requestHeaders); $this->assertEquals(1, $validationCount); } @@ -71,7 +71,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType()), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -93,7 +93,7 @@ abstract class AbstractValidationTest extends AbstractControllerTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithIncorrectMimeType())); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithIncorrectMimeType()), $this->requestHeaders); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful()); diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index c06c8d1..b9c3f82 100644 --- a/Tests/Controller/BlueimpTest.php +++ b/Tests/Controller/BlueimpTest.php @@ -16,7 +16,7 @@ class BlueimpTest extends AbstractUploadTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile(), array('HTTP_ACCEPT' => 'application/json')); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile(), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -41,7 +41,6 @@ class BlueimpTest extends AbstractUploadTest $this->assertTrue($response->isSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'text/plain; charset=UTF-8'); $this->assertCount(1, $this->getUploadedFiles()); - } public function testEvents() @@ -79,7 +78,7 @@ class BlueimpTest extends AbstractUploadTest $me->assertEquals('cat', $request->get('grumpy')); }); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile(), $this->requestHeaders); $this->assertCount(1, $this->getUploadedFiles()); $this->assertEquals($uploadCount, count($this->getUploadedFiles())); diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index 2aec2f7..7ba1307 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -14,7 +14,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile(), array('HTTP_ACCEPT' => 'application/json')); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile(), $this->requestHeaders); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful()); @@ -35,7 +35,7 @@ class BlueimpValidationTest extends AbstractValidationTest ++ $validationCount; }); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType(), $this->requestHeaders); $this->assertEquals(1, $validationCount); } @@ -46,7 +46,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType(), array('HTTP_ACCEPT' => 'application/json')); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType(), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -68,7 +68,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType(), array('HTTP_ACCEPT' => 'application/json')); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType(), $this->requestHeaders); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful());
0
ceaa3937689d50fd1f8e9a0dfee5b508fd01eb94
1up-lab/OneupUploaderBundle
Initialize with moved chunk file.
commit ceaa3937689d50fd1f8e9a0dfee5b508fd01eb94 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:06:00 2013 +0200 Initialize with moved chunk file. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index d659cf6..f32cc56 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -22,7 +22,7 @@ abstract class AbstractChunkedController extends AbstractController // get information about this chunked request list($last, $uuid, $index, $orig) = $this->parseChunkedRequest($request); - $chunkManager->addChunk($uuid, $index, $file, $orig); + $uploaded = $chunkManager->addChunk($uuid, $index, $file, $orig); // if all chunks collected and stored, proceed // with reassembling the parts
0
986b5636e61ddf2fa9e293a14ef20246124e4c9e
1up-lab/OneupUploaderBundle
Added initial composer.json file.
commit 986b5636e61ddf2fa9e293a14ef20246124e4c9e Author: Jim Schmid <[email protected]> Date: Fri Mar 8 17:57:20 2013 +0100 Added initial composer.json file. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..42ecd5c --- /dev/null +++ b/composer.json @@ -0,0 +1,14 @@ +{ + "name": "oneup/uploader-bundle", + "type": "symfony-bundle", + "description": "valums/file-uploader integration", + "keywords": ["fileupload", "upload", "multifileupload"], + "homepage": "http://1up.io", + "license": "MIT", + "authors": [ + { + "name": "Jim Schmid", + "email": "[email protected]" + } + ] +} \ No newline at end of file
0
d688bfbfa1c3fd6cd026038c1afffb07bedfefc5
1up-lab/OneupUploaderBundle
Added new getRequest method to documentation.
commit d688bfbfa1c3fd6cd026038c1afffb07bedfefc5 Author: Jim Schmid <[email protected]> Date: Sat Sep 14 15:37:08 2013 +0200 Added new getRequest method to documentation. diff --git a/Resources/doc/custom_validator.md b/Resources/doc/custom_validator.md index 37fa8c1..1f0ef03 100644 --- a/Resources/doc/custom_validator.md +++ b/Resources/doc/custom_validator.md @@ -15,9 +15,11 @@ class AlwaysFalseValidationListener { public function onValidate(ValidationEvent $event) { - $config = $event->getConfig(); - $file = $event->getFile(); - + $config = $event->getConfig(); + $file = $event->getFile(); + $type = $event->getType(); + $request = $event->getRequest(); + // do some validations throw new ValidationException('Sorry! Always false.'); }
0
eae52b2c241977c0b10994aeeccc88a8ecdb0335
1up-lab/OneupUploaderBundle
Improve installation steps
commit eae52b2c241977c0b10994aeeccc88a8ecdb0335 Author: JHGitty <[email protected]> Date: Sat Jan 30 16:24:39 2016 +0100 Improve installation steps diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 4178e9e..39ab715 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -34,19 +34,9 @@ Perform the following steps to install and use the basic functionality of the On Add OneupUploaderBundle to your composer.json using the following construct: -```js -{ - "require": { - "oneup/uploader-bundle": "~1.4" - } -} -``` - -Now tell composer to download the bundle by running the following command: - - $> php composer.phar update oneup/uploader-bundle + $ composer require oneup/uploader-bundle "~1.4" -Composer will now fetch and install this bundle in the vendor directory ```vendor/oneup``` +Composer will install the bundle to your project's ``vendor/oneup/uploader-bundle`` directory. ### Step 2: Enable the bundle
0
3745b3af2e19c7c8be02d6552bd2708b7f86d51d
1up-lab/OneupUploaderBundle
Update composer.json
commit 3745b3af2e19c7c8be02d6552bd2708b7f86d51d Author: Flavian <[email protected]> Date: Sun Apr 14 12:53:55 2013 +0300 Update composer.json diff --git a/composer.json b/composer.json index 8124134..a59d0c0 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "oneup/uploader-bundle", "type": "symfony-bundle", - "description": "Handle multi file uploads. Features included: Chunked upload, Orphans management, Gaufrette support.", + "description": "Handles multi file uploads in Symonfy2. Features included: Chunked upload, Orphans management, Gaufrette support.", "keywords": ["fileupload", "upload", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload", "Plupload"], "homepage": "http://1up.io", "license": "MIT", @@ -30,4 +30,4 @@ }, "target-dir": "Oneup/UploaderBundle" -} \ No newline at end of file +}
0
331f14afaa12ac997505d93160d6bff043200541
1up-lab/OneupUploaderBundle
Removed manual install of framework-bundle on travis
commit 331f14afaa12ac997505d93160d6bff043200541 Author: David Greminger <[email protected]> Date: Mon Jan 4 11:14:42 2016 +0100 Removed manual install of framework-bundle on travis diff --git a/.travis.yml b/.travis.yml index f81a416..1564c0e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -42,5 +42,4 @@ matrix: before_script: - composer selfupdate - composer require symfony/http-kernel:${SYMFONY_VERSION} --prefer-source - - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source - composer install --dev --prefer-source
0
69d6d93ccc6a09f625267bf5701df7e27df69c28
1up-lab/OneupUploaderBundle
Documented Plupload.
commit 69d6d93ccc6a09f625267bf5701df7e27df69c28 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 16:01:06 2013 +0200 Documented Plupload. diff --git a/README.md b/README.md index 48eb51b..292b3cb 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ The OneupUploaderBundle adds support for handling file uploads using one of the * [Uploadify](http://www.uploadify.com/) * [FancyUpload](http://digitarald.de/project/fancyupload/) * [MooUpload](https://github.com/juanparati/MooUpload) +* [Plupload](http://www.plupload.com/) Features included: diff --git a/Resources/doc/frontend_blueimp.md b/Resources/doc/frontend_blueimp.md index 1b4e63a..453dd54 100644 --- a/Resources/doc/frontend_blueimp.md +++ b/Resources/doc/frontend_blueimp.md @@ -29,4 +29,16 @@ oneup_uploader: frontend: blueimp ``` -Be sure to check out the [official manual](https://github.com/blueimp/jQuery-File-Upload#jquery-file-upload-plugin) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](https://github.com/blueimp/jQuery-File-Upload#jquery-file-upload-plugin) for details on the configuration. + +The jQuery File Upload library does not send a unique id along the file upload request. Because of that, we only have the filename as an information to distinguish uploads. It is possible though that two users upload a file with the same name at the same time. To further tell these files apart, the SessionId is used. If you provide anonymous uploads on your application, be sure to configure the firewall accordingly. + +```yml +# app/config/security.yml + +security: + firewalls: + main: + pattern: ^/ + anonymous: true +``` \ No newline at end of file diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md new file mode 100644 index 0000000..b27657c --- /dev/null +++ b/Resources/doc/frontend_plupload.md @@ -0,0 +1,50 @@ +Use Plupload in your Symfony2 application +========================================= + +Download [Plupload](http://http://www.plupload.com/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}`. + +```html +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> +<script type="text/javascript" src="http://bp.yahooapis.com/2.4.21/browserplus-min.js"></script> +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script> +<script type="text/javascript" src="http://www.plupload.com/plupload/js/plupload.full.js"></script> +<script type="text/javascript" src="http://www.plupload.com/plupload/js/jquery.ui.plupload/jquery.ui.plupload.js"></script> + +<script type="text/javascript"> +$(document).ready(function() +{ + $("#fileupload").plupload( + { + runtimes: "html5", + url: "{{ path('_uploader_gallery') }}" + }); +}); +</script> + +<div id="fileupload"></div> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: plupload +``` + +Be sure to check out the [official manual](http://www.plupload.com/documentation.php) for details on the configuration. + +The Plupload library does not send a unique id along the file upload request. Because of that, we only have the filename as an information to distinguish uploads. It is possible though that two users upload a file with the same name at the same time. To further tell these files apart, the SessionId is used. If you provide anonymous uploads on your application, be sure to configure the firewall accordingly. + +```yml +# app/config/security.yml + +security: + firewalls: + main: + pattern: ^/ + anonymous: true +``` \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 9b6afe0..2a49f75 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -98,6 +98,7 @@ So if you take the mapping described before, the generated route name would be ` * [Use Uploadify](frontend_uploadify.md) * [Use FancyUpload](frontend_fancyupload.md) * [Use MooUpload](frontend_mooupload.md) +* [Use Plupload](frontend_plupload.md) ## Next steps diff --git a/composer.json b/composer.json index 36f6e82..99e963e 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "oneup/uploader-bundle", "type": "symfony-bundle", "description": "Handle multi file uploads. Features included: Chunked upload, Orphans management, Gaufrette support.", - "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload"], + "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload", "Plupload"], "homepage": "http://1up.io", "license": "MIT", "authors": [
0
44fbde3a6aaec6a7364362386b5b63907ce6688d
1up-lab/OneupUploaderBundle
Fixed error when running tests in PHP5.3
commit 44fbde3a6aaec6a7364362386b5b63907ce6688d Author: Jim Schmid <[email protected]> Date: Sat Sep 14 16:51:44 2013 +0200 Fixed error when running tests in PHP5.3 diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 5461c6b..01b0a6d 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -73,9 +73,10 @@ abstract class AbstractValidationTest extends AbstractControllerTest // event data $validationCount = 0; + $me = $this; - $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $event->getRequest()); + $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount, &$me) { + $me->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $event->getRequest()); // to be sure this listener is called ++ $validationCount;
0
a832a6c9f8992fc4ec06579e13feb82f6ed64515
1up-lab/OneupUploaderBundle
Revert "Fix PHP 7.1 Notice: A non well formed numeric value" This reverts commit fc9d5c10e27136dad7865807c584db6471cfb658.
commit a832a6c9f8992fc4ec06579e13feb82f6ed64515 Author: David Greminger <[email protected]> Date: Thu Dec 15 09:33:29 2016 +0100 Revert "Fix PHP 7.1 Notice: A non well formed numeric value" This reverts commit fc9d5c10e27136dad7865807c584db6471cfb658. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 86fd9f6..0d472ff 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -292,7 +292,7 @@ class OneupUploaderExtension extends Extension protected function getValueInBytes($input) { // see: http://www.php.net/manual/en/function.ini-get.php - $input = (float) trim($input); + $input = trim($input); $last = strtolower($input[strlen($input) - 1]); $numericInput = substr($input, 0, -1);
0
b58c73839c1ca093733b92f6e1efaa8c271654e1
1up-lab/OneupUploaderBundle
Changed progress to progressRoute and introduced helper function progressKey
commit b58c73839c1ca093733b92f6e1efaa8c271654e1 Author: Jim Schmid <[email protected]> Date: Tue Jun 25 11:09:09 2013 +0200 Changed progress to progressRoute and introduced helper function progressKey diff --git a/Templating/Helper/UploaderHelper.php b/Templating/Helper/UploaderHelper.php index ffdfd91..a61efa5 100644 --- a/Templating/Helper/UploaderHelper.php +++ b/Templating/Helper/UploaderHelper.php @@ -24,8 +24,13 @@ class UploaderHelper extends Helper return $this->router->generate(sprintf('_uploader_upload_%s', $key)); } - public function progress($key) + public function progressRoute($key) { return $this->router->generate(sprintf('_uploader_progress_%s', $key)); } + + public function progressKey() + { + return ini_get('session.upload_progress.name'); + } } diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index 3e7d5da..4b23e2f 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -21,8 +21,9 @@ class UploaderExtension extends \Twig_Extension public function getFunctions() { return array( - 'oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint') - 'oneup_uploader_progress' => new \Twig_Function_Method($this, 'progress') + 'oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint'), + 'oneup_uploader_progress_route' => new \Twig_Function_Method($this, 'progressRoute'), + 'oneup_uploader_progress_key' => new \Twig_Function_Method($this, 'progressKey') ); } @@ -31,8 +32,13 @@ class UploaderExtension extends \Twig_Extension return $this->helper->endpoint($key); } - public function progress($key) + public function progressRoute($key) { - return $this->helper->progress($key); + return $this->helper->progressRoute($key); + } + + public function progressKey() + { + return $this->helper->progressKey(); } }
0
bd3efd06744782eda171a40e5ffe1f052d0e3b3f
1up-lab/OneupUploaderBundle
composer changed back to symfony 2.2
commit bd3efd06744782eda171a40e5ffe1f052d0e3b3f Author: Martin Aarhof <[email protected]> Date: Wed Dec 9 10:37:31 2015 +0100 composer changed back to symfony 2.2 diff --git a/composer.json b/composer.json index 59fc218..aa66e5d 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ ], "require": { - "symfony/framework-bundle": ">=2.4", + "symfony/framework-bundle": ">=2.2", "symfony/finder": ">=2.2.0" },
0
d5a149b431311e19ca6c8fab276c58bce30c58a6
1up-lab/OneupUploaderBundle
Merge branch 'feature/symfony3-support'
commit d5a149b431311e19ca6c8fab276c58bce30c58a6 (from 6102b3ad676f9e935506e7bac323c93b6f68e322) Merge: 6102b3a 7f0f7b1 Author: David Greminger <[email protected]> Date: Tue Sep 19 13:10:06 2017 +0200 Merge branch 'feature/symfony3-support' diff --git a/composer.json b/composer.json index 497d403..ab88f2d 100644 --- a/composer.json +++ b/composer.json @@ -16,19 +16,22 @@ "require": { "php":">=5.4", - "symfony/framework-bundle": "^2.4.0|~3.0", - "symfony/finder": "^2.4.0|~3.0", + "symfony/framework-bundle": "^2.4|^3.0", + "symfony/finder": "^2.4|^3.0", + "symfony/translation": "^2.4|^3.0", + "symfony/asset": "^2.4|^3.0", + "symfony/templating": "^2.4|^3.0", "paragonie/random_compat": "^1.1|^2.0" }, "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", "knplabs/gaufrette": "0.2.*@dev", - "symfony/class-loader": "2.*|~3.0", - "symfony/security-bundle": "2.*|~3.0", - "sensio/framework-extra-bundle": "2.*|~3.0", - "symfony/browser-kit": "2.*|~3.0", - "phpunit/phpunit": "~4.4", + "symfony/class-loader": "2.*|^3.0", + "symfony/security-bundle": "2.*|^3.0", + "sensio/framework-extra-bundle": "2.*|^3.0", + "symfony/browser-kit": "2.*|^3.0", + "phpunit/phpunit": "^4.4", "oneup/flysystem-bundle": "^1.2" }, commit d5a149b431311e19ca6c8fab276c58bce30c58a6 (from 7f0f7b112a36f27ab0cb18368698bf74b65f1967) Merge: 6102b3a 7f0f7b1 Author: David Greminger <[email protected]> Date: Tue Sep 19 13:10:06 2017 +0200 Merge branch 'feature/symfony3-support' diff --git a/.travis.yml b/.travis.yml index cd37eb1..15534ea 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,16 +1,12 @@ language: php php: - - 5.4 - - 5.5 - - 5.6 - 7.0 - 7.1 env: - SYMFONY_VERSION=2.7.* - SYMFONY_VERSION=2.8.* - - SYMFONY_VERSION=3.2.* - SYMFONY_VERSION=3.3.* - SYMFONY_VERSION=dev-master @@ -22,22 +18,6 @@ matrix: allow_failures: - env: SYMFONY_VERSION=dev-master - include: - - php: 5.6 - env: SYMFONY_VERSION=2.4.* - - php: 5.6 - env: SYMFONY_VERSION=2.5.* - - php: 5.6 - env: SYMFONY_VERSION=2.6.* - - php: 5.6 - env: SYMFONY_VERSION=2.7.* - - php: 5.6 - env: SYMFONY_VERSION=2.8.* - - php: 5.6 - env: SYMFONY_VERSION=3.0.* - - php: 5.6 - env: SYMFONY_VERSION=dev-master - before_install: - composer selfupdate
0
2453924a0f5f7f47ab828ced1aa99828a14d1ac3
1up-lab/OneupUploaderBundle
Changed $file to $chunk. Ref #180.
commit 2453924a0f5f7f47ab828ced1aa99828a14d1ac3 Author: Jim Schmid <[email protected]> Date: Mon Jun 15 09:50:45 2015 +0200 Changed $file to $chunk. Ref #180. diff --git a/Event/PostChunkUploadEvent.php b/Event/PostChunkUploadEvent.php index 9b32dfd..32e8fe7 100644 --- a/Event/PostChunkUploadEvent.php +++ b/Event/PostChunkUploadEvent.php @@ -8,7 +8,7 @@ use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; class PostChunkUploadEvent extends Event { - protected $file; + protected $chunk; protected $request; protected $type; protected $response;
0
4ef13b9dd7c46c84fad301674d7fd41611c8ee81
1up-lab/OneupUploaderBundle
Tests for UploaderResponse.
commit 4ef13b9dd7c46c84fad301674d7fd41611c8ee81 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 11:16:17 2013 +0200 Tests for UploaderResponse. diff --git a/Tests/Uploader/Response/UploaderResponseTest.php b/Tests/Uploader/Response/UploaderResponseTest.php new file mode 100644 index 0000000..a232436 --- /dev/null +++ b/Tests/Uploader/Response/UploaderResponseTest.php @@ -0,0 +1,61 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; + +class TestUploaderResponse extends \PHPUnit_Framework_TestCase +{ + public function testCreationOfResponse() + { + $response = new UploaderResponse(); + + $this->assertTrue($response->getSuccess()); + $this->assertNull($response->getError()); + } + + public function testFillOfResponse() + { + $response = new UploaderResponse(); + + $cat = 'is grumpy'; + $dog = 'has no idea'; + + $response['cat'] = $cat; + $response['dog'] = $dog; + $response->setSuccess(false); + + $assembled = $response->assemble(); + + $this->assertTrue(is_array($assembled)); + $this->assertArrayHasKey('cat', $assembled); + $this->assertArrayHasKey('dog', $assembled); + $this->assertEquals($assembled['cat'], $cat); + $this->assertEquals($assembled['dog'], $dog); + $this->assertFalse($response->getSuccess()); + $this->assertNull($response->getError()); + } + + public function testError() + { + $response = new UploaderResponse(); + $response->setError('This response is grumpy'); + + $this->assertEquals($response->getError(), 'This response is grumpy'); + } + + public function testOverwriteOfInternals() + { + $response = new UploaderResponse(); + $response['success'] = false; + $response['error'] = 42; + + $this->assertTrue($response->getSuccess()); + $this->assertNull($response->getError()); + + $assembled = $response->assemble(); + + $this->assertTrue($assembled['success']); + $this->assertArrayNotHasKey('error', $assembled); + } +} \ No newline at end of file
0
796f27f46fa2fd69583d46e2b1f6386d7566b023
1up-lab/OneupUploaderBundle
Merge pull request #34 from dirkluijk/patch-1 Renamed chunk_manager to chunks
commit 796f27f46fa2fd69583d46e2b1f6386d7566b023 (from c4b736752cbc14c6c909df51b8136973698f081c) Merge: c4b7367 b0e8666 Author: Jim Schmid <[email protected]> Date: Wed Jul 24 07:20:52 2013 -0700 Merge pull request #34 from dirkluijk/patch-1 Renamed chunk_manager to chunks diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index d649a14..4f5c5e1 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -29,7 +29,7 @@ You can configure the `ChunkManager` by using the following configuration parame ``` oneup_uploader: - chunk_manager: + chunks: maxage: 86400 directory: %kernel.cache_dir%/uploader/chunks ```
0
80722032f811e5b742c052b2f64ef1010b301073
1up-lab/OneupUploaderBundle
Update frontend_fineuploader.md
commit 80722032f811e5b742c052b2f64ef1010b301073 Author: Max Tobias Weber <[email protected]> Date: Wed Aug 14 12:03:32 2013 +0200 Update frontend_fineuploader.md diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md index 91a0f77..b024857 100644 --- a/Resources/doc/frontend_fineuploader.md +++ b/Resources/doc/frontend_fineuploader.md @@ -10,7 +10,7 @@ Download [FineUploader](http://fineuploader.com/) and include it in your templat $(document).ready(function() { var uploader = new qq.FineUploader({ - element: $('#uploader'), + element: $('#uploader')[0], request: { endpoint: "{{ oneup_uploader_endpoint('gallery') }}" } @@ -34,4 +34,4 @@ oneup_uploader: > Actually, `fineuploader` is the default value, so you don't have to provide it manually. -Be sure to check out the [official manual](https://github.com/Widen/fine-uploader/blob/master/readme.md) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](https://github.com/Widen/fine-uploader/blob/master/readme.md) for details on the configuration.
0
b6249188487f8558b3d160c674677ce5089916a3
1up-lab/OneupUploaderBundle
Added php71 to test matrix
commit b6249188487f8558b3d160c674677ce5089916a3 Author: David Greminger <[email protected]> Date: Thu Dec 15 10:24:03 2016 +0100 Added php71 to test matrix diff --git a/.travis.yml b/.travis.yml index c044e39..44b121f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,7 @@ matrix: allow_failures: - php: hhvm - php: 7.0 + - php: 7.1 - env: SYMFONY_VERSION=dev-master include:
0
b808587d5c344e14006699f9dad9f9762d1051ec
1up-lab/OneupUploaderBundle
Added a YUI3 implementation.
commit b808587d5c344e14006699f9dad9f9762d1051ec Author: Jim Schmid <[email protected]> Date: Thu Apr 11 20:29:09 2013 +0200 Added a YUI3 implementation. diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php new file mode 100644 index 0000000..8ade2ec --- /dev/null +++ b/Controller/YUI3Controller.php @@ -0,0 +1,40 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\Controller\AbstractController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class YUI3Controller extends AbstractController +{ + public function upload() + { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new EmptyResponse(); + $files = $request->files; + + foreach($files as $file) + { + try + { + $uploaded = $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + } + + return new JsonResponse($response->assemble()); + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 6e065bb..7298bec 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 454f024..6933114 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -14,6 +14,7 @@ <parameter key="oneup_uploader.controller.fineuploader.class">Oneup\UploaderBundle\Controller\FineUploaderController</parameter> <parameter key="oneup_uploader.controller.blueimp.class">Oneup\UploaderBundle\Controller\BlueimpController</parameter> <parameter key="oneup_uploader.controller.uploadify.class">Oneup\UploaderBundle\Controller\UploadifyController</parameter> + <parameter key="oneup_uploader.controller.yui3.class">Oneup\UploaderBundle\Controller\YUI3Controller</parameter> </parameters> <services>
0
8f243bf6f64a78decbd533ab1a57bc09a7a608a2
1up-lab/OneupUploaderBundle
Integrated BlueimpResponse.
commit 8f243bf6f64a78decbd533ab1a57bc09a7a608a2 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:51:57 2013 +0200 Integrated BlueimpResponse. diff --git a/Uploader/Response/BlueimpResponse.php b/Uploader/Response/BlueimpResponse.php index a4abe2d..8842b6b 100644 --- a/Uploader/Response/BlueimpResponse.php +++ b/Uploader/Response/BlueimpResponse.php @@ -1,2 +1,42 @@ <?php +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class FineUploaderResponse extends AbstractResponse +{ + protected $files; + + public function __construct() + { + $this->success = array(); + + parent::__construct(); + } + + public function assemble() + { + // explicitly overwrite success and error key + // as these keys are used internaly by the + // frontend uploader + $data = $this->data; + $data['files'] = $this->files; + + return $data; + } + + public function addFile($file) + { + $this->files[] = $file; + + return $this; + } + + public function setFiles(array $files) + { + $this->files = $files; + + return $this; + } +} \ No newline at end of file
0
3e8df9c49e2dfd7545c5f8906568e3ec94472cae
1up-lab/OneupUploaderBundle
Return the moved file after adding chunk.
commit 3e8df9c49e2dfd7545c5f8906568e3ec94472cae Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:04:33 2013 +0200 Return the moved file after adding chunk. diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 2403fd0..14f070e 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -49,7 +49,7 @@ class ChunkManager implements ChunkManagerInterface if(!$filesystem->exists($path)) $filesystem->mkdir(sprintf('%s/%s', $this->configuration['directory'], $uuid)); - $chunk->move($path, $name); + return $chunk->move($path, $name); } public function assembleChunks(\Traversable $chunks)
0
6d945791565861a543a4cc148c461d8a6dbab592
1up-lab/OneupUploaderBundle
Merge pull request #213 from lsv/integrate-flysystem Added league/flysystem to also be a possible filesystem
commit 6d945791565861a543a4cc148c461d8a6dbab592 (from ea2804ca78e8a139fcaf3f847997e9ff2a49b1a5) Merge: ea2804c 2bcb029 Author: David Greminger <[email protected]> Date: Thu Jan 28 15:48:42 2016 +0100 Merge pull request #213 from lsv/integrate-flysystem Added league/flysystem to also be a possible filesystem diff --git a/.travis.yml b/.travis.yml index 1564c0e..c044e39 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.3 - 5.4 - 5.5 - 5.6 diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 3374889..276ddf3 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -22,7 +22,7 @@ class Configuration implements ConfigurationInterface ->addDefaultsIfNotSet() ->children() ->enumNode('type') - ->values(array('filesystem', 'gaufrette')) + ->values(array('filesystem', 'gaufrette', 'flysystem')) ->defaultValue('filesystem') ->end() ->scalarNode('filesystem')->defaultNull()->end() @@ -65,7 +65,7 @@ class Configuration implements ConfigurationInterface ->children() ->scalarNode('service')->defaultNull()->end() ->enumNode('type') - ->values(array('filesystem', 'gaufrette')) + ->values(array('filesystem', 'gaufrette', 'flysystem')) ->defaultValue('filesystem') ->end() ->scalarNode('filesystem')->defaultNull()->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 7f35224..4a471c5 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -13,6 +13,10 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { protected $storageServices = array(); + + /** + * @var ContainerBuilder + */ protected $container; protected $config; @@ -141,31 +145,44 @@ class OneupUploaderExtension extends Extension $config = &$this->config['chunks']['storage']; $storageClass = sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type']); - if ($config['type'] === 'filesystem') { - $config['directory'] = is_null($config['directory']) ? - sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : - $this->normalizePath($config['directory']) - ; - - $this->container - ->register('oneup_uploader.chunks_storage', sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type'])) - ->addArgument($config['directory']) - ; - } else { - $this->registerGaufretteStorage( - 'oneup_uploader.chunks_storage', - $storageClass, $config['filesystem'], - $config['sync_buffer_size'], - $config['stream_wrapper'], - $config['prefix'] - ); - - $this->container->setParameter('oneup_uploader.orphanage.class', 'Oneup\UploaderBundle\Uploader\Storage\GaufretteOrphanageStorage'); - - // enforce load distribution when using gaufrette as chunk - // torage to avoid moving files forth-and-back - $this->config['chunks']['load_distribution'] = true; + + switch($config['type']) { + case 'filesystem': + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : + $this->normalizePath($config['directory']) + ; + + $this->container + ->register('oneup_uploader.chunks_storage', sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type'])) + ->addArgument($config['directory']) + ; + break; + case 'gaufrette': + case 'flysystem': + $this->registerFilesystem( + $config['type'], + 'oneup_uploader.chunks_storage', + $storageClass, $config['filesystem'], + $config['sync_buffer_size'], + $config['stream_wrapper'], + $config['prefix'] + ); + + $this->container->setParameter( + 'oneup_uploader.orphanage.class', + sprintf('Oneup\UploaderBundle\Uploader\Storage\%sOrphanageStorage', ucfirst($config['type'])) + ); + + // enforce load distribution when using gaufrette as chunk + // torage to avoid moving files forth-and-back + $this->config['chunks']['load_distribution'] = true; + break; + default: + throw new \InvalidArgumentException(sprintf('Filesystem "%s" is invalid', $config['type'])); + break; } + } protected function createStorageService(&$config, $key, $orphanage = false) @@ -181,26 +198,31 @@ class OneupUploaderExtension extends Extension $storageName = sprintf('oneup_uploader.storage.%s', $key); $storageClass = sprintf('%%oneup_uploader.storage.%s.class%%', $config['type']); - if ($config['type'] == 'filesystem') { - $config['directory'] = is_null($config['directory']) ? - sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : - $this->normalizePath($config['directory']) - ; - - $this->container - ->register($storageName, $storageClass) - ->addArgument($config['directory']) - ; - } - - if ($config['type'] == 'gaufrette') { - $this->registerGaufretteStorage( - $storageName, - $storageClass, - $config['filesystem'], - $config['sync_buffer_size'], - $config['stream_wrapper'] - ); + switch ($config['type']) { + case 'filesystem': + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : + $this->normalizePath($config['directory']) + ; + + $this->container + ->register($storageName, $storageClass) + ->addArgument($config['directory']) + ; + break; + case 'gaufrette': + case 'flysystem': + $this->registerFilesystem( + $config['type'], + $storageName, + $storageClass, + $config['filesystem'], + $config['sync_buffer_size'], + $config['stream_wrapper'] + ); + break; + default: + break; } $storageService = new Reference($storageName); @@ -227,12 +249,22 @@ class OneupUploaderExtension extends Extension return $storageService; } - protected function registerGaufretteStorage($key, $class, $filesystem, $buffer, $streamWrapper = null, $prefix = '') + protected function registerFilesystem($type, $key, $class, $filesystem, $buffer, $streamWrapper = null, $prefix = '') { - if(!class_exists('Gaufrette\\Filesystem')) - throw new InvalidArgumentException('You have to install Gaufrette in order to use it as a chunk storage service.'); + switch ($type) { + case 'gaufrette': + if (!class_exists('Gaufrette\\Filesystem')) { + throw new InvalidArgumentException('You have to install knplabs/knp-gaufrette-bundle in order to use it as a chunk storage service.'); + } + break; + case 'flysystem': + if (!class_exists('League\\Flysystem\\Filesystem')) { + throw new InvalidArgumentException('You have to install oneup/flysystem-bundle in order to use it as a chunk storage service.'); + } + break; + } - if(strlen($filesystem) <= 0) + if (strlen($filesystem) <= 0) throw new ServiceNotFoundException('Empty service name'); $streamWrapper = $this->normalizeStreamWrapper($streamWrapper); @@ -242,8 +274,7 @@ class OneupUploaderExtension extends Extension ->addArgument(new Reference($filesystem)) ->addArgument($this->getValueInBytes($buffer)) ->addArgument($streamWrapper) - ->addArgument($prefix) - ; + ->addArgument($prefix); } protected function getMaxUploadSize($input) diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index c970994..13d8f30 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -6,10 +6,12 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> <parameter key="oneup_uploader.chunks_storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage</parameter> + <parameter key="oneup_uploader.chunks_storage.flysystem.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage</parameter> <parameter key="oneup_uploader.chunks_storage.filesystem.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> + <parameter key="oneup_uploader.storage.flysystem.class">Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage</parameter> <parameter key="oneup_uploader.storage.filesystem.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemOrphanageStorage</parameter> <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php new file mode 100644 index 0000000..a277d7e --- /dev/null +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -0,0 +1,119 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; + +use League\Flysystem\File; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage as ChunkStorage; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; + +use League\Flysystem\Adapter\Local as Adapter; +use League\Flysystem\Filesystem as FSAdapter; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage as Storage; + +class FlysystemOrphanageStorageTest extends OrphanageTest +{ + protected $chunkDirectory; + protected $chunksKey = 'chunks'; + protected $orphanageKey = 'orphanage'; + + public function setUp() + { + $this->numberOfPayloads = 5; + $this->realDirectory = sys_get_temp_dir() . '/storage'; + $this->chunkDirectory = $this->realDirectory .'/' . $this->chunksKey; + $this->tempDirectory = $this->realDirectory . '/' . $this->orphanageKey; + $this->payloads = array(); + + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + + $filesystem = new Filesystem(); + $filesystem->mkdir($this->realDirectory); + $filesystem->mkdir($this->chunkDirectory); + $filesystem->mkdir($this->tempDirectory); + + $adapter = new Adapter($this->realDirectory, true); + $filesystem = new FSAdapter($adapter); + + $this->storage = new Storage($filesystem, 100000); + + $chunkStorage = new ChunkStorage($filesystem, 100000, null, 'chunks'); + + // create orphanage + $session = new Session(new MockArraySessionStorage()); + $session->start(); + + $config = array('directory' => 'orphanage'); + + $this->orphanage = new FlysystemOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat'); + + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + // create temporary file as if it was reassembled by the chunk manager + $file = tempnam($this->chunkDirectory, 'uploader'); + + $pointer = fopen($file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + //gaufrette needs the key relative to it's root + $fileKey = str_replace($this->realDirectory, '', $file); + + $this->payloads[] = new FlysystemFile(new File($filesystem, $fileKey), $filesystem); + } + } + + public function testUpload() + { + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + // exclude the orphanage and the chunks + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $this->assertCount(0, $finder); + } + + public function testUploadAndFetching() + { + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $this->assertCount(0, $finder); + + $files = $this->orphanage->uploadFiles(); + + $this->assertTrue(is_array($files)); + $this->assertCount($this->numberOfPayloads, $files); + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount(0, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + } + + public function checkIfTempnameMatchesAfterCreation() + { + return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + } +} diff --git a/Tests/Uploader/Storage/FlysystemStorageTest.php b/Tests/Uploader/Storage/FlysystemStorageTest.php new file mode 100644 index 0000000..bdd43e9 --- /dev/null +++ b/Tests/Uploader/Storage/FlysystemStorageTest.php @@ -0,0 +1,61 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; + +use League\Flysystem\Adapter\Local as Adapter; +use League\Flysystem\Filesystem as FSAdapter; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage as Storage; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FlysystemStorageTest extends \PHPUnit_Framework_TestCase +{ + protected $directory; + + /** + * @var Storage + */ + protected $storage; + protected $file; + + public function setUp() + { + $this->directory = sys_get_temp_dir() . '/storage'; + + // create temporary file + $this->file = tempnam(sys_get_temp_dir(), 'uploader'); + + $pointer = fopen($this->file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + $adapter = new Adapter($this->directory, true); + $filesystem = new FSAdapter($adapter); + + $this->storage = new Storage($filesystem, 100000); + } + + public function testUpload() + { + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); + $this->storage->upload($payload, 'notsogrumpyanymore.jpeg'); + + $finder = new Finder(); + $finder->in($this->directory)->files(); + + $this->assertCount(1, $finder); + + foreach ($finder as $file) { + $this->assertEquals($file->getFilename(), 'notsogrumpyanymore.jpeg'); + $this->assertEquals($file->getSize(), 1024); + } + } + + public function tearDown() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->directory); + } +} diff --git a/Tests/Uploader/Storage/OrphanageTest.php b/Tests/Uploader/Storage/OrphanageTest.php index 836ab86..ce3f6cd 100644 --- a/Tests/Uploader/Storage/OrphanageTest.php +++ b/Tests/Uploader/Storage/OrphanageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; @@ -9,6 +10,10 @@ abstract class OrphanageTest extends \PHPUnit_Framework_Testcase { protected $tempDirectory; protected $realDirectory; + + /** + * @var \Oneup\UploaderBundle\Uploader\Storage\OrphanageStorageInterface + */ protected $orphanage; protected $storage; protected $payloads; diff --git a/Uploader/Chunk/Storage/FlysystemStorage.php b/Uploader/Chunk/Storage/FlysystemStorage.php new file mode 100644 index 0000000..19e7a44 --- /dev/null +++ b/Uploader/Chunk/Storage/FlysystemStorage.php @@ -0,0 +1,152 @@ +<?php +namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; + +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use League\Flysystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FlysystemStorage implements ChunkStorageInterface +{ + + protected $unhandledChunk; + protected $prefix; + protected $streamWrapperPrefix; + + /** + * @var Filesystem + */ + private $filesystem; + + public $bufferSize; + + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) + { + if ( + ! method_exists($filesystem, 'readStream') + || + ! method_exists($filesystem, 'putStream') + ) { + throw new \InvalidArgumentException('The filesystem used as chunk storage must streamable'); + } + + $this->filesystem = $filesystem; + $this->bufferSize = $bufferSize; + $this->prefix = $prefix; + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + public function clear($maxAge, $prefix = null) + { + $prefix = $prefix ? :$this->prefix; + $matches = $this->filesystem->listFiles($prefix); + + $now = time(); + $toDelete = array(); + + // Collect the directories that are old, + // this also means the files inside are old + // but after the files are deleted the dirs + // would remain + foreach ($matches['dirs'] as $key) { + if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { + $toDelete[] = $key; + } + } + // The same directory is returned for every file it contains + array_unique($toDelete); + foreach ($matches['keys'] as $key) { + if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { + $this->filesystem->delete($key); + } + } + + foreach ($toDelete as $key) { + // The filesystem will throw exceptions if + // a directory is not empty + try { + $this->filesystem->delete($key); + } catch (\Exception $e) { + continue; + } + } + } + + public function addChunk($uuid, $index, UploadedFile $chunk, $original) + { + $this->unhandledChunk = array( + 'uuid' => $uuid, + 'index' => $index, + 'chunk' => $chunk, + 'original' => $original + ); + } + + public function assembleChunks($chunks, $removeChunk, $renameChunk) + { + // the index is only added to be in sync with the filesystem storage + $path = $this->prefix.'/'.$this->unhandledChunk['uuid'].'/'; + $filename = $this->unhandledChunk['index'].'_'.$this->unhandledChunk['original']; + + if (empty($chunks)) { + $target = $filename; + } else { + sort($chunks, SORT_STRING | SORT_FLAG_CASE); + $target = pathinfo($chunks[0], PATHINFO_BASENAME); + } + + + if ($this->unhandledChunk['index'] === 0) { + // if it's the first chunk overwrite the already existing part + // to avoid appending to earlier failed uploads + $handle = fopen($path . '/' . $target, 'w'); + } else { + $handle = fopen($path . '/' . $target, 'a'); + } + + $this->filesystem->putStream($path . $target, $handle); + if ($renameChunk) { + $name = preg_replace('/^(\d+)_/', '', $target); + /* The name can only match if the same user in the same session is + * trying to upload a file under the same name AND the previous upload failed, + * somewhere between this function, and the cleanup call. If that happened + * the previous file is unaccessible by the user, but if it is not removed + * it will block the user from trying to re-upload it. + */ + if ($this->filesystem->has($path.$name)) { + $this->filesystem->delete($path.$name); + } + + $this->filesystem->rename($path.$target, $path.$name); + $target = $name; + } + $uploaded = $this->filesystem->get($path.$target); + + if (!$renameChunk) { + return $uploaded; + } + + return new FlysystemFile($uploaded, $this->filesystem, $this->streamWrapperPrefix); + } + + public function cleanup($path) + { + $this->filesystem->delete($path); + } + + public function getChunks($uuid) + { + $results = $this->filesystem->listFiles($this->prefix.'/'.$uuid); + return preg_grep('/^.+\/(\d+)_/', $results['keys']); + } + + public function getFilesystem() + { + return $this->filesystem; + } + + public function getStreamWrapperPrefix() + { + return $this->streamWrapperPrefix; + } + +} diff --git a/Uploader/File/FlysystemFile.php b/Uploader/File/FlysystemFile.php new file mode 100644 index 0000000..dc36e69 --- /dev/null +++ b/Uploader/File/FlysystemFile.php @@ -0,0 +1,48 @@ +<?php +namespace Oneup\UploaderBundle\Uploader\File; + +use League\Flysystem\File; +use League\Flysystem\Filesystem; + +class FlysystemFile extends File implements FileInterface +{ + + protected $streamWrapperPrefix; + protected $mimeType; + + public function __construct(File $file, Filesystem $filesystem, $streamWrapperPrefix = null) + { + parent::__construct($filesystem, $file->getPath()); + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + /** + * Returns the path of the file + * + * @return string + */ + public function getPathname() + { + return $this->getPath(); + } + + /** + * Returns the basename of the file + * + * @return string + */ + public function getBasename() + { + return pathinfo($this->getPath(), PATHINFO_BASENAME); + } + + /** + * Returns the guessed extension of the file + * + * @return mixed + */ + public function getExtension() + { + return pathinfo($this->getPath(), PATHINFO_EXTENSION); + } +} diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php index 58868b8..7fcc83a 100644 --- a/Uploader/Gaufrette/StreamManager.php +++ b/Uploader/Gaufrette/StreamManager.php @@ -25,11 +25,9 @@ class StreamManager protected function ensureRemotePathExists($path) { - // this is a somehow ugly workaround introduced - // because the stream-mode is not able to create - // subdirectories. - if(!$this->filesystem->has($path)) + if(!$this->filesystem->has($path)) { $this->filesystem->write($path, '', true); + } } protected function openStream(Stream $stream, $mode) diff --git a/Uploader/Storage/FlysystemOrphanageStorage.php b/Uploader/Storage/FlysystemOrphanageStorage.php new file mode 100644 index 0000000..d9947c3 --- /dev/null +++ b/Uploader/Storage/FlysystemOrphanageStorage.php @@ -0,0 +1,93 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use League\Flysystem\File; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage as ChunkStorage; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageStorageInterface +{ + protected $storage; + protected $session; + protected $chunkStorage; + protected $config; + protected $type; + + /** + * @param StorageInterface $storage + * @param SessionInterface $session + * @param ChunkStorage $chunkStorage This class is only used if the gaufrette chunk storage is used. + * @param $config + * @param $type + */ + public function __construct(StorageInterface $storage, SessionInterface $session, ChunkStorage $chunkStorage, $config, $type) + { + /* + * initiate the storage on the chunk storage's filesystem + * the stream wrapper is useful for metadata. + */ + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, $chunkStorage->getStreamWrapperPrefix()); + + $this->storage = $storage; + $this->chunkStorage = $chunkStorage; + $this->session = $session; + $this->config = $config; + $this->type = $type; + } + + public function upload(FileInterface $file, $name, $path = null) + { + if(!$this->session->isStarted()) + throw new \RuntimeException('You need a running session in order to run the Orphanage.'); + + return parent::upload($file, $name, $this->getPath()); + } + + public function uploadFiles(array $files = null) + { + try { + if (null === $files) { + $files = $this->getFiles(); + } + $return = array(); + + foreach ($files as $key => $file) { + try { + $return[] = $this->storage->upload($file, str_replace($this->getPath(), '', $key)); + } catch (\Exception $e) { + // well, we tried. + continue; + } + } + + return $return; + } catch (\Exception $e) { + return array(); + } + } + + public function getFiles() + { + $keys = $this->chunkStorage->getFilesystem()->listFiles($this->getPath()); + $keys = $keys['keys']; + $files = array(); + + foreach ($keys as $key) { + // gotta pass the filesystem to both as you can't get it out from one.. + $files[$key] = new FlysystemFile(new File($this->chunkStorage->getFilesystem(), $key), $this->chunkStorage->getFilesystem()); + } + + return $files; + } + + protected function getPath() + { + // the storage is initiated in the root of the filesystem, from where the orphanage directory + // should be relative. + return sprintf('%s/%s/%s', $this->config['directory'], $this->session->getId(), $this->type); + } + +} diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php new file mode 100644 index 0000000..4d0212d --- /dev/null +++ b/Uploader/Storage/FlysystemStorage.php @@ -0,0 +1,59 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use League\Flysystem\Filesystem; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use Symfony\Component\Filesystem\Filesystem as LocalFilesystem; + +class FlysystemStorage implements StorageInterface +{ + + /** + * @var null|string + */ + protected $streamWrapperPrefix; + + /** + * @var float + */ + protected $bufferSize; + + /** + * @var Filesystem + */ + private $filesystem; + + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix = null) + { + $this->filesystem = $filesystem; + $this->bufferSize = $bufferSize; + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + public function upload(FileInterface $file, $name, $path = null) + { + $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); + + if ($file instanceof FlysystemFile) { + if ($file->getFilesystem() == $this->filesystem) { + $file->getFilesystem()->rename($file->getPath(), $path); + + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + } + } + + $this->filesystem->put($name, file_get_contents($file)); + + if ($file instanceof FlysystemFile) { + $file->delete(); + } else { + $filesystem = new LocalFilesystem(); + $filesystem->remove($file->getPathname()); + } + + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + } + +} diff --git a/composer.json b/composer.json index b2f32a3..69253bb 100644 --- a/composer.json +++ b/composer.json @@ -26,11 +26,13 @@ "symfony/security-bundle": "2.*|~3.0", "sensio/framework-extra-bundle": "2.*|~3.0", "symfony/browser-kit": "2.*|~3.0", - "phpunit/phpunit": "~4.4" + "phpunit/phpunit": "~4.4", + "oneup/flysystem-bundle": "^1.2" }, "suggest": { - "knplabs/knp-gaufrette-bundle": "0.1.*" + "knplabs/knp-gaufrette-bundle": "0.1.*", + "oneup/flysystem-bundle": "^1.2" }, "autoload": {
0
41df4540fe52c4b71f5280b5be1e8aa440c71cd7
1up-lab/OneupUploaderBundle
Testing ChunkManager (basic implementation).
commit 41df4540fe52c4b71f5280b5be1e8aa440c71cd7 Author: Jim Schmid <[email protected]> Date: Mon Mar 11 12:12:35 2013 +0100 Testing ChunkManager (basic implementation). diff --git a/Tests/Uploader/Chunk/ChunkManagerTest.php b/Tests/Uploader/Chunk/ChunkManagerTest.php new file mode 100644 index 0000000..85967a9 --- /dev/null +++ b/Tests/Uploader/Chunk/ChunkManagerTest.php @@ -0,0 +1,100 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk; + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; + +use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; + +class ChunkManagerTest extends \PHPUnit_Framework_TestCase +{ + protected $tmpDir; + + public function setUp() + { + // create a cache dir + $tmpDir = sprintf('/tmp/%s', uniqid()); + + $system = new Filesystem(); + $system->mkdir($tmpDir); + + $this->tmpDir = $tmpDir; + } + + public function tearDown() + { + $system = new Filesystem(); + $finder = new Finder(); + + // first remove every file in temporary directory + foreach($finder->in($this->tmpDir) as $file) + { + $system->remove($file); + } + + // and finally remove the directory itself + $system->remove($this->tmpDir); + } + + public function testExistanceOfTmpDir() + { + $this->assertTrue(is_dir($this->tmpDir)); + $this->assertTrue(is_writeable($this->tmpDir)); + } + + public function testFillOfTmpDir() + { + $finder = new Finder(); + $finder->in($this->tmpDir); + + $numberOfFiles = 10; + + $this->fillDirectory($numberOfFiles); + $this->assertCount($numberOfFiles, $finder); + } + + public function testChunkCleanup() + { + // get a manager configured with a max-age of 5 minutes + $maxage = 5 * 60; + $manager = $this->getManager($maxage); + $numberOfFiles = 10; + + $finder = new Finder(); + $finder->in($this->tmpDir); + + $this->fillDirectory($numberOfFiles); + $this->assertCount(10, $finder); + + $manager->clear(); + + $this->assertTrue(is_dir($this->tmpDir)); + $this->assertTrue(is_writeable($this->tmpDir)); + + $this->assertCount(5, $finder); + + foreach($finder as $file) + { + $this->assertGreaterThanOrEqual(time() - $maxage, filemtime($file)); + } + } + + protected function getManager($maxage) + { + return new ChunkManager(array( + 'directory' => $this->tmpDir, + 'maxage' => $maxage + )); + } + + protected function fillDirectory($number) + { + $system = new Filesystem(); + + for($i = 0; $i < $number; $i ++) + { + $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid()), time() - $i * 60); + } + } +} \ No newline at end of file diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 332ae47..1b184f5 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -1,11 +1,13 @@ <?php -namespace Oneup\UploaderBundle\Uploder\Chunk; +namespace Oneup\UploaderBundle\Uploader\Chunk; +use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -use Oneup\UploaderBundle\Uploader\ChunkManagerInterface; -class ChunkManager implements ChunkManagerInterafce +use Oneup\UploaderBundle\Uploader\Chunk\ChunkManagerInterface; + +class ChunkManager implements ChunkManagerInterface { public function __construct($configuration) { @@ -20,9 +22,14 @@ class ChunkManager implements ChunkManagerInterafce public function clear() { - $fileSystem = new FileSystem(); - $fileSystem->remove($this->configuration['directory']); + $system = new Filesystem(); + $finder = new Finder(); + + $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds'); - $this->warmup(); + foreach($finder as $file) + { + $system->remove($file); + } } } \ No newline at end of file
0
49c4704668ee8dd714696e6b144e2826586b7dff
1up-lab/OneupUploaderBundle
Removed existing Orphanage-implementation. It will be reimplemented as a storage layer.
commit 49c4704668ee8dd714696e6b144e2826586b7dff Author: Jim Schmid <[email protected]> Date: Wed Mar 27 19:04:06 2013 +0100 Removed existing Orphanage-implementation. It will be reimplemented as a storage layer. diff --git a/EventListener/OrphanageListener.php b/EventListener/OrphanageListener.php deleted file mode 100644 index f830b39..0000000 --- a/EventListener/OrphanageListener.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; - -use Oneup\UploaderBundle\Event\PostUploadEvent; -use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; - -class OrphanageListener implements EventSubscriberInterface -{ - protected $manager; - - public function __construct(OrphanageManagerInterface $manager) - { - $this->manager = $manager; - } - - public function add(PostUploadEvent $event) - { - $options = $event->getOptions(); - $request = $event->getRequest(); - $file = $event->getFile(); - $type = $event->getType(); - - if(!array_key_exists('use_orphanage', $options) || !$options['use_orphanage']) - return; - - $this->manager->get($type)->addFile($file, $options['file_name']); - } - - public static function getSubscribedEvents() - { - return array( - UploadEvents::POST_UPLOAD => 'add', - ); - } -} \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 66ba880..b74071a 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -5,13 +5,11 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> - <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> - <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Orphanage\Orphanage</parameter> <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> <parameter key="oneup_uploader.storage.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> - <parameter key="oneup_uploader.listener.orphanage.class">Oneup\UploaderBundle\EventListener\OrphanageListener</parameter> + <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\OrphanageStorage</parameter> </parameters> <services> @@ -19,12 +17,6 @@ <argument>%oneup_uploader.chunks%</argument> </service> - <!-- orphanage --> - <service id="oneup_uploader.orphanage_manager" class="%oneup_uploader.orphanage.manager.class%"> - <argument type="service" id="service_container" /> - <argument>%oneup_uploader.orphanage%</argument> - </service> - <!-- namer --> <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" /> @@ -33,13 +25,6 @@ <tag name="routing.loader" /> </service> - <!-- events --> - <service id="oneup_uploader.listener.orphanage" class="%oneup_uploader.listener.orphanage.class%"> - <argument type="service" id="oneup_uploader.orphanage_manager" /> - - <tag name="kernel.event_subscriber" /> - </service> - </services> </container> \ No newline at end of file diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php deleted file mode 100644 index 138d692..0000000 --- a/Uploader/Orphanage/Orphanage.php +++ /dev/null @@ -1,78 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Symfony\Component\Finder\Finder; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpFoundation\File\UploadedFile; -use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; - -class Orphanage implements OrphanageInterface -{ - protected $session; - protected $storage; - protected $namer; - protected $config; - protected $type; - - public function __construct(SessionInterface $session, StorageInterface $storage, $config, $type) - { - $this->session = $session; - $this->storage = $storage; - $this->config = $config; - $this->type = $type; - } - - public function addFile(File $file, $name) - { - if(!$this->session->isStarted()) - throw new \RuntimeException('You need a running session in order to run the Orphanage.'); - - // move file to orphanage - return $file->move($this->getPath(), $name); - } - - public function uploadFiles($keep = false) - { - $system = new Filesystem(); - $finder = new Finder(); - - if(!$system->exists($this->getPath())) - return array(); - - $finder->in($this->getPathRelativeToSession())->files(); - - $uploaded = array(); - - foreach($finder as $file) - { - $uploaded[] = $this->storage->upload(new UploadedFile($file->getPathname(), $file->getBasename(), null, null, null, true)); - - if(!$keep) - { - $system->remove($file); - } - } - - return $uploaded; - } - - protected function getPath() - { - $id = $this->session->getId(); - $path = sprintf('%s/%s/%s', $this->config['directory'], $id, $this->type); - - return $path; - } - - protected function getPathRelativeToSession() - { - $id = $this->session->getId(); - $path = sprintf('%s/%s', $this->config['directory'], $id); - - return $path; - } -} \ No newline at end of file diff --git a/Uploader/Orphanage/OrphanageInterface.php b/Uploader/Orphanage/OrphanageInterface.php deleted file mode 100644 index 00b584a..0000000 --- a/Uploader/Orphanage/OrphanageInterface.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Symfony\Component\HttpFoundation\File\File; - -interface OrphanageInterface -{ - public function addFile(File $file, $name); - public function uploadFiles($keep = false); -} diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php deleted file mode 100644 index 13d0d4b..0000000 --- a/Uploader/Orphanage/OrphanageManager.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Symfony\Component\Finder\Finder; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\DependencyInjection\ContainerInterface; - -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; - -class OrphanageManager implements OrphanageManagerInterface -{ - protected $container; - protected $configuration; - protected $orphanages; - - public function __construct(ContainerInterface $container, array $configuration) - { - $this->container = $container; - $this->configuration = $configuration; - $this->orphanages = array(); - } - - public function warmup() - { - $fileSystem = new FileSystem(); - $fileSystem->mkdir($this->configuration['directory']); - } - - public function clear() - { - $system = new Filesystem(); - $finder = new Finder(); - - try - { - $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds')->files(); - } - catch(\InvalidArgumentException $e) - { - // the finder will throw an exception of type InvalidArgumentException - // if the directory he should search in does not exist - // in that case we don't have anything to clean - return; - } - - foreach($finder as $file) - { - $system->remove($file); - } - } - - public function get($type) - { - return $this->getImplementation($type); - } - - public function getImplementation($type) - { - if(!array_key_exists($type, $this->orphanages)) - throw new \InvalidArgumentException(sprintf('No Orphanage implementation of type "%s" found.', $type)); - - return $this->orphanages[$type]; - } - - public function addImplementation($type, OrphanageInterface $orphanage) - { - $this->orphanages[$type] = $orphanage; - } -} \ No newline at end of file diff --git a/Uploader/Orphanage/OrphanageManagerInterface.php b/Uploader/Orphanage/OrphanageManagerInterface.php deleted file mode 100644 index 01bf0dc..0000000 --- a/Uploader/Orphanage/OrphanageManagerInterface.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; - -interface OrphanageManagerInterface -{ - public function warmup(); - public function clear(); - public function getImplementation($type); - public function addImplementation($type, OrphanageInterface $orphanage); -} \ No newline at end of file
0
ea2804ca78e8a139fcaf3f847997e9ff2a49b1a5
1up-lab/OneupUploaderBundle
Doc changes
commit ea2804ca78e8a139fcaf3f847997e9ff2a49b1a5 Author: David Greminger <[email protected]> Date: Mon Jan 4 12:03:05 2016 +0100 Doc changes diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 5850164..4178e9e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -5,7 +5,9 @@ The OneupUploaderBundle is a Symfony2 bundle developed and tested for versions 2 ## Prerequisites -This bundle is tested using Symfony 2.4+. +This bundle is tested using Symfony 2.4+. + +**With Symfony 2.3** If you want to use the bundle with Symfony 2.3, head over to the documentation for [1.3.x](https://github.com/1up-lab/OneupUploaderBundle/blob/release-1.3.x/Resources/doc/index.md). ### Translations
0
94ac72a032661423e21e967db178f5bd0d630386
1up-lab/OneupUploaderBundle
Added english translations of error messages.
commit 94ac72a032661423e21e967db178f5bd0d630386 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 23:46:19 2013 +0200 Added english translations of error messages. diff --git a/Resources/translations/OneupUploaderBundle.en.yml b/Resources/translations/OneupUploaderBundle.en.yml new file mode 100644 index 0000000..4d5f620 --- /dev/null +++ b/Resources/translations/OneupUploaderBundle.en.yml @@ -0,0 +1,4 @@ +error: + maxsize: This file is too large. + whitelist: This file type is not allowed. + blacklist: This file type is not allowed. \ No newline at end of file
0
3e763f0e6d65c6ce9a49d550dab0482562951dcf
1up-lab/OneupUploaderBundle
Removed a leading namespace separator.
commit 3e763f0e6d65c6ce9a49d550dab0482562951dcf Author: Jim Schmid <[email protected]> Date: Tue Apr 8 10:16:50 2014 +0200 Removed a leading namespace separator. diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php index 73fc147..446ae14 100644 --- a/Uploader/File/GaufretteFile.php +++ b/Uploader/File/GaufretteFile.php @@ -5,7 +5,7 @@ namespace Oneup\UploaderBundle\Uploader\File; use Gaufrette\Adapter\StreamFactory; use Gaufrette\File; use Gaufrette\Filesystem; -use \Gaufrette\Adapter\AwsS3; +use Gaufrette\Adapter\AwsS3; class GaufretteFile extends File implements FileInterface {
0
ecd34b328b15c2abca215a3f5d95e291ce69aa1f
1up-lab/OneupUploaderBundle
Fix doc
commit ecd34b328b15c2abca215a3f5d95e291ce69aa1f Author: David Greminger <[email protected]> Date: Sun Mar 29 12:15:59 2020 +0200 Fix doc diff --git a/doc/custom_namer.md b/doc/custom_namer.md index 5e95a77..d790dec 100644 --- a/doc/custom_namer.md +++ b/doc/custom_namer.md @@ -116,7 +116,8 @@ class CatNamer implements NamerInterface */ public function name(FileInterface $file) { - $userId = $this->tokenStorage->getToken()->getUser()->getId(); + // Prevent path traversal attacks + $userId = basename($this->tokenStorage->getToken()->getUser()->getId()); return sprintf('%s/%s.%s', $userId,
0
dc7c5f6361c073d428b569e8b14cb29e638607e4
1up-lab/OneupUploaderBundle
Update errorhandler.xml Added plupload
commit dc7c5f6361c073d428b569e8b14cb29e638607e4 Author: MJBGO <[email protected]> Date: Sun Nov 16 00:03:21 2014 +0100 Update errorhandler.xml Added plupload diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index e684668..f0eb112 100644 --- a/Resources/config/errorhandler.xml +++ b/Resources/config/errorhandler.xml @@ -6,6 +6,7 @@ <parameters> <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter> <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter> + <parameter key="oneup_uploader.error_handler.plupload.class">Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler</parameter> </parameters> <services> @@ -16,7 +17,7 @@ <service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> - <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.plupload.class%" public="false" /> <service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" /> </services>
0