commit_id
string
repo
string
commit_message
string
diff
string
label
int64
7920b4393d57e76038fbdb0e7152552ac52fd715
1up-lab/OneupUploaderBundle
Merge pull request #242 from diegotham/patch-1 Fix unnamed directory when uploading to Amazon S3
commit 7920b4393d57e76038fbdb0e7152552ac52fd715 (from 95740749e0550dc63f7b4f28b2e0129ef5fc33be) Merge: 9574074 52303cf Author: David Greminger <[email protected]> Date: Fri Jul 15 13:50:32 2016 +0200 Merge pull request #242 from diegotham/patch-1 Fix unnamed directory when uploading to Amazon S3 diff --git a/Uploader/Storage/FilesystemOrphanageStorage.php b/Uploader/Storage/FilesystemOrphanageStorage.php index ed6e4f6..8888e16 100644 --- a/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -48,7 +48,7 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageS $return = array(); foreach ($files as $file) { - $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), str_replace($this->getFindPath(), '', $file)); + $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), ltrim(str_replace($this->getFindPath(), '', $file), "/")); } return $return; commit 7920b4393d57e76038fbdb0e7152552ac52fd715 (from 52303cf5d4387b7f320ffb6fd46a0687a51d98ee) Merge: 9574074 52303cf Author: David Greminger <[email protected]> Date: Fri Jul 15 13:50:32 2016 +0200 Merge pull request #242 from diegotham/patch-1 Fix unnamed directory when uploading to Amazon S3 diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 276ddf3..75d64b4 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -90,6 +90,7 @@ class Configuration implements ConfigurationInterface ->booleanNode('enable_progress')->defaultFalse()->end() ->booleanNode('enable_cancelation')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() + ->booleanNode('root_folder')->defaultFalse()->end() ->end() ->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 4a471c5..5ffbe09 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -200,8 +200,11 @@ class OneupUploaderExtension extends Extension switch ($config['type']) { case 'filesystem': + // root_folder is true, remove the mapping name folder from path + $folder = $this->config['mappings'][$key]['root_folder'] ? '' : $key; + $config['directory'] = is_null($config['directory']) ? - sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : + sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $folder) : $this->normalizePath($config['directory']) ; diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index c577309..2aa007b 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -82,6 +82,6 @@ See the [Use Chunked Uploads behind Load Balancers](load_balancers.md) section i The ChunkManager can be forced to clean up old and orphanaged chunks by using the command provided by the OneupUploaderBundle. - $> php app/console oneup:uploader:clean-chunks + $> php app/console oneup:uploader:clear-chunks This parameter will clean all chunk files older than the `maxage` value in your configuration. diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 6b0d248..a7cee8a 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -38,6 +38,7 @@ oneup_uploader: allowed_mimetypes: [] disallowed_mimetypes: [] error_handler: oneup_uploader.error_handler.noop + root_folder: false # Set max_size to -1 for gracefully downgrade this number to the systems max upload size. max_size: 9223372036854775807 diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index 256d2c6..fea6ee0 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -50,3 +50,64 @@ oneup_uploader: ``` Every file uploaded through the `Controller` of this mapping will be named with your custom namer. + +## Change the directory structure + +With the `NameInterface` you can change the directory structure to provide a better files organization or to use your own existing structure. For example, you need to separate the uploaded files by users with a `user_id` folder. + +You need to inject the `security.token_storage` service to your namer. + +```xml +<services> + <service id="acme_demo.custom_namer" class="Acme\DemoBundle\CatNamer"> + <argument type="service" id="security.token_storage"/> + </service> +</services> +``` + +```yml +services: + acme_demo.custom_namer: + class: Acme\DemoBundle\CatNamer + arguments: ["@security.token_storage"] +``` + +Now you can use the service to get the logged user id and return the custom directory like below: + +```php +<?php + +namespace Acme\DemoBundle; + +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; + +class CatNamer implements NamerInterface +{ + private $tokenStorage; + + public function __construct(TokenStorage $tokenStorage){ + $this->tokenStorage = $tokenStorage; + } + + /** + * Creates a user directory name for the file being uploaded. + * + * @param FileInterface $file + * @return string The directory name. + */ + public function name(FileInterface $file) + { + $userId = $this->tokenStorage->getToken()->getUser()->getId(); + + return sprintf('%s/%s.%s', + $userId, + uniqid(), + $file->getExtension() + ); + } +} +``` + +Every file uploaded through the `Controller` of this mapping will be named with your new directory structure. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 39ab715..7b6601e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -25,7 +25,7 @@ framework: Perform the following steps to install and use the basic functionality of the OneupUploaderBundle: -* Download OnueupUploaderBundle using Composer +* Download OneupUploaderBundle using Composer * Enable the bundle * Configure the bundle * Prepare your frontend @@ -78,9 +78,31 @@ oneup_uploader: type: uploader ``` -The default directory that is used to upload files to is `web/uploads/{mapping_name}`. +The default directory that is used to upload files to is `web/uploads/{mapping_name}`. In case you want to avoid a separated mapping folder, you can set `root_folder: true` and the default directory will be `web/uploads`. + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + root_folder: true +``` > 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: + storage: + directory: "%kernel.root_dir%/../data/uploads/" +``` ### Step 4: Prepare your frontend diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 9352b4e..9442712 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -32,7 +32,7 @@ class OrphanageManager // 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 = $this->container->get('oneup_uploader.chunks_storage'); $chunkStorage->clear($this->config['maxage'], $this->config['directory']); return;
0
beaadefeb00acf0230f3f96cdbc02c6c21f7220e
1up-lab/OneupUploaderBundle
Added chunk configuration.
commit beaadefeb00acf0230f3f96cdbc02c6c21f7220e Author: Jim Schmid <[email protected]> Date: Mon Mar 11 10:08:24 2013 +0100 Added chunk configuration. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 2c20ba1..902be76 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -11,6 +11,17 @@ class Configuration implements ConfigurationInterface { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('oneup_uploader'); + + $rootNode + ->children() + ->arrayNode('chunks') + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('directory')->end() + ->scalarNode('maxage')->defaultValue(604800)->end() + ->end() + ->end() + ; return $treeBuilder; } diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 3a77172..29cd7e9 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -16,5 +16,13 @@ class OneupUploaderExtension extends Extension $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); + + // handling chunk configuration + if(!array_key_exists('directory', $config['chunks'])) + { + $config['chunks']['directory'] = sprintf('%s/chunks', $container->getParameter('kernel.cache_dir')); + } + + $container->setParameter('oneup_uploader.chunks', $config['chunks']); } } \ No newline at end of file
0
87908265bc2dec00c8e2337ad27b944453ebc16f
1up-lab/OneupUploaderBundle
Merge branch 'lsv-error-handling-doc' into release-1.4.0
commit 87908265bc2dec00c8e2337ad27b944453ebc16f (from 210707fefc9f9fe9d14e5aefe361ad7e6c346ef7) Merge: 210707f 790a534 Author: David Greminger <[email protected]> Date: Mon Jan 4 10:09:56 2016 +0100 Merge branch 'lsv-error-handling-doc' into release-1.4.0 diff --git a/Resources/doc/custom_error_handler.md b/Resources/doc/custom_error_handler.md index 69bedfa..8c1e248 100644 --- a/Resources/doc/custom_error_handler.md +++ b/Resources/doc/custom_error_handler.md @@ -48,4 +48,9 @@ oneup_uploader: error_handler: acme_demo.custom_error_handler ``` -**Note**: As of [9dbd905](https://github.com/1up-lab/OneupUploaderBundle/commit/9dbd9056dfe403ce6f1273d2d75fe814d517731a) only the `BlueimpErrorHandler` is implemented. If you know how to implement the error handlers for the other supported frontends, please create a pull request or drop me a note. +**Note**: + +* As of [9dbd905](https://github.com/1up-lab/OneupUploaderBundle/commit/9dbd9056dfe403ce6f1273d2d75fe814d517731a) `BlueimpErrorHandler` is implemented. +* As of [f420fff](https://github.com/1up-lab/OneupUploaderBundle/commit/f420fff5bc3ec910e925ceae15bc513b419693f2) `DropZoneErrorHandler` is implemented. + +If you know how to implement the error handlers for the other supported frontends, please create a pull request or drop me a note. diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index b91091e..ccb915e 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -99,3 +99,21 @@ If you are using chunked uploads and hook into the `oneup_uploader.post_chunk_up * `getType`: Get the name of the mapping of the current upload. Useful if you have multiple mappings and EventListeners. * `getConfig`: Get the config of the mapping. * `isLast`: Returns `true` if this is the last chunk to be uploaded, `false` otherwise. + +## Returning a error +You can return a upload error by throwing a ```Symfony\Component\HttpFoundation\File\Exception\UploadException``` exception + +But remember in the PostPersistEvent the file is already uploaded, so its up to you to remove the file before throwing the exception. + +You should use the [validation event](custom_validator.md) if possible, so the file does not touch your system. + +```php + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; + +public function onUpload(PostPersistEvent $event) +{ + // Remember to remove the already uploaded file + throw new UploadException('Nope, I dont do files'); +} +```
0
893d73a76c83e72888b67617b34451e47f69ce02
1up-lab/OneupUploaderBundle
Merge pull request #39 from maurotdo/patch-1 Update custom_error_handler.md
commit 893d73a76c83e72888b67617b34451e47f69ce02 (from 1819ca7236b823cd03fe55b383313b1aef5f37b8) Merge: 1819ca7 4a72ed5 Author: Jim Schmid <[email protected]> Date: Thu Aug 8 02:32:45 2013 -0700 Merge pull request #39 from maurotdo/patch-1 Update custom_error_handler.md diff --git a/Resources/doc/custom_error_handler.md b/Resources/doc/custom_error_handler.md index baf4507..b6cd21c 100644 --- a/Resources/doc/custom_error_handler.md +++ b/Resources/doc/custom_error_handler.md @@ -18,7 +18,7 @@ class CustomErrorHandler implements ErrorHandlerInterface { public function addException(ResponseInterface $response, UploadException $exception) { - $message = $exception->getErrorMessage(); + $message = $exception->getMessage(); $response['error'] = $message; } } @@ -42,4 +42,4 @@ oneup_uploader: error_handler: acme_demo.custom_error_handler ``` -**Note**: As of [9dbd905](https://github.com/1up-lab/OneupUploaderBundle/commit/9dbd9056dfe403ce6f1273d2d75fe814d517731a) only the `BlueimpErrorHandler` is implemented. If you know how to implement the error handlers for the other supported frontends, please create a pull request or drop me a note. \ No newline at end of file +**Note**: As of [9dbd905](https://github.com/1up-lab/OneupUploaderBundle/commit/9dbd9056dfe403ce6f1273d2d75fe814d517731a) only the `BlueimpErrorHandler` is implemented. If you know how to implement the error handlers for the other supported frontends, please create a pull request or drop me a note.
0
5ba9a444a57063aeeb02f528039ac4384d702775
1up-lab/OneupUploaderBundle
Fix travis builds.
commit 5ba9a444a57063aeeb02f528039ac4384d702775 Author: Jim Schmid <[email protected]> Date: Mon May 6 22:30:01 2013 +0200 Fix travis builds. diff --git a/.travis.yml b/.travis.yml index d231b7e..40d1a2d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ php: env: - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* - - SYMFONY_VERSION=dev-master before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source
0
160c9a163d34b03c5413cee193743bc0407471f1
1up-lab/OneupUploaderBundle
Update custom_namer.md
commit 160c9a163d34b03c5413cee193743bc0407471f1 Author: mitom <[email protected]> Date: Fri Oct 11 10:50:13 2013 +0200 Update custom_namer.md 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`
0
44d5bc62821b07b121712c901e78750e7af5ce32
1up-lab/OneupUploaderBundle
Tested MooUploadResponse class.
commit 44d5bc62821b07b121712c901e78750e7af5ce32 Author: Jim Schmid <[email protected]> Date: Thu Apr 18 20:24:11 2013 +0200 Tested MooUploadResponse class. diff --git a/Tests/Uploader/Response/MooUploadResponseTest.php b/Tests/Uploader/Response/MooUploadResponseTest.php new file mode 100644 index 0000000..ba28199 --- /dev/null +++ b/Tests/Uploader/Response/MooUploadResponseTest.php @@ -0,0 +1,92 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\MooUploadResponse; + +class MooUploadResponseTest extends \PHPUnit_Framework_TestCase +{ + public function testCreationOfResponse() + { + $response = new MooUploadResponse(); + + $this->assertTrue($response->getFinish()); + $this->assertEquals(0, $response->getError()); + } + + public function testFunctionsOfResponse() + { + $response = new MooUploadResponse(); + $response->setId(3); + $response->setName('grumpy_cat.jpg'); + $response->setSize(15093); + $response->setError(-1); + $response->setFinish(true); + $response->setUploadedName('b1/2d/b12d23.jpg'); + + $this->assertEquals(3, $response->getId()); + $this->assertEquals('grumpy_cat.jpg', $response->getName()); + $this->assertEquals(15093, $response->getSize()); + $this->assertEquals(-1, $response->getError()); + $this->assertEquals(true, $response->getFinish()); + $this->assertEquals('b1/2d/b12d23.jpg', $response->getUploadedName()); + } + + public function testFunctionsAfterOverwrite() + { + $response = new MooUploadResponse(); + $response->setId(3); + $response->setName('grumpy_cat.jpg'); + $response->setSize(15093); + $response->setError(-1); + $response->setFinish(true); + $response->setUploadedName('b1/2d/b12d23.jpg'); + + $response['id'] = null; + $response['name'] = null; + $response['size'] = null; + $response['error'] = null; + $response['finish'] = null; + $response['uploadedName'] = null; + $response['princess'] = !null; + + $this->assertEquals(3, $response->getId()); + $this->assertEquals('grumpy_cat.jpg', $response->getName()); + $this->assertEquals(15093, $response->getSize()); + $this->assertEquals(-1, $response->getError()); + $this->assertEquals(true, $response->getFinish()); + $this->assertEquals('b1/2d/b12d23.jpg', $response->getUploadedName()); + $this->assertEquals(!null, $response['princess']); + } + + public function testAssemble() + { + + $response = new MooUploadResponse(); + $response->setId(3); + $response->setName('grumpy_cat.jpg'); + $response->setSize(15093); + $response->setError(-1); + $response->setFinish(true); + $response->setUploadedName('b1/2d/b12d23.jpg'); + + $response['id'] = null; + $response['name'] = null; + $response['size'] = null; + $response['error'] = null; + $response['finish'] = null; + $response['uploadedName'] = null; + $response['upload_name'] = null; + $response['princess'] = !null; + + $data = $response->assemble(); + + $this->assertEquals(3, $data['id']); + $this->assertEquals('grumpy_cat.jpg', $data['name']); + $this->assertEquals(15093, $data['size']); + $this->assertEquals(-1, $data['error']); + $this->assertEquals(true, $data['finish']); + $this->assertEquals('b1/2d/b12d23.jpg', $data['upload_name']); + $this->assertEquals(!null, $data['princess']); + } +}
0
9ad3cb176d2fbfc2cf77c3814252bc8f78d076f9
1up-lab/OneupUploaderBundle
Added basic FineUploaderTest.
commit 9ad3cb176d2fbfc2cf77c3814252bc8f78d076f9 Author: Jim Schmid <[email protected]> Date: Mon May 6 22:16:48 2013 +0200 Added basic FineUploaderTest. diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 564f071..c399626 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -28,6 +28,12 @@ monolog: oneup_uploader: mappings: + + fineuploader: + frontend: fineuploader + storage: + directory: %kernel.root_dir%/cache/%kernel.environment%/upload + blueimp: frontend: blueimp storage: diff --git a/Tests/Controller/FineUploaderTest.php b/Tests/Controller/FineUploaderTest.php new file mode 100644 index 0000000..7c6ec11 --- /dev/null +++ b/Tests/Controller/FineUploaderTest.php @@ -0,0 +1,29 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; + +class FineUploaderTest extends AbstractControllerTest +{ + protected function getConfigKey() + { + return 'fineuploader'; + } + + protected function getRequestParameters() + { + return array(); + } + + protected function getRequestFile() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txt', + 'text/plain', + 128 + ); + } +}
0
f795b14669b1cb3e7855b7326aee646f1aae7570
1up-lab/OneupUploaderBundle
moved the metadatasupporter check
commit f795b14669b1cb3e7855b7326aee646f1aae7570 Author: mitom <[email protected]> Date: Thu Oct 10 12:32:55 2013 +0200 moved the metadatasupporter check diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 35d46b7..c69e3b2 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -21,6 +21,10 @@ class GaufretteStorage extends StreamManager implements StorageInterface { $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); + if ($this->filesystem->getAdapter() instanceof MetadataSupporter) { + $this->filesystem->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); + } + if ($file instanceof GaufretteFile) { if ($file->getFilesystem() == $this->filesystem) { $file->getFilesystem()->rename($file->getKey(), $path); @@ -29,9 +33,6 @@ class GaufretteStorage extends StreamManager implements StorageInterface } } - if ($this->filesystem->getAdapter() instanceof MetadataSupporter) { - $this->filesystem->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); - } $this->ensureRemotePathExists($path.$name); $dst = $this->filesystem->createStream($path);
0
a2b58acd47ee19bed944e45cb4488e338c97b3fe
1up-lab/OneupUploaderBundle
Added warning to readme. ping #21
commit a2b58acd47ee19bed944e45cb4488e338c97b3fe Author: Jim Schmid <[email protected]> Date: Thu Jul 25 17:28:23 2013 +0200 Added warning to readme. ping #21 diff --git a/README.md b/README.md index 17de8d8..cfdfbdb 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,16 @@ +*** + +**Warning**: There is currently a pretty serious issue reported. Until further notice, +consider chunked uploads as *not-working*. It is highly recommended to switch from chunked +uploads to non-chunked uploads until this issue is fixed again. You can find more +information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21). + +*** + + 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). * [FineUploader](http://fineuploader.com/)
0
91b5eccf9d9d1461be052092434dedfdd40d28f5
1up-lab/OneupUploaderBundle
Merge branch 'xml-to-yml' of https://github.com/lsv/OneupUploaderBundle into lsv-xml-to-yml
commit 91b5eccf9d9d1461be052092434dedfdd40d28f5 (from c0c044660aef7a57f6b63885ac367786bc9251e8) Merge: c0c0446 d02c6d1 Author: David Greminger <[email protected]> Date: Mon Jan 4 10:08:15 2016 +0100 Merge branch 'xml-to-yml' of https://github.com/lsv/OneupUploaderBundle into lsv-xml-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..c83002d 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -34,6 +34,12 @@ Next, register your created namer as a service in your `services.xml` </services> ``` +```yml +services: + acme_demo.custom_namer: + class: Acme\DemoBundle\CatNamer +``` + Now you can use your custom service by adding it to your configuration: ```yml 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 } +``` commit 91b5eccf9d9d1461be052092434dedfdd40d28f5 (from d02c6d19f0ad13d58c604589134612ad3ddc3b96) Merge: c0c0446 d02c6d1 Author: David Greminger <[email protected]> Date: Mon Jan 4 10:08:15 2016 +0100 Merge branch 'xml-to-yml' of https://github.com/lsv/OneupUploaderBundle into lsv-xml-to-yml diff --git a/.travis.yml b/.travis.yml index 5a3affa..26b3eb4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,24 +5,43 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 - hhvm env: - SYMFONY_VERSION=2.3.* + - SYMFONY_VERSION=2.7.* + - SYMFONY_VERSION=2.8.* + +cache: + directories: + - $COMPOSER_CACHE_DIR matrix: allow_failures: - - env: SYMFONY_VERSION=dev-master - php: hhvm + - env: SYMFONY_VERSION=dev-master + include: - - php: 5.5 + - php: 5.6 + env: SYMFONY_VERSION=2.3.* + - php: 5.6 env: SYMFONY_VERSION=2.4.* - - php: 5.5 + - php: 5.6 env: SYMFONY_VERSION=2.5.* - - php: 5.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 - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source - composer install --dev --prefer-source diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 62f9df1..691a44f 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -7,7 +7,6 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\UploadEvents; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; -use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Event\PostChunkUploadEvent; abstract class AbstractChunkedController extends AbstractController @@ -45,7 +44,6 @@ abstract class AbstractChunkedController extends AbstractController protected function handleChunkedUpload(UploadedFile $file, ResponseInterface $response, Request $request) { // get basic container stuff - $request = $this->container->get('request'); $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); // get information about this chunked request diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index a551ba8..01ae713 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -17,6 +17,7 @@ use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Symfony\Component\HttpKernel\Kernel; abstract class AbstractController { @@ -38,7 +39,7 @@ abstract class AbstractController public function progress() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $session = $this->container->get('session'); $prefix = ini_get('session.upload_progress.prefix'); @@ -54,7 +55,7 @@ abstract class AbstractController public function cancel() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $session = $this->container->get('session'); $prefix = ini_get('session.upload_progress.prefix'); @@ -73,8 +74,8 @@ abstract class AbstractController /** * Flattens a given filebag to extract all files. * - * @param bag The filebag to use - * @return array An array of files + * @param FileBag $bag The filebag to use + * @return array An array of files */ protected function getFiles(FileBag $bag) { @@ -100,9 +101,9 @@ abstract class AbstractController * * Note: The return value differs when * - * @param The file to upload - * @param response A response object. - * @param request The request object. + * @param mixed $file The file to upload + * @param ResponseInterface $response A response object. + * @param Request $request The request object. */ protected function handleUpload($file, ResponseInterface $response, Request $request) { @@ -129,9 +130,9 @@ abstract class AbstractController /** * This function is a helper function which dispatches pre upload event * - * @param uploaded The uploaded file. - * @param response A response object. - * @param request The request object. + * @param FileInterface $uploaded The uploaded file. + * @param ResponseInterface $response A response object. + * @param Request $request The request object. */ protected function dispatchPreUploadEvent(FileInterface $uploaded, ResponseInterface $response, Request $request) { @@ -147,9 +148,9 @@ abstract class AbstractController * This function is a helper function which dispatches post upload * and post persist events. * - * @param uploaded The uploaded file. - * @param response A response object. - * @param request The request object. + * @param mixed $uploaded The uploaded file. + * @param ResponseInterface $response A response object. + * @param Request $request The request object. */ protected function dispatchPostEvents($uploaded, ResponseInterface $response, Request $request) { @@ -171,7 +172,7 @@ abstract class AbstractController protected function validate(FileInterface $file) { $dispatcher = $this->container->get('event_dispatcher'); - $event = new ValidationEvent($file, $this->container->get('request'), $this->config, $this->type); + $event = new ValidationEvent($file, $this->getRequest(), $this->config, $this->type); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); } @@ -183,13 +184,14 @@ abstract class AbstractController * then the content type of the response will be set to text/plain instead. * * @param mixed $data + * @param int $statusCode * * @return JsonResponse */ - protected function createSupportedJsonResponse($data) + protected function createSupportedJsonResponse($data, $statusCode = 200) { - $request = $this->container->get('request'); - $response = new JsonResponse($data); + $request = $this->getRequest(); + $response = new JsonResponse($data, $statusCode); $response->headers->set('Vary', 'Accept'); if (!in_array('application/json', $request->getAcceptableContentTypes())) { @@ -198,4 +200,20 @@ abstract class AbstractController return $response; } + + /** + * Get the master request + * + * @return Request + */ + protected function getRequest() + { + + if (version_compare(Kernel::VERSION, '2.4', '<=')) { + return $this->container->get('request'); + } + + return $this->container->get('request_stack')->getMasterRequest(); + } + } diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index f9186c7..f12329e 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -5,14 +5,13 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\Controller\AbstractChunkedController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class BlueimpController extends AbstractChunkedController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new EmptyResponse(); $files = $this->getFiles($request->files); @@ -34,7 +33,7 @@ class BlueimpController extends AbstractChunkedController public function progress() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $session = $this->container->get('session'); $prefix = ini_get('session.upload_progress.prefix'); diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 2121f32..b4fdc99 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -4,21 +4,21 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class DropzoneController extends AbstractController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new EmptyResponse(); $files = $this->getFiles($request->files); - + $statusCode = 200; foreach ($files as $file) { try { $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); $translator = $this->container->get('translator'); $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); @@ -28,6 +28,6 @@ class DropzoneController extends AbstractController } } - return $this->createSupportedJsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble(), $statusCode); } } diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index bc21006..2aae793 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -4,14 +4,13 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class FancyUploadController extends AbstractController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new EmptyResponse(); $files = $this->getFiles($request->files); diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index 246b7f6..79cab8c 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -5,14 +5,13 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\Controller\AbstractChunkedController; use Oneup\UploaderBundle\Uploader\Response\FineUploaderResponse; class FineUploaderController extends AbstractChunkedController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $translator = $this->container->get('translator'); $response = new FineUploaderResponse(); diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index e4f055b..95babd4 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -6,7 +6,6 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\Controller\AbstractChunkedController; use Oneup\UploaderBundle\Uploader\Response\MooUploadResponse; class MooUploadController extends AbstractChunkedController @@ -15,7 +14,7 @@ class MooUploadController extends AbstractChunkedController public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new MooUploadResponse(); $headers = $request->headers; diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index 56cb151..ee0ceb4 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -5,14 +5,13 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\Controller\AbstractChunkedController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class PluploadController extends AbstractChunkedController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new EmptyResponse(); $files = $this->getFiles($request->files); diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index ea68396..b93c725 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -4,14 +4,13 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class UploadifyController extends AbstractController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new EmptyResponse(); $files = $this->getFiles($request->files); diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index c79e72b..043cacc 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -4,14 +4,13 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Oneup\UploaderBundle\Controller\AbstractController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class YUI3Controller extends AbstractController { public function upload() { - $request = $this->container->get('request'); + $request = $this->getRequest(); $response = new EmptyResponse(); $files = $this->getFiles($request->files); diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index e684668..bf580bf 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.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter> </parameters> <services> @@ -17,7 +18,7 @@ <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.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.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" /> </services> diff --git a/Resources/doc/custom_uploader.md b/Resources/doc/custom_uploader.md index 20de413..c4fd761 100644 --- a/Resources/doc/custom_uploader.md +++ b/Resources/doc/custom_uploader.md @@ -40,7 +40,7 @@ class CustomUploader extends UploaderController public function upload() { // get some basic stuff together - $request = $this->container->get('request'); + $request = $this->container->get('request_stack')->getMasterRequest(); $response = new EmptyResponse(); // get file from request (your own logic) diff --git a/Uploader/ErrorHandler/DropzoneErrorHandler.php b/Uploader/ErrorHandler/DropzoneErrorHandler.php new file mode 100755 index 0000000..5b0ad44 --- /dev/null +++ b/Uploader/ErrorHandler/DropzoneErrorHandler.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 DropzoneErrorHandler implements ErrorHandlerInterface +{ + public function addException(AbstractResponse $response, Exception $exception) + { + $errors[] = $exception; + $message = $exception->getMessage(); + // Dropzone wants JSON with error message put into 'error' field. + // This overwrites the previous error message, so we're only displaying the last one. + $response['error'] = $message; + } +} diff --git a/composer.json b/composer.json index aa66e5d..3d9a755 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,8 @@ ], "require": { - "symfony/framework-bundle": ">=2.2", + "symfony/framework-bundle": "^2.3.0", + "symfony/http-kernel": "^2.3.0", "symfony/finder": ">=2.2.0" },
0
9dbd9056dfe403ce6f1273d2d75fe814d517731a
1up-lab/OneupUploaderBundle
Distribute the load of assembling chunks to every upload request. This is a configurable option, as it could be the case that chunks will be uploaded asynchronous and therefore not in the correct order. Fixes #24.
commit 9dbd9056dfe403ce6f1273d2d75fe814d517731a Author: Jim Schmid <[email protected]> Date: Mon Jul 15 01:24:35 2013 +0200 Distribute the load of assembling chunks to every upload request. This is a configurable option, as it could be the case that chunks will be uploaded asynchronous and therefore not in the correct order. Fixes #24. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 4d797d1..f053703 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -57,16 +57,20 @@ abstract class AbstractChunkedController extends AbstractController $chunk = $chunkManager->addChunk($uuid, $index, $file, $orig); $this->dispatchChunkEvents($chunk, $response, $request, $last); + + if ($chunkManager->getLoadDistribution()) { + $chunks = $chunkManager->getChunks($uuid); + $assembled = $chunkManager->assembleChunks($chunks); + } // if all chunks collected and stored, proceed // with reassembling the parts if ($last) { - // we'll take the first chunk and append the others to it - // this way we don't need another file in temporary space for assembling - $chunks = $chunkManager->getChunks($uuid); - - // assemble parts - $assembled = $chunkManager->assembleChunks($chunks); + if (!$chunkManager->getLoadDistribution()) { + $chunks = $chunkManager->getChunks($uuid); + $assembled = $chunkManager->assembleChunks($chunks); + } + $path = $assembled->getPath(); // create a temporary uploaded file to meet the interface restrictions diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 9b4c457..02085e0 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -19,6 +19,7 @@ class Configuration implements ConfigurationInterface ->children() ->scalarNode('maxage')->defaultValue(604800)->end() ->scalarNode('directory')->defaultNull()->end() + ->booleanNode('load_distribution')->defaultTrue()->end() ->end() ->end() ->arrayNode('orphanage') diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 5bfa4b5..310cd0b 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -48,7 +48,7 @@ class ChunkManager implements ChunkManagerInterface return $chunk->move($path, $name); } - public function assembleChunks(\IteratorAggregate $chunks) + public function assembleChunks(\IteratorAggregate $chunks, $removeChunk = true) { $iterator = $chunks->getIterator()->getInnerIterator(); @@ -63,6 +63,11 @@ class ChunkManager implements ChunkManagerInterface throw new \RuntimeException('Reassembling chunks failed.'); } + if ($removeChunk) { + $filesystem = new Filesystem(); + $filesystem->remove($file->getPathname()); + } + $iterator->next(); } @@ -97,4 +102,9 @@ class ChunkManager implements ChunkManagerInterface return $finder; } + + public function getLoadDistribution() + { + return $this->configuration['load_distribution']; + } }
0
1fd15f74248a7f11481be3bb1c66315d68e7a1be
1up-lab/OneupUploaderBundle
Add Errorhandling to Dropzone
commit 1fd15f74248a7f11481be3bb1c66315d68e7a1be Author: Gladhon <[email protected]> Date: Fri Feb 20 17:23:38 2015 +0100 Add Errorhandling to Dropzone diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 0c8a5b0..2121f32 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -20,6 +20,11 @@ class DropzoneController extends AbstractController $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); + $translator = $this->container->get('translator'); + $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); + $response = $this->createSupportedJsonResponse(array('error'=>$message )); + $response->setStatusCode(400); + return $response; } }
0
955f07222e4af4c18fc3664fe0bf41104b2e104a
1up-lab/OneupUploaderBundle
Renamed some tests so PHPUnit get the connections.
commit 955f07222e4af4c18fc3664fe0bf41104b2e104a Author: Jim Schmid <[email protected]> Date: Sat Apr 6 21:57:53 2013 +0200 Renamed some tests so PHPUnit get the connections. diff --git a/Tests/Controller/ControllerChunkedUploadTest.php b/Tests/Controller/UploaderControllerChunkedTest.php similarity index 98% rename from Tests/Controller/ControllerChunkedUploadTest.php rename to Tests/Controller/UploaderControllerChunkedTest.php index 3c57240..1291823 100644 --- a/Tests/Controller/ControllerChunkedUploadTest.php +++ b/Tests/Controller/UploaderControllerChunkedTest.php @@ -11,7 +11,7 @@ use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; use Oneup\UploaderBundle\Controller\UploaderController; -class ControllerChunkedUploadTest extends \PHPUnit_Framework_TestCase +class UploaderControllerChunkedTest extends \PHPUnit_Framework_TestCase { protected $tempChunks; protected $currentChunk; diff --git a/Tests/Controller/ControllerUploadTest.php b/Tests/Controller/UploaderControllerTest.php similarity index 79% rename from Tests/Controller/ControllerUploadTest.php rename to Tests/Controller/UploaderControllerTest.php index 7bd7fc8..967ca51 100644 --- a/Tests/Controller/ControllerUploadTest.php +++ b/Tests/Controller/UploaderControllerTest.php @@ -10,7 +10,7 @@ use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; use Oneup\UploaderBundle\Controller\UploaderController; -class ControllerUploadTest extends \PHPUnit_Framework_TestCase +class UploaderControllerTest extends \PHPUnit_Framework_TestCase { protected $tempFile; @@ -53,6 +53,29 @@ class ControllerUploadTest extends \PHPUnit_Framework_TestCase $this->assertCount(1, $finder); } + public function testUploadWhichFails() + { + $container = $this->getContainerMock(); + $storage = new FilesystemStorage(sys_get_temp_dir() . '/uploader'); + $config = array( + 'use_orphanage' => false, + 'namer' => 'namer', + 'max_size' => 1, + 'allowed_extensions' => array(), + 'disallowed_extensions' => array() + ); + + $controller = new UploaderController($container, $storage, $config, 'cat'); + $response = $controller->upload(); + + $json = json_decode($response->getContent()); + + // testing response + $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertFalse($json->success); + } + protected function getContainerMock() { $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); diff --git a/Tests/Controller/ControllerValidationTest.php b/Tests/Controller/UploaderControllerValidationTest.php similarity index 98% rename from Tests/Controller/ControllerValidationTest.php rename to Tests/Controller/UploaderControllerValidationTest.php index fd4c2d0..2e06720 100644 --- a/Tests/Controller/ControllerValidationTest.php +++ b/Tests/Controller/UploaderControllerValidationTest.php @@ -4,7 +4,7 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Oneup\UploaderBundle\Controller\UploaderController; -class ControllerValidationTest extends \PHPUnit_Framework_TestCase +class UploaderControllerValidationTest extends \PHPUnit_Framework_TestCase { /** * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException
0
4ad7f0965d7e75408670cda668a9e008b3ff67cb
1up-lab/OneupUploaderBundle
Renamed Orphanage to OrphanageManager as we need specific, session-based Orphanaged later.
commit 4ad7f0965d7e75408670cda668a9e008b3ff67cb Author: Jim Schmid <[email protected]> Date: Tue Mar 12 11:49:23 2013 +0100 Renamed Orphanage to OrphanageManager as we need specific, session-based Orphanaged later. diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 7b85efe..24a24b2 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -5,7 +5,7 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> - <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Orphanage\Orphanage</parameter> + <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> </parameters> @@ -15,7 +15,7 @@ <argument>%oneup_uploader.chunks%</argument> </service> - <service id="oneup_uploader.orphanage" class="%oneup_uploader.orphanage.class%"> + <service id="oneup_uploader.orphanage.manager" class="%oneup_uploader.orphanage.manager.class%"> <argument>%oneup_uploader.orphanage%</argument> </service> diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/OrphanageManager.php similarity index 89% rename from Uploader/Orphanage/Orphanage.php rename to Uploader/Orphanage/OrphanageManager.php index 7239042..9657d7a 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -5,9 +5,9 @@ namespace Oneup\UploaderBundle\Uploader\Orphanage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; +use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; -class Orphanage implements OrphanageInterface +class OrphanageManager implements OrphanageManagerInterface { public function __construct($configuration) { diff --git a/Uploader/Orphanage/OrphanageInterface.php b/Uploader/Orphanage/OrphanageManagerInterface.php similarity index 77% rename from Uploader/Orphanage/OrphanageInterface.php rename to Uploader/Orphanage/OrphanageManagerInterface.php index 6d66c0f..52c3807 100644 --- a/Uploader/Orphanage/OrphanageInterface.php +++ b/Uploader/Orphanage/OrphanageManagerInterface.php @@ -2,7 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Orphanage; -interface OrphanageInterface +interface OrphanageManagerInterface { public function warmup(); public function clear();
0
f4ee50f60e1e19cbd1ad8671e33afbf46e88df6e
1up-lab/OneupUploaderBundle
Added the possibility to whitelist file extensions per mapping.
commit f4ee50f60e1e19cbd1ad8671e33afbf46e88df6e Author: Jim Schmid <[email protected]> Date: Thu Mar 14 16:36:25 2013 +0100 Added the possibility to whitelist file extensions per mapping. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 722172d..3efe927 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -2,6 +2,7 @@ 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\Finder\Finder; @@ -34,11 +35,15 @@ class UploaderController implements UploadControllerInterface foreach($files as $file) { - // some error handling - if($file->getClientSize() > $this->config['max_size']) - return new JsonResponse(array('error' => 'File is too large')); - - $ret = $totalParts > 1 ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + try + { + $ret = $totalParts > 1 ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + } + catch(UploadException $e) + { + // an error happended, return this error message. + return new JsonResponse(array('error' => $e->getMessage())); + } } return $ret; @@ -46,6 +51,17 @@ class UploaderController implements UploadControllerInterface protected function handleUpload(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('File is too large.'); + + $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_types']) > 0 && !in_array($extension, $this->config['allowed_types'])) + throw new UploadException('This extension is not allowed.'); + $name = $this->namer->name($file, $this->config['directory_prefix']); $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index fc02a08..d5a0663 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,6 +35,9 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->scalarNode('storage')->isRequired()->end() + ->arrayNode('allowed_types') + ->prototype('scalar')->end() + ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->scalarNode('directory_prefix')->defaultNull()->end() ->booleanNode('use_orphanage')->defaultFalse()->end()
0
6188e0c231c4c7435f5a54e017b9ac95b53791fc
1up-lab/OneupUploaderBundle
Added newline in ValidationListener.
commit 6188e0c231c4c7435f5a54e017b9ac95b53791fc Author: Jim Schmid <[email protected]> Date: Mon Apr 22 19:57:44 2013 +0200 Added newline in ValidationListener. diff --git a/EventListener/DisallowedExtensionValidationListener.php b/EventListener/DisallowedExtensionValidationListener.php index 26a5f3a..14319a3 100644 --- a/EventListener/DisallowedExtensionValidationListener.php +++ b/EventListener/DisallowedExtensionValidationListener.php @@ -18,4 +18,4 @@ class DisallowedExtensionValidationListener throw new ValidationException('error.blacklist'); } } -} \ No newline at end of file +}
0
8423b63c04eb95f1165859a2decffc7d4b97a098
1up-lab/OneupUploaderBundle
Merge branch 'Lctrs-feature/file-extension-validation' into release/2.0.0
commit 8423b63c04eb95f1165859a2decffc7d4b97a098 (from 03231b8e00cee33658243ec2071a1576280e86f5) Merge: 03231b8 ce217c6 Author: David Greminger <[email protected]> Date: Fri Dec 1 16:45:58 2017 +0100 Merge branch 'Lctrs-feature/file-extension-validation' into release/2.0.0 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 ); }
0
b73b62a50de1906ea949eba7626dad74412e4f18
1up-lab/OneupUploaderBundle
Added to possibility to blacklist file extensions per mapping.
commit b73b62a50de1906ea949eba7626dad74412e4f18 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 16:38:46 2013 +0100 Added to possibility to blacklist file extensions per mapping. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 3efe927..a7566f4 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -62,6 +62,11 @@ class UploaderController implements UploadControllerInterface if(count($this->config['allowed_types']) > 0 && !in_array($extension, $this->config['allowed_types'])) throw new UploadException('This extension is not allowed.'); + // check if the current extension is mentioned in the disallowed types + // and if so, throw an exception + if(count($this->config['disallowed_types']) > 0 && in_array($extension, $this->config['disallowed_types'])) + throw new UploadException('This extension is not allowed.'); + $name = $this->namer->name($file, $this->config['directory_prefix']); $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index d5a0663..658f48f 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -38,6 +38,9 @@ class Configuration implements ConfigurationInterface ->arrayNode('allowed_types') ->prototype('scalar')->end() ->end() + ->arrayNode('disallowed_types') + ->prototype('scalar')->end() + ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->scalarNode('directory_prefix')->defaultNull()->end() ->booleanNode('use_orphanage')->defaultFalse()->end()
0
e1b1b618cfbbdb48f80547e44f9889e362374997
1up-lab/OneupUploaderBundle
Thank you
commit e1b1b618cfbbdb48f80547e44f9889e362374997 Author: David Greminger <[email protected]> Date: Fri Dec 1 17:02:35 2017 +0100 Thank you diff --git a/README.md b/README.md index c76f765..2a54218 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! Symfony 2.x support was dropped. You can also configure now a file extension validation whitelist (PR [#289](https://github.com/1up-lab/OneupUploaderBundle/pull/289)) +* 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 **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
b07a20a65872176f6f639012f2736b04334d8e19
1up-lab/OneupUploaderBundle
Tested OrphanageManager.
commit b07a20a65872176f6f639012f2736b04334d8e19 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 20:06:10 2013 +0200 Tested OrphanageManager. diff --git a/Tests/Uploader/Orphanage/OrphanageManagerTest.php b/Tests/Uploader/Orphanage/OrphanageManagerTest.php new file mode 100644 index 0000000..2c331b8 --- /dev/null +++ b/Tests/Uploader/Orphanage/OrphanageManagerTest.php @@ -0,0 +1,99 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Orphanage; + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; +use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager; + +class OrphanageManagerTest extends \PHPUnit_Framework_TestCase +{ + protected $numberOfOrphans; + protected $orphanagePath; + protected $mockContainer; + protected $mockConfig; + + public function setUp() + { + $this->numberOfOrphans = 10; + $this->orphanagePath = sys_get_temp_dir() . '/orphanage'; + + $filesystem = new Filesystem(); + $filesystem->mkdir($this->orphanagePath); + + // create n orphans with a filemtime in the past + for($i = 0; $i < $this->numberOfOrphans; $i ++) + { + touch($this->orphanagePath . '/' . uniqid(), time() - 1000); + } + + $this->mockConfig = array( + 'maxage' => 100, + 'directory' => $this->orphanagePath + ); + + $this->mockContainer = $this->getContainerMock(); + } + + public function testGetSpecificService() + { + $manager = new OrphanageManager($this->mockContainer, $this->mockConfig); + $service = $manager->get('grumpycat'); + + $this->assertTrue($service); + } + + public function testClearAllInPast() + { + // create n orphans with a filemtime in the past + for($i = 0; $i < $this->numberOfOrphans; $i ++) + { + touch($this->orphanagePath . '/' . uniqid(), time() - 1000); + } + + $manager = new OrphanageManager($this->mockContainer, $this->mockConfig); + $manager->clear(); + + $finder = new Finder(); + $finder->in($this->orphanagePath)->files(); + + $this->assertCount(0, $finder); + } + + public function testClearSomeInPast() + { + // create n orphans with half filetimes in the past and half in the future + // relative to the given threshold + for($i = 0; $i < $this->numberOfOrphans; $i ++) + { + touch($this->orphanagePath . '/' . uniqid(), time() - $i * 20); + } + + $manager = new OrphanageManager($this->mockContainer, $this->mockConfig); + $manager->clear(); + + $finder = new Finder(); + $finder->in($this->orphanagePath)->files(); + + $this->assertCount($this->numberOfOrphans / 2, $finder); + } + + protected function getContainerMock() + { + $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); + $mock + ->expects($this->any()) + ->method('get') + ->with('oneup_uploader.orphanage.grumpycat') + ->will($this->returnValue(true)) + ; + + return $mock; + } + + public function tearDown() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->orphanagePath); + } +} \ No newline at end of file
0
b0aa221c634c7c8179ee1e55457a0ee191ac4acb
1up-lab/OneupUploaderBundle
Made mapping.frontend configuration key mandatory. This is required anyways. But without the isRequired() directive, a user will end up in a E_NOTICE about the index frontend on the config array is not set. This fixes #65.
commit b0aa221c634c7c8179ee1e55457a0ee191ac4acb Author: Jim Schmid <[email protected]> Date: Tue Oct 29 10:21:54 2013 +0100 Made mapping.frontend configuration key mandatory. This is required anyways. But without the isRequired() directive, a user will end up in a E_NOTICE about the index frontend on the config array is not set. This fixes #65. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index a9efae7..34df9d3 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -51,6 +51,7 @@ class Configuration implements ConfigurationInterface ->children() ->enumNode('frontend') ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload', 'dropzone', 'custom')) + ->isRequired() ->end() ->arrayNode('custom_frontend') ->addDefaultsIfNotSet()
0
e6f99c59d9b613fd35e0c1cb9cfc663dc53705c3
1up-lab/OneupUploaderBundle
Introduced getFiles function on AbstractController This method will flatten a given file bag and extract all UploadedFile instances. Addresses: #28 & #29.
commit e6f99c59d9b613fd35e0c1cb9cfc663dc53705c3 Author: Jim Schmid <[email protected]> Date: Thu Jul 18 10:31:22 2013 +0200 Introduced getFiles function on AbstractController This method will flatten a given file bag and extract all UploadedFile instances. Addresses: #28 & #29. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 865517d..9f6c7f0 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -6,6 +6,7 @@ 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; use Oneup\UploaderBundle\UploadEvents; use Oneup\UploaderBundle\Event\PreUploadEvent; @@ -68,6 +69,29 @@ abstract class AbstractController return new JsonResponse(true); } + /** + * Flattens a given filebag to extract all files. + * + * @param bag The filebag to use + * @return array An array of files + */ + protected function getFiles(FileBag $bag) + { + $files = array(); + $fileBag = $bag->all(); + $fileIterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($fileBag), \RecursiveIteratorIterator::SELF_FIRST); + + foreach ($fileIterator as $file) { + if (is_array($file)) { + continue; + } + + $files[] = $file; + } + + return $files; + } + /** * This internal function handles the actual upload process * and will most likely be called from the upload() diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index c0842a8..3e1578b 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -15,7 +15,7 @@ class BlueimpController extends AbstractChunkedController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files->get('files'); + $files = $this->getFiles($request->files); $chunked = !is_null($request->headers->get('content-range')); diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index 00858f6..8901b2e 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -14,7 +14,7 @@ class FancyUploadController extends AbstractController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files; + $files = $this->getFiles($request->files); foreach ($files as $file) { try { diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index a9dc1b1..e279e8b 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -18,7 +18,7 @@ class FineUploaderController extends AbstractChunkedController $response = new FineUploaderResponse(); $totalParts = $request->get('qqtotalparts', 1); - $files = $request->files; + $files = $this->getFiles($request->files); $chunked = $totalParts > 1; foreach ($files as $file) { diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index d2b6a8a..9f06c18 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -15,7 +15,7 @@ class PluploadController extends AbstractChunkedController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files; + $files = $this->getFiles($request->files); $chunked = !is_null($request->get('chunks')); diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index de75cdd..a98f7e8 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -14,7 +14,7 @@ class UploadifyController extends AbstractController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files; + $files = $this->getFiles($request->files); foreach ($files as $file) { try { diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index ac4760c..8638ad6 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -14,7 +14,7 @@ class YUI3Controller extends AbstractController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files; + $files = $this->getFiles($request->files); foreach ($files as $file) { try {
0
34f516144d4ff74855f8ad7c5d03691557224f44
1up-lab/OneupUploaderBundle
Set orphanage Storage Service public (see #311)
commit 34f516144d4ff74855f8ad7c5d03691557224f44 Author: Erwan Nader <[email protected]> Date: Mon Jan 8 17:04:05 2018 +0100 Set orphanage Storage Service public (see #311) diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index af8af94..d909662 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -245,6 +245,7 @@ class OneupUploaderExtension extends Extension ->addArgument(new Reference('oneup_uploader.chunks_storage')) ->addArgument($this->config['orphanage']) ->addArgument($key) + ->setPublic(true) ; // switch storage of mapping to orphanage
0
ce5f1f555380460a00c1da2276cb0662a6be05cc
1up-lab/OneupUploaderBundle
CS fixes for Controller
commit ce5f1f555380460a00c1da2276cb0662a6be05cc Author: Jim Schmid <[email protected]> Date: Thu Jun 20 21:24:23 2013 +0200 CS fixes for Controller diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index b167aa6..4d797d1 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -29,7 +29,7 @@ abstract class AbstractChunkedController extends AbstractController * @return array */ abstract protected function parseChunkedRequest(Request $request); - + /** * This function will be called in order to upload and save an * uploaded chunk. @@ -47,35 +47,35 @@ abstract class AbstractChunkedController extends AbstractController // get basic container stuff $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 all chunks collected and stored, proceed // with reassembling the parts if ($last) { // we'll take the first chunk and append the others to it // this way we don't need another file in temporary space for assembling $chunks = $chunkManager->getChunks($uuid); - + // assemble parts $assembled = $chunkManager->assembleChunks($chunks); $path = $assembled->getPath(); - + // 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); } } @@ -91,10 +91,10 @@ abstract class AbstractChunkedController extends AbstractController protected function dispatchChunkEvents($uploaded, ResponseInterface $response, Request $request, $isLast) { $dispatcher = $this->container->get('event_dispatcher'); - + // dispatch post upload event (both the specific and the general) $postUploadEvent = new PostChunkUploadEvent($uploaded, $response, $request, $isLast, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_CHUNK_UPLOAD, $postUploadEvent); $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_CHUNK_UPLOAD, $this->type), $postUploadEvent); } -} \ No newline at end of file +} diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index b5c91a1..1f6b0dd 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -5,7 +5,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Oneup\UploaderBundle\UploadEvents; @@ -13,7 +12,6 @@ use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Oneup\UploaderBundle\Uploader\Exception\ValidationException; @@ -23,7 +21,7 @@ abstract class AbstractController protected $storage; protected $config; protected $type; - + public function __construct(ContainerInterface $container, StorageInterface $storage, array $config, $type) { $this->container = $container; @@ -31,7 +29,7 @@ abstract class AbstractController $this->config = $config; $this->type = $type; } - + abstract public function upload(); /** @@ -50,17 +48,17 @@ abstract class AbstractController protected function handleUpload(UploadedFile $file, ResponseInterface $response, Request $request) { $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); - + $this->dispatchEvents($uploaded, $response, $request); } - + /** * This function is a helper function which dispatches post upload * and post persist events. @@ -72,13 +70,13 @@ abstract class AbstractController protected function dispatchEvents($uploaded, ResponseInterface $response, Request $request) { $dispatcher = $this->container->get('event_dispatcher'); - + // dispatch post upload event (both the specific and the general) $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_UPLOAD, $this->type), $postUploadEvent); - - if (!$this->config['use_orphanage']) { + + if (!$this->config['use_orphanage']) { // dispatch post persist event (both the specific and the general) $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); @@ -90,10 +88,10 @@ abstract class AbstractController { $dispatcher = $this->container->get('event_dispatcher'); $event = new ValidationEvent($file, $this->config, $this->type); - + try { $dispatcher->dispatch(UploadEvents::VALIDATION, $event); - } catch(ValidationException $exception) { + } catch (ValidationException $exception) { // pass the exception one level up throw new UploadException($exception->getMessage()); } diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index e62ed31..41736a2 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -16,36 +16,35 @@ class BlueimpController extends AbstractChunkedController $request = $this->container->get('request'); $response = new EmptyResponse(); $files = $request->files; - + $chunked = !is_null($request->headers->get('content-range')); - - foreach($files as $file) - { + + foreach ($files as $file) { $file = $file[0]; - + try { $chunked ? $this->handleChunkedUpload($file, $response, $request) : $this->handleUpload($file, $response, $request) ; - } catch(UploadException $e) { + } catch (UploadException $e) { // return nothing return new JsonResponse(array()); } } - + return new JsonResponse($response->assemble()); } - + protected function parseChunkedRequest(Request $request) { $session = $this->container->get('session'); $headerRange = $request->headers->get('content-range'); $attachmentName = rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $request->headers->get('content-disposition'))); - + // split the header string to the appropriate parts list($tmp, $startByte, $endByte, $totalBytes) = preg_split('/[^0-9]+/', $headerRange); - + // getting information about chunks // note: We don't have a chance to get the last $total // correct. This is due to the fact that the $size variable @@ -57,13 +56,13 @@ class BlueimpController extends AbstractChunkedController $last = ($endByte + 1) == $totalBytes; $index = $last ? \PHP_INT_MAX : floor($startByte / $size); $total = ceil($totalBytes / $size); - + // it is possible, that two clients send a file with the // exact same filename, therefore we have to add the session // to the uuid otherwise we will get a mess $uuid = md5(sprintf('%s.%s', $attachmentName, $session->getId())); $orig = $attachmentName; - + return array($last, $uuid, $index, $orig); } -} \ No newline at end of file +} diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index b9244fe..c26f040 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -15,20 +15,16 @@ class FancyUploadController extends AbstractController $request = $this->container->get('request'); $response = new EmptyResponse(); $files = $request->files; - - foreach($files as $file) - { - try - { + + foreach ($files as $file) { + try { $uploaded = $this->handleUpload($file, $response, $request); - } - catch(UploadException $e) - { + } catch (UploadException $e) { // return nothing return new JsonResponse(array()); } } - + return new JsonResponse($response->assemble()); } -} \ No newline at end of file +} diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index c295234..2fcfe00 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -15,34 +15,30 @@ class FineUploaderController extends AbstractChunkedController { $request = $this->container->get('request'); $translator = $this->container->get('translator'); - + $response = new FineUploaderResponse(); $totalParts = $request->get('qqtotalparts', 1); $files = $request->files; $chunked = $totalParts > 1; - - foreach($files as $file) - { - try - { + + foreach ($files as $file) { + try { $chunked ? $this->handleChunkedUpload($file, $response, $request) : $this->handleUpload($file, $response, $request) ; - } - catch(UploadException $e) - { + } catch (UploadException $e) { $response->setSuccess(false); $response->setError($translator->trans($e->getMessage(), array(), 'OneupUploaderBundle')); - + // an error happended, return this error message. return new JsonResponse($response->assemble()); } } - + return new JsonResponse($response->assemble()); } - + protected function parseChunkedRequest(Request $request) { $index = $request->get('qqpartindex'); @@ -50,7 +46,7 @@ class FineUploaderController extends AbstractChunkedController $uuid = $request->get('qquuid'); $orig = $request->get('qqfilename'); $last = ($total - 1) == $index; - + return array($last, $uuid, $index, $orig); } -} \ No newline at end of file +} diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index 1b2ec9b..dbc75f6 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -13,29 +13,28 @@ use Oneup\UploaderBundle\Uploader\Response\MooUploadResponse; class MooUploadController extends AbstractChunkedController { protected $response; - + public function upload() { $request = $this->container->get('request'); $dispatcher = $this->container->get('event_dispatcher'); $translator = $this->container->get('translator'); - + $response = new MooUploadResponse(); $headers = $request->headers; - + list($file, $uploadFileName) = $this->getUploadedFile($request); - + // we have to get access to this object in another method $this->response = $response; - + // check if uploaded by chunks $chunked = $headers->get('content-length') < $headers->get('x-file-size'); - - try - { + + try { // fill response object $response = $this->response; - + $response->setId($headers->get('x-file-id')); $response->setSize($headers->get('content-length')); $response->setName($headers->get('x-file-name')); @@ -45,86 +44,79 @@ class MooUploadController extends AbstractChunkedController $this->handleChunkedUpload($file, $response, $request) : $this->handleUpload($file, $response, $request) ; - } - catch(UploadException $e) - { + } catch (UploadException $e) { $response = $this->response; - + $response->setFinish(true); $response->setError(-1); - + // return nothing return new JsonResponse($response->assemble()); } - + return new JsonResponse($response->assemble()); } - + protected function parseChunkedRequest(Request $request) { $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); $headers = $request->headers; $parameters = array_keys($request->query->all()); - + $uuid = $headers->get('x-file-id'); $index = $this->createIndex($parameters[0]); $orig = $headers->get('x-file-name'); $size = 0; - - try - { + + try { // loop through every file that has been uploaded before - foreach($chunkManager->getChunks($uuid) as $file) - { + foreach ($chunkManager->getChunks($uuid) as $file) { $size += $file->getSize(); } - } - catch(\InvalidArgumentException $e) - { + } catch (\InvalidArgumentException $e) { // do nothing: this exception will be thrown // if the directory does not yet exist. this // means we don't have a chunk and the actual // size is 0 } - + $last = $headers->get('x-file-size') == ($size + $headers->get('content-length')); - + // store also to response object $this->response->setFinish($last); - + return array($last, $uuid, $index, $orig); } - + protected function createIndex($id) { $ints = 0; - + // loop through every char and convert it to an integer // we need this for sorting - foreach(str_split($id) as $char) - { + foreach (str_split($id) as $char) { $ints += ord($char); } - + return $ints; } - + protected function getUploadedFile(Request $request) { $headers = $request->headers; - + // create temporary file in systems temp dir $tempFile = tempnam(sys_get_temp_dir(), 'uploader'); $contents = file_get_contents('php://input'); - + // put data from php://input to temp file file_put_contents($tempFile, $contents); - + $uploadFileName = sprintf('%s_%s', $headers->get('x-file-id'), $headers->get('x-file-name')); - + // create an uploaded file to upload $file = new UploadedFile($tempFile, $uploadFileName, null, null, null, true); - + return array($file, $uploadFileName); } -} \ No newline at end of file +} diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index 60501e9..162f6a8 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -16,41 +16,37 @@ class PluploadController extends AbstractChunkedController $request = $this->container->get('request'); $response = new EmptyResponse(); $files = $request->files; - + $chunked = !is_null($request->get('chunks')); - - foreach($files as $file) - { - try - { + + foreach ($files as $file) { + try { $chunked ? $this->handleChunkedUpload($file, $response, $request) : $this->handleUpload($file, $response, $request) ; - } - catch(UploadException $e) - { + } catch (UploadException $e) { // return nothing return new JsonResponse(array()); } } - + return new JsonResponse($response->assemble()); } - + protected function parseChunkedRequest(Request $request) { $session = $this->container->get('session'); - + $orig = $request->get('name'); $index = $request->get('chunk'); $last = $request->get('chunks') - 1 == $request->get('chunk'); - + // it is possible, that two clients send a file with the // exact same filename, therefore we have to add the session // to the uuid otherwise we will get a mess $uuid = md5(sprintf('%s.%s', $orig, $session->getId())); - + return array($last, $uuid, $index, $orig); } -} \ No newline at end of file +} diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index cc42c74..fe57183 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -15,20 +15,16 @@ class UploadifyController extends AbstractController $request = $this->container->get('request'); $response = new EmptyResponse(); $files = $request->files; - - foreach($files as $file) - { - try - { + + foreach ($files as $file) { + try { $uploaded = $this->handleUpload($file, $response, $request); - } - catch(UploadException $e) - { + } 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 index d5c87de..5b1e98f 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -15,20 +15,16 @@ class YUI3Controller extends AbstractController $request = $this->container->get('request'); $response = new EmptyResponse(); $files = $request->files; - - foreach($files as $file) - { - try - { + + foreach ($files as $file) { + try { $uploaded = $this->handleUpload($file, $response, $request); - } - catch(UploadException $e) - { + } catch (UploadException $e) { // return nothing return new JsonResponse(array()); } } - + return new JsonResponse($response->assemble()); } -} \ No newline at end of file +}
0
49ecb4eda3e32d8ea3fc24a338e4b5c35f860eb3
1up-lab/OneupUploaderBundle
Implemented chunked upload on PluploadController
commit 49ecb4eda3e32d8ea3fc24a338e4b5c35f860eb3 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 15:49:17 2013 +0200 Implemented chunked upload on PluploadController diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index ede7a8d..6b0cfe3 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -17,11 +17,13 @@ class PluploadController extends AbstractChunkedController $response = new EmptyResponse(); $files = $request->files; + $chunked = !is_null($request->get('chunks')); + foreach($files as $file) { try { - $uploaded = $this->handleUpload($file); + $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); // dispatch POST_PERSIST AND POST_UPLOAD events $this->dispatchEvents($uploaded, $response, $request); @@ -38,6 +40,11 @@ class PluploadController extends AbstractChunkedController protected function parseChunkedRequest(Request $request) { - die("foobar"); + $orig = $request->get('name'); + $uuid = $request->get('name'); + $index = $request->get('chunk'); + $last = $request->get('chunks') - 1 == $request->get('chunk'); + + return array($last, $uuid, $index, $orig); } } \ No newline at end of file
0
9e6489e378c1c653b64e513f72fab95579d746eb
1up-lab/OneupUploaderBundle
Merge pull request #55 from erik-am/fix-blueimp-IE9 Let blueimp return a text/plain response to old browsers
commit 9e6489e378c1c653b64e513f72fab95579d746eb (from c0138f647c8aee974ac085708a543dec20d52c29) Merge: c0138f6 f9fb64b Author: Jim Schmid <[email protected]> Date: Wed Oct 2 06:13:33 2013 -0700 Merge pull request #55 from erik-am/fix-blueimp-IE9 Let blueimp return a text/plain response to old browsers diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 3e1578b..f10f776 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -30,7 +30,7 @@ class BlueimpController extends AbstractChunkedController } } - return new JsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble()); } public function progress() @@ -51,7 +51,7 @@ class BlueimpController extends AbstractChunkedController 'total' => $value['content_length'] ); - return new JsonResponse($progress); + return $this->createSupportedJsonResponse($progress); } protected function parseChunkedRequest(Request $request) @@ -83,4 +83,26 @@ 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/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index 351f173..8909345 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -63,7 +63,7 @@ abstract class AbstractControllerTest extends WebTestCase $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint); + $client->request('POST', $endpoint, array(), array(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index 44e07bd..c06c8d1 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()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -30,6 +30,20 @@ class BlueimpTest extends AbstractUploadTest } } + public function testResponseForOldBrowsers() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'text/plain; charset=UTF-8'); + $this->assertCount(1, $this->getUploadedFiles()); + + } + public function testEvents() { $client = $this->client; diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index dc90c38..4bbfa1c 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -15,7 +15,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful()); @@ -29,7 +29,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -67,7 +67,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectExtension()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectExtension(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful()); @@ -81,7 +81,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); @@ -103,7 +103,7 @@ class BlueimpValidationTest extends AbstractValidationTest $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType()); + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType(), array('HTTP_ACCEPT' => 'application/json')); $response = $client->getResponse(); //$this->assertTrue($response->isNotSuccessful());
0
499cd9e4d3c86cd0db30a46b69628552fdd954ba
1up-lab/OneupUploaderBundle
Allow EventDispatcher component to have version >=2.0.16,<2.3-dev
commit 499cd9e4d3c86cd0db30a46b69628552fdd954ba Author: Jim Schmid <[email protected]> Date: Thu Mar 14 16:57:35 2013 +0100 Allow EventDispatcher component to have version >=2.0.16,<2.3-dev diff --git a/composer.json b/composer.json index 6d97b50..f9fa6d5 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "require": { "symfony/finder": ">=2.0.16,<2.3-dev", "symfony/filesystem": ">=2.0.16,<2.3-dev", - "symfony/event-dispatcher": "2.2.*", + "symfony/event-dispatcher": ">=2.0.16,<2.3-dev", "knplabs/knp-gaufrette-bundle": "0.1.*", "valums/file-uploader": "3.3.*" },
0
b679a47b0125e19ee8519fde3ba193d86bf789c2
1up-lab/OneupUploaderBundle
Added basic ControllerTest (Blueimp)
commit b679a47b0125e19ee8519fde3ba193d86bf789c2 Author: Jim Schmid <[email protected]> Date: Mon May 6 21:58:34 2013 +0200 Added basic ControllerTest (Blueimp) diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php new file mode 100644 index 0000000..be2176d --- /dev/null +++ b/Tests/Controller/AbstractControllerTest.php @@ -0,0 +1,103 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; + +abstract class AbstractControllerTest extends WebTestCase +{ + protected $client; + protected $container; + protected $createdFiles; + + public function setUp() + { + $this->client = static::createClient(); + $this->container = $this->client->getContainer(); + $this->helper = $this->container->get('oneup_uploader.templating.uploader_helper'); + $this->createdFiles = array(); + + $routes = $this->container->get('router')->getRouteCollection()->all(); + } + + abstract protected function getConfigKey(); + abstract protected function getSingleRequestParameters(); + abstract protected function getSingleRequestFile(); + + public function testSingleUpload() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getSingleRequestParameters(), $this->getSingleRequestFile()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + } + + public function testRoute() + { + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $this->assertNotNull($endpoint); + $this->assertEquals(0, strpos('_uploader', $endpoint)); + } + + /** + * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + public function testCallByGet() + { + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $this->client->request('GET', $endpoint); + } + + /** + * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + public function testCallByDelete() + { + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $this->client->request('DELETE', $endpoint); + } + + /** + * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + public function testCallByPut() + { + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $this->client->request('PUT', $endpoint); + } + + public function testCallByPost() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + } + + protected function createTempFile($size = 128) + { + $file = tempnam(sys_get_temp_dir(), 'uploader_'); + file_put_contents($file, str_repeat('A', $size)); + + $this->createdFiles[] = $file; + + return $file; + } + + public function tearDown() + { + foreach($this->createdFiles as $file) { + @unlink($file); + } + } +} diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php new file mode 100644 index 0000000..f60d785 --- /dev/null +++ b/Tests/Controller/BlueimpTest.php @@ -0,0 +1,31 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; + +class BlueimpTest extends AbstractControllerTest +{ + protected function getConfigKey() + { + return 'blueimp'; + } + + protected function getSingleRequestParameters() + { + return array(); + } + + protected function getSingleRequestFile() + { + $file = new UploadedFile( + $this->createTempFile(128), + 'cat.txt', + 'text/plain', + 128 + ); + + return array($file); + } +}
0
16c08c46a3fa9ae679c5492996a6b61adceb280e
1up-lab/OneupUploaderBundle
Catch exception in tests (#345)
commit 16c08c46a3fa9ae679c5492996a6b61adceb280e Author: David Greminger <[email protected]> Date: Mon Jul 16 11:11:44 2018 +0200 Catch exception in tests (#345) diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index d092e58..d0c5cef 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -6,6 +6,7 @@ use Oneup\UploaderBundle\Templating\Helper\UploaderHelper; use Symfony\Bundle\FrameworkBundle\Client; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; abstract class AbstractControllerTest extends WebTestCase { @@ -102,6 +103,10 @@ abstract class AbstractControllerTest extends WebTestCase $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); + if (405 === $expectedStatusCode) { + $this->expectException(MethodNotAllowedHttpException::class); + } + $client->request($method, $endpoint, [], [], $this->requestHeaders); $response = $client->getResponse();
0
fa06d1f733a9dde68bbb52a42bdb69b9a4e44bf9
1up-lab/OneupUploaderBundle
Merge branch 'lsv-really-uniquenamer'
commit fa06d1f733a9dde68bbb52a42bdb69b9a4e44bf9 (from a453078f0ffc3496f482e39149768fbd1de63823) Merge: a453078 46acc77 Author: David Greminger <[email protected]> Date: Fri Sep 15 16:35:08 2017 +0200 Merge branch 'lsv-really-uniquenamer' diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 13d8f30..4389640 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -8,6 +8,7 @@ <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.urlsafename.class">Oneup\UploaderBundle\Uploader\Naming\UrlSafeNamer</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> @@ -40,6 +41,7 @@ <!-- namer --> <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" /> + <service id="oneup_uploader.namer.urlsafe" class="%oneup_uploader.namer.urlsafename.class%" /> <!-- routing --> <service id="oneup_uploader.routing.loader" class="%oneup_uploader.routing.loader.class%"> diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index fea6ee0..37be120 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -1,7 +1,24 @@ Custom Namer ============ -The purpose of a namer service is to name an uploaded file before it is stored to the storage layer. Currently the OneupUploaderBundle only provides a single namer service called `UniqidNamer`, which will return a system wide unique filename using the `uniqid()` function. +The purpose of a namer service is to name an uploaded file before it is stored to the storage layer. + +Currently the OneupUploaderBundle provides two namer methods. +- Default used is a namer called `UniqidNamer`, which will return a system wide unique filename using the `uniqid()` function. +- The other method called `UrlSafeNamer` using `random_bytes` function, see [Using UrlSafeNamer](#urlsafenamer) how to use it + +## UrlSafeNamer + +To enable UrlSafeNamer you will need to change your namer in your mappings to `oneup_uploader.namer.urlsafe` + +Example + +```yml +oneup_uploader: + mappings: + gallery: + namer: oneup_uploader.namer.urlsafe +``` ## Use a custom namer diff --git a/Tests/Uploader/Naming/UrlSafeNamerTest.php b/Tests/Uploader/Naming/UrlSafeNamerTest.php new file mode 100644 index 0000000..1707940 --- /dev/null +++ b/Tests/Uploader/Naming/UrlSafeNamerTest.php @@ -0,0 +1,53 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\Naming; + +use Oneup\UploaderBundle\Tests\Uploader\File\FileTest; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\Naming\UrlSafeNamer; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class UrlSafeNamerTest extends FileTest +{ + + public function setUp() + { + $this->path = sys_get_temp_dir(). '/oneup_namer_test'; + 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 testCanGetString() + { + $namer = new UrlSafeNamer(); + $this->assertTrue(is_string($namer->name($this->file))); + $this->assertStringEndsWith($this->extension, $namer->name($this->file)); + } + + public function test_two_file_names_not_equal() + { + $namer = new UrlSafeNamer(); + // Trying 200 times just to be sure + for($i = 0; $i < 200; $i++) { + $name1 = $namer->name($this->file); + $name2 = $namer->name($this->file); + $this->assertNotEquals($name1, $name2); + } + + } + + public function tearDown() + { + unlink($this->pathname); + rmdir($this->path); + } + +} diff --git a/Uploader/Naming/UrlSafeNamer.php b/Uploader/Naming/UrlSafeNamer.php new file mode 100644 index 0000000..7ff6660 --- /dev/null +++ b/Uploader/Naming/UrlSafeNamer.php @@ -0,0 +1,21 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Naming; + +use Oneup\UploaderBundle\Uploader\File\FileInterface; + +class UrlSafeNamer implements NamerInterface +{ + + /** + * Name a given file and return the name + * + * @param FileInterface $file + * @return string + */ + public function name(FileInterface $file) + { + $bytes = random_bytes(256 / 8); + return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=') . '.' . $file->getExtension(); + } +} diff --git a/composer.json b/composer.json index b0ef8ce..a5cea42 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ "require": { "php":">=5.4", "symfony/framework-bundle": "^2.4.0|~3.0", - "symfony/finder": "^2.4.0|~3.0" + "symfony/finder": "^2.4.0|~3.0", + "paragonie/random_compat": "^1.1" }, "require-dev": {
0
b0065a6002387f8eabb4ac8fff5c13e137526d77
1up-lab/OneupUploaderBundle
Adding a real unique namer
commit b0065a6002387f8eabb4ac8fff5c13e137526d77 Author: Martin Aarhof <[email protected]> Date: Sat Jan 23 15:58:02 2016 +0100 Adding a real unique namer diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index c970994..0e80c99 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -7,6 +7,7 @@ <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.urlsafename.class">Oneup\UploaderBundle\Uploader\Naming\UrlSafeNamer</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> @@ -38,6 +39,7 @@ <!-- namer --> <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" /> + <service id="oneup_uploader.namer.urlsafe" class="%oneup_uploader.namer.urlsafename.class%" /> <!-- routing --> <service id="oneup_uploader.routing.loader" class="%oneup_uploader.routing.loader.class%"> diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index c83002d..7ac3fc1 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -1,7 +1,24 @@ Custom Namer ============ -The purpose of a namer service is to name an uploaded file before it is stored to the storage layer. Currently the OneupUploaderBundle only provides a single namer service called `UniqidNamer`, which will return a system wide unique filename using the `uniqid()` function. +The purpose of a namer service is to name an uploaded file before it is stored to the storage layer. + +Currently the OneupUploaderBundle provides two namer methods. +- Default used is a namer called `UniqidNamer`, which will return a system wide unique filename using the `uniqid()` function. +- The other method called `UrlSafeNamer` using `random_bytes` function, see [Using UrlSafeNamer](#urlsafenamer) how to use it + +## UrlSafeNamer + +To enable UrlSafeNamer you will need to change your namer in your mappings to `oneup_uploader.namer.urlsafe` + +Example + +```yml +oneup_uploader: + mappings: + gallery: + namer: oneup_uploader.namer.urlsafe +``` ## Use a custom namer diff --git a/Tests/Uploader/Naming/UrlSafeNamerTest.php b/Tests/Uploader/Naming/UrlSafeNamerTest.php new file mode 100644 index 0000000..8673c91 --- /dev/null +++ b/Tests/Uploader/Naming/UrlSafeNamerTest.php @@ -0,0 +1,65 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\Naming; + +use Oneup\UploaderBundle\Tests\Uploader\File\FileTest; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\Naming\UrlSafeNamer; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class UrlSafeNamerTest extends FileTest +{ + + public function setUp() + { + $this->path = sys_get_temp_dir(). '/oneup_namer_test'; + 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 testCanGetString() + { + $namer = new UrlSafeNamer(); + $this->assertTrue(is_string($namer->name($this->file))); + $this->assertStringEndsWith($this->extension, $namer->name($this->file)); + } + + public function test_two_file_names_not_equal() + { + $file = $this->getMockBuilder('Oneup\UploaderBundle\Uploader\File\FilesystemFile') + ->disableOriginalConstructor() + ->getMock() + ; + + $file + ->expects($this->any()) + ->method('getExtension') + ->will($this->returnValue('jpeg')) + ; + + /** @var \Oneup\UploaderBundle\Uploader\File\FileInterface $file */ + $namer = new UrlSafeNamer(); + // Trying 200 times just to be sure + for($i = 0; $i < 200; $i++) { + $name1 = $namer->name($file); + $name2 = $namer->name($file); + $this->assertNotEquals($name1, $name2); + } + + } + + public function tearDown() + { + unlink($this->pathname); + rmdir($this->path); + } + +} diff --git a/Uploader/Naming/UrlSafeNamer.php b/Uploader/Naming/UrlSafeNamer.php new file mode 100644 index 0000000..7ff6660 --- /dev/null +++ b/Uploader/Naming/UrlSafeNamer.php @@ -0,0 +1,21 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Naming; + +use Oneup\UploaderBundle\Uploader\File\FileInterface; + +class UrlSafeNamer implements NamerInterface +{ + + /** + * Name a given file and return the name + * + * @param FileInterface $file + * @return string + */ + public function name(FileInterface $file) + { + $bytes = random_bytes(256 / 8); + return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=') . '.' . $file->getExtension(); + } +} diff --git a/composer.json b/composer.json index b2f32a3..7e123de 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,8 @@ "require": { "symfony/framework-bundle": "^2.4.0|~3.0", - "symfony/finder": "^2.4.0|~3.0" + "symfony/finder": "^2.4.0|~3.0", + "paragonie/random_compat": "^1.1" }, "require-dev": {
0
579231a07b75193336c18d082fab862af8c8a00e
1up-lab/OneupUploaderBundle
Added TemplateHelperTest for code coverage completion.
commit 579231a07b75193336c18d082fab862af8c8a00e Author: Jim Schmid <[email protected]> Date: Mon May 6 22:43:48 2013 +0200 Added TemplateHelperTest for code coverage completion. diff --git a/Tests/Templating/TemplateHelperTest.php b/Tests/Templating/TemplateHelperTest.php new file mode 100644 index 0000000..7dc17eb --- /dev/null +++ b/Tests/Templating/TemplateHelperTest.php @@ -0,0 +1,19 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk; + +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; + +class TemplateHelperTest extends WebTestCase +{ + public function testName() + { + $client = static::createClient(); + $container = $client->getContainer(); + + $helper = $container->get('oneup_uploader.templating.uploader_helper'); + + // this is for code coverage + $this->assertEquals($helper->getName(), 'oneup_uploader'); + } +}
0
7f7009a0a29a7d864f9ae0c8dec979bc5f53dd65
1up-lab/OneupUploaderBundle
Supress weird tempnam() output (due to php71)
commit 7f7009a0a29a7d864f9ae0c8dec979bc5f53dd65 Author: David Greminger <[email protected]> Date: Thu Dec 15 10:22:33 2016 +0100 Supress weird tempnam() output (due to php71) diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index a277d7e..f78b1fc 100644 --- a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -114,6 +114,6 @@ class FlysystemOrphanageStorageTest extends OrphanageTest public function checkIfTempnameMatchesAfterCreation() { - return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + return strpos(@tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; } } diff --git a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php index 418298c..a9e55cb 100644 --- a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php @@ -113,6 +113,6 @@ class GaufretteOrphanageStorageTest extends OrphanageTest public function checkIfTempnameMatchesAfterCreation() { - return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + return strpos(@tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; } }
0
513bcab5d405c388e70773dca66454d82d2da4a8
1up-lab/OneupUploaderBundle
CS fixes for DI and root files.
commit 513bcab5d405c388e70773dca66454d82d2da4a8 Author: Jim Schmid <[email protected]> Date: Thu Jun 20 21:25:14 2013 +0200 CS fixes for DI and root files. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c22b3d1..c38cf24 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -4,14 +4,14 @@ namespace Oneup\UploaderBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; - + class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('oneup_uploader'); - + $rootNode ->children() ->arrayNode('chunks') @@ -78,7 +78,7 @@ class Configuration implements ConfigurationInterface ->end() ->end() ; - + return $treeBuilder; } -} \ No newline at end of file +} diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index c8acf0a..24c872a 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -13,89 +13,81 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { protected $storageServices = array(); - + public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - + $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); $loader->load('templating.xml'); $loader->load('validators.xml'); - - if($config['twig']) - { + + if ($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']) ; - + $config['orphanage']['directory'] = is_null($config['orphanage']['directory']) ? sprintf('%s/uploader/orphanage', $container->getParameter('kernel.cache_dir')) : $this->normalizePath($config['orphanage']['directory']) ; - + $container->setParameter('oneup_uploader.chunks', $config['chunks']); $container->setParameter('oneup_uploader.orphanage', $config['orphanage']); - + $controllers = array(); - + // handle mappings - foreach($config['mappings'] as $key => $mapping) - { + foreach ($config['mappings'] as $key => $mapping) { $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); // 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'])) - { + if (!is_null($mapping['storage']['service'])) { $storageService = new Reference($mapping['storage']['service']); - } - else - { + } else { // no service was given, so we create one $storageName = sprintf('oneup_uploader.storage.%s', $key); - - if($mapping['storage']['type'] == 'filesystem') - { + + 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, $container->getParameter(sprintf('oneup_uploader.storage.%s.class', $mapping['storage']['type']))) ->addArgument($mapping['storage']['directory']) ; } - - if($mapping['storage']['type'] == 'gaufrette') - { + + 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, $container->getParameter(sprintf('oneup_uploader.storage.%s.class', $mapping['storage']['type']))) ->addArgument(new Reference($mapping['storage']['filesystem'])) ; } - + $storageService = new Reference($storageName); - - if($mapping['use_orphanage']) - { + + 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 @@ -110,69 +102,65 @@ class OneupUploaderExtension extends Extension $storageService = new Reference($orphanageName); } } - - if($mapping['frontend'] != 'custom') - { + + if ($mapping['frontend'] != 'custom') { $controllerName = sprintf('oneup_uploader.controller.%s', $key); $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $mapping['frontend']); - } - else - { + } else { $customFrontend = $mapping['custom_frontend']; - + $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.'); } - + // create controllers based on mapping $container ->register($controllerName, $controllerType) - + ->addArgument(new Reference('service_container')) ->addArgument($storageService) ->addArgument($mapping) ->addArgument($key) - + ->addTag('oneup_uploader.routable', array('type' => $key)) ->setScope('request') ; - + $controllers[$key] = $controllerName; } - + $container->setParameter('oneup_uploader.controllers', $controllers); } - + protected function getMaxUploadSize($input) { $input = $this->getValueInBytes($input); $maxPost = $this->getValueInBytes(ini_get('upload_max_filesize')); $maxFile = $this->getValueInBytes(ini_get('post_max_size')); - + return min(min($input, $maxPost), $maxFile); } - + protected function getValueInBytes($input) { // see: http://www.php.net/manual/en/function.ini-get.php $input = trim($input); $last = strtolower($input[strlen($input) - 1]); - - switch($last) - { + + switch ($last) { case 'g': $input *= 1024; case 'm': $input *= 1024; case 'k': $input *= 1024; } - + return $input; } - + protected function normalizePath($input) { return rtrim($input, '/'); } -} \ No newline at end of file +} diff --git a/OneupUploaderBundle.php b/OneupUploaderBundle.php index 693f273..2eaf18f 100644 --- a/OneupUploaderBundle.php +++ b/OneupUploaderBundle.php @@ -3,10 +3,7 @@ namespace Oneup\UploaderBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; -use Symfony\Component\DependencyInjection\ContainerBuilder; - -use Oneup\UploaderBundle\DependencyInjection\Compiler\ControllerCompilerPass; class OneupUploaderBundle extends Bundle { -} \ No newline at end of file +} diff --git a/UploadEvents.php b/UploadEvents.php index 73f5c93..12b97a6 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -8,4 +8,4 @@ final class UploadEvents const POST_UPLOAD = 'oneup_uploader.post_upload'; const POST_CHUNK_UPLOAD = 'oneup_uploader.post_chunk_upload'; const VALIDATION = 'oneup_uploader.validation'; -} \ No newline at end of file +}
0
725490c30f1eef6774e1f08e719ba128cf94d984
1up-lab/OneupUploaderBundle
Fix CS.
commit 725490c30f1eef6774e1f08e719ba128cf94d984 Author: Jim Schmid <[email protected]> Date: Mon Mar 11 14:03:06 2013 +0100 Fix CS. diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 4d1077d..74ced99 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -37,7 +37,6 @@ class ChunkManager implements ChunkManagerInterface return; } - foreach($finder as $file) { $system->remove($file);
0
f8bab11872e3f9b3b77c526e4b4ecd51db558d28
1up-lab/OneupUploaderBundle
Fixes a wrong function call to array_key_exists.
commit f8bab11872e3f9b3b77c526e4b4ecd51db558d28 Author: Jim Schmid <[email protected]> Date: Tue Mar 12 17:49:28 2013 +0100 Fixes a wrong function call to array_key_exists. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 7dc1244..bc4b949 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -37,7 +37,7 @@ class OneupUploaderExtension extends Extension // handle mappings foreach($config['mappings'] as $key => $mapping) { - if(!array_key_exists($mapping['directory_prefix'])) + if(!array_key_exists('directory_prefix', $mapping)) { $mapping['directory_prefix'] = $key; }
0
13e312a9f059da53094702f5b3e1a25dacccb7a4
1up-lab/OneupUploaderBundle
Added missing instance variables and TypeHinting for constructor variables.
commit 13e312a9f059da53094702f5b3e1a25dacccb7a4 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 17:20:52 2013 +0100 Added missing instance variables and TypeHinting for constructor variables. diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 9593d07..13d0d4b 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -4,14 +4,17 @@ 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($container, $configuration) + public function __construct(ContainerInterface $container, array $configuration) { $this->container = $container; $this->configuration = $configuration;
0
c5e249ba547b3179ca83b09628322273ef364806
1up-lab/OneupUploaderBundle
Added PHPDoc block for ErrorHandlerInterface.
commit c5e249ba547b3179ca83b09628322273ef364806 Author: Jim Schmid <[email protected]> Date: Tue Aug 13 15:41:00 2013 +0200 Added PHPDoc block for ErrorHandlerInterface. diff --git a/Uploader/ErrorHandler/ErrorHandlerInterface.php b/Uploader/ErrorHandler/ErrorHandlerInterface.php index 4d59aa3..453de0d 100644 --- a/Uploader/ErrorHandler/ErrorHandlerInterface.php +++ b/Uploader/ErrorHandler/ErrorHandlerInterface.php @@ -7,5 +7,13 @@ use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; interface ErrorHandlerInterface { + /** + * Adds an exception to a given response + * + * @param AbstractResponse $response + * @param Exception $exception + * + * @return void + */ public function addException(AbstractResponse $response, Exception $exception); }
0
77bdcdee09cbe9a8c80854c5888585dd62b20fbd
1up-lab/OneupUploaderBundle
Fix Flysystem integration and add tests
commit 77bdcdee09cbe9a8c80854c5888585dd62b20fbd Author: Jérôme Parmentier <[email protected]> Date: Fri Oct 6 17:48:45 2017 +0200 Fix Flysystem integration and add tests 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..ddb5664 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 { @@ -38,12 +39,14 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $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 +71,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 +105,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(); diff --git a/Uploader/Chunk/Storage/FlysystemStorage.php b/Uploader/Chunk/Storage/FlysystemStorage.php index 19e7a44..5afbfa5 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; @@ -22,13 +23,17 @@ class FlysystemStorage implements ChunkStorageInterface public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) { if ( - ! method_exists($filesystem, 'readStream') + !method_exists($filesystem, 'readStream') || - ! method_exists($filesystem, 'putStream') + !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; $this->bufferSize = $bufferSize; $this->prefix = $prefix; @@ -37,8 +42,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 +52,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 +78,7 @@ class FlysystemStorage implements ChunkStorageInterface 'uuid' => $uuid, 'index' => $index, 'chunk' => $chunk, - 'original' => $original + 'original' => $original, ); } @@ -91,21 +92,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 +136,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 +157,4 @@ class FlysystemStorage implements ChunkStorageInterface { return $this->streamWrapperPrefix; } - } 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/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
d55763721f67b3100ec2986e5bad901a6cb62fc7
1up-lab/OneupUploaderBundle
Added the size to the temporary created UploadedFile, so clientSize won't be null. Details in #36.
commit d55763721f67b3100ec2986e5bad901a6cb62fc7 Author: Jim Schmid <[email protected]> Date: Thu Jul 25 20:01:21 2013 +0200 Added the size to the temporary created UploadedFile, so clientSize won't be null. Details in #36. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index beabd2e..020d315 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -74,7 +74,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, null, null, true); + $uploadedFile = new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, $assembled->getSize(), null, true); $uploaded = $this->handleUpload($uploadedFile, $response, $request); $chunkManager->cleanup($path); diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index e7c207d..cd70c1e 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\PostUploadEvent; use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\UploadEvents; @@ -37,6 +38,8 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$me, $basename) { $file = $event->getFile(); + $me->assertNotNull($file->getClientSize()); + $me->assertGreaterThan(0, $file->getClientSize()); $me->assertEquals($file->getBasename(), $basename); });
0
fdebca99c4c4b55ce2cfa71f89942b2e5c343cbf
1up-lab/OneupUploaderBundle
Update testing.md Added a note about how to enable the new AWS test which came along with pr #18.
commit fdebca99c4c4b55ce2cfa71f89942b2e5c343cbf Author: Jim Schmid <[email protected]> Date: Wed Jun 12 09:42:41 2013 +0200 Update testing.md Added a note about how to enable the new AWS test which came along with pr #18. diff --git a/Resources/doc/testing.md b/Resources/doc/testing.md index 7da4cb2..91a37a6 100644 --- a/Resources/doc/testing.md +++ b/Resources/doc/testing.md @@ -14,6 +14,17 @@ You can run the unit tests by simply performing the follwowing command. $> phpunit +If you are using the Gaufrette storage to upload files to an Amazon S3 instance be sure to add your AWS credentials by exporting them as environment variables. +It will enable an otherwise skipped test. + +```bash +export AWS_ACCESS_KEY_ID="your-id-here" +export AWS_SECRET_ACCESS_KEY="your-key-here" +export AWS_BUCKET="your-bucket-name-here" +``` + +Details can be found in the corresponding [pull request](https://github.com/1up-lab/OneupUploaderBundle/pull/18). + ## Testing Code Coverage PHPUnit comes bundles with a handy feature to test the code coverage of a project. I recommend using the following configuration to enable the creation of code coverage reports in the `log` directory in the root of this bundle. This directory is gitignored by default. @@ -57,4 +68,4 @@ The directories `Command`, `DependencyInjection` and `Event` are excluded from t Run the test suite and generate reports by running: - $> phpunit \ No newline at end of file + $> phpunit
0
6d945acde6d375b2077f0874e7a2a9757dd9874e
1up-lab/OneupUploaderBundle
replace the deprecated "Twig_Function_Method" replace it with the recommended "Twig_SimpleFunction" as per Twig docs
commit 6d945acde6d375b2077f0874e7a2a9757dd9874e Author: Ahmad Tawila <[email protected]> Date: Sun Oct 25 05:54:29 2015 +0200 replace the deprecated "Twig_Function_Method" replace it with the recommended "Twig_SimpleFunction" as per Twig docs diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index c042e56..ab76375 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -21,11 +21,11 @@ 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_cancel' => new \Twig_Function_Method($this, 'cancel'), - 'oneup_uploader_upload_key' => new \Twig_Function_Method($this, 'uploadKey'), - 'oneup_uploader_maxsize' => new \Twig_Function_Method($this, 'maxSize'), + 'oneup_uploader_endpoint' => new \Twig_SimpleFunction('endpoint', array($this, 'endpoint')), + 'oneup_uploader_progress' => new \Twig_SimpleFunction('progress', array($this, 'progress')), + 'oneup_uploader_cancel' => new \Twig_SimpleFunction('cancel', array($this, 'cancel')), + 'oneup_uploader_upload_key' => new \Twig_SimpleFunction('uploadKey', array($this, 'uploadKey')), + 'oneup_uploader_maxsize' => new \Twig_SimpleFunction('maxSize', array($this, 'maxSize')), ); }
0
676ef153a7ed0607e1ca777cf8bd67e76aa1ee7b
1up-lab/OneupUploaderBundle
Added configuration reference file and link from index.md
commit 676ef153a7ed0607e1ca777cf8bd67e76aa1ee7b Author: Jim Schmid <[email protected]> Date: Sun Apr 7 13:07:56 2013 +0200 Added configuration reference file and link from index.md diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md new file mode 100644 index 0000000..e69de29 diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 0fec11f..05a27f0 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -95,4 +95,11 @@ $(document).ready(function() <div id="uploader"></div> ``` -This is of course a very minimal setup. Be sure to include stylesheets for Fine Uploader if you want to use them. \ No newline at end of file +This is of course a very minimal setup. Be sure to include stylesheets for Fine Uploader if you want to use them. + +## Next steps + +After installing and setting up the basic functionality of this bundle you can move on and integrate +some more advanced features. + +* [Configuration Reference](configuration_reference.md) \ No newline at end of file
0
7288cecd805802baf5f8660bea7d894cf75084e8
1up-lab/OneupUploaderBundle
Fixes ChunkManager class declaration.
commit 7288cecd805802baf5f8660bea7d894cf75084e8 Author: Jim Schmid <[email protected]> Date: Mon Mar 11 13:39:52 2013 +0100 Fixes ChunkManager class declaration. diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index f10809d..72d08e6 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <parameters> - <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunks\ChunkManager</parameter> + <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> </parameters> <services>
0
0429688c6d9880c953b72ef8c68660dc0c1bd551
1up-lab/OneupUploaderBundle
Changed translation keys in Controller.
commit 0429688c6d9880c953b72ef8c68660dc0c1bd551 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 23:21:51 2013 +0200 Changed translation keys in Controller. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index f7880cb..3bf61a5 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -126,19 +126,19 @@ class UploaderController implements UploadControllerInterface { // 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('File is too large.'); + 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('This extension is not allowed.'); + 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('This extension is not allowed.'); + throw new UploadException('error.blacklist'); } } \ No newline at end of file
0
b7596dd4204342ab663e1e2675bdd7d9e2efd55f
1up-lab/OneupUploaderBundle
Test uploadFiles() if orphanage path does not exist.
commit b7596dd4204342ab663e1e2675bdd7d9e2efd55f Author: Jim Schmid <[email protected]> Date: Sat Apr 6 21:35:58 2013 +0200 Test uploadFiles() if orphanage path does not exist. diff --git a/Tests/Uploader/Storage/OrphanageStorageTest.php b/Tests/Uploader/Storage/OrphanageStorageTest.php index c09caaf..070c677 100644 --- a/Tests/Uploader/Storage/OrphanageStorageTest.php +++ b/Tests/Uploader/Storage/OrphanageStorageTest.php @@ -100,6 +100,17 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase $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 tearDown() { $filesystem = new Filesystem();
0
603ab521de2ee222f1e7f7fb0e6677658b57471f
1up-lab/OneupUploaderBundle
Documented Dropzone uploader
commit 603ab521de2ee222f1e7f7fb0e6677658b57471f Author: Jim Schmid <[email protected]> Date: Wed Sep 18 12:18:17 2013 +0200 Documented Dropzone uploader diff --git a/README.md b/README.md index d7ed3fd..a8b708b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ The OneupUploaderBundle for Symfony2 adds support for handling file uploads usin * [FancyUpload](http://digitarald.de/project/fancyupload/) * [MooUpload](https://github.com/juanparati/MooUpload) * [Plupload](http://www.plupload.com/) +* [Dropzone](http://www.dropzonejs.com/) Features included: diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md new file mode 100644 index 0000000..0be52b3 --- /dev/null +++ b/Resources/doc/frontend_dropzone.md @@ -0,0 +1,24 @@ +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> + +<form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone"> +</form> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: dropzone +``` + +Be sure to check out the [official manual](http://www.dropzonejs.com/) for details on the configuration. \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 8d85022..29ccad1 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -96,7 +96,7 @@ $endpoint = $helper->endpoint('gallery'); or in a Twig template you can use the `oneup_uploader_endpoint` function: {{ oneup_uploader_endpoint('gallery') }} - + 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: * [Use FineUploader](frontend_fineuploader.md) @@ -106,6 +106,7 @@ So if you take the mapping described before, the generated route name would be ` * [Use FancyUpload](frontend_fancyupload.md) * [Use MooUpload](frontend_mooupload.md) * [Use Plupload](frontend_plupload.md) +* [Use Dropzone]|(frontend_dropzone.md) ## Next steps diff --git a/composer.json b/composer.json index 2dfd657..37e7667 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "oneup/uploader-bundle", "type": "symfony-bundle", "description": "Handles multi file uploads in Symfony2. Features included: Chunked upload, Orphans management, Gaufrette support.", - "keywords": ["fileupload", "upload", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload", "Plupload"], + "keywords": ["fileupload", "upload", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload", "Plupload", "Dropzone"], "homepage": "http://1up.io", "license": "MIT", "authors": [
0
e3b5e71bbf33e5c635e97eaf2a0334c2a5c0b2c5
1up-lab/OneupUploaderBundle
Fixed a bug in a getter of MooUploadResponse.
commit e3b5e71bbf33e5c635e97eaf2a0334c2a5c0b2c5 Author: Jim Schmid <[email protected]> Date: Thu Apr 18 20:17:43 2013 +0200 Fixed a bug in a getter of MooUploadResponse. diff --git a/Uploader/Response/MooUploadResponse.php b/Uploader/Response/MooUploadResponse.php index 36e8572..44e0db4 100644 --- a/Uploader/Response/MooUploadResponse.php +++ b/Uploader/Response/MooUploadResponse.php @@ -56,7 +56,7 @@ class MooUploadResponse extends AbstractResponse public function getName() { - return $this->id; + return $this->name; } public function setSize($size)
0
674398ffe9fc5dce0e8f5b940c7535c353863b3f
1up-lab/OneupUploaderBundle
Changed type of node use_orphanage to BooleanNode instead of scalarNode
commit 674398ffe9fc5dce0e8f5b940c7535c353863b3f Author: Jim Schmid <[email protected]> Date: Tue Mar 12 11:31:20 2013 +0100 Changed type of node use_orphanage to BooleanNode instead of scalarNode diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 6e820db..a238a49 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -42,7 +42,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->scalarNode('storage')->isRequired()->end() - ->scalarNode('use_orphanage')->defaultFalse()->end() + ->booleanNode('use_orphanage')->defaultFalse()->end() ->scalarNode('action')->defaultNull()->end() ->scalarNode('namer')->defaultNull()->end() ->end()
0
03fb43403d135ec89c507a565250b7b8c2db504c
1up-lab/OneupUploaderBundle
Added Validation test for Plupload uploader.
commit 03fb43403d135ec89c507a565250b7b8c2db504c Author: Jim Schmid <[email protected]> Date: Sat May 18 16:53:48 2013 +0200 Added Validation test for Plupload uploader. diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 1e0ae87..a7d02f4 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -52,6 +52,15 @@ oneup_uploader: frontend: plupload storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + + plupload_validation: + frontend: plupload + 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" ] uploadify: frontend: uploadify diff --git a/Tests/Controller/PluploadValidationTest.php b/Tests/Controller/PluploadValidationTest.php new file mode 100644 index 0000000..0bdbd03 --- /dev/null +++ b/Tests/Controller/PluploadValidationTest.php @@ -0,0 +1,59 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; + +class PluploadValidationTest extends AbstractValidationTest +{ + protected function getConfigKey() + { + return 'plupload_validation'; + } + + protected function getRequestParameters() + { + return array(); + } + + 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( + $this->createTempFile(128), + 'cat.ok', + 'image/jpg', + 128 + ); + } + + protected function getFileWithIncorrectMimeType() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'image/gif', + 128 + ); + } +} diff --git a/Tests/Controller/YUI3ValidationTest.php b/Tests/Controller/YUI3ValidationTest.php index c3781cb..bd09245 100644 --- a/Tests/Controller/YUI3ValidationTest.php +++ b/Tests/Controller/YUI3ValidationTest.php @@ -3,7 +3,7 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; class YUI3ValidationTest extends AbstractValidationTest {
0
2138609ee5cebdc2b151669b0eae2e104ecb6816
1up-lab/OneupUploaderBundle
Fix: README.md Symfony 2.8.2 Error without the fix : UploadListener::__construct() must be an instance of Doctrine\Common\Persistence\ObjectManager, none given
commit 2138609ee5cebdc2b151669b0eae2e104ecb6816 Author: p1rox <[email protected]> Date: Sat Feb 13 11:54:34 2016 +0100 Fix: README.md Symfony 2.8.2 Error without the fix : UploadListener::__construct() must be an instance of Doctrine\Common\Persistence\ObjectManager, none given diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 6fea373..1aa1cfd 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -50,7 +50,7 @@ And register it in your `services.xml`. services: acme_hello.upload_listener: class: AppBundle\EventListener\UploadListener - argument: ["@doctrine.orm.entity_manager"] + arguments: ["@doctrine.orm.entity_manager"] tags: - { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload } ```
0
082f119827d52101398ec25abd4fc1278e7b1ad1
1up-lab/OneupUploaderBundle
orphanage for gaufrette chunk storage
commit 082f119827d52101398ec25abd4fc1278e7b1ad1 Author: mitom <[email protected]> Date: Fri Oct 11 13:07:30 2013 +0200 orphanage for gaufrette chunk storage diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index a86036f..b25c844 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -50,8 +50,13 @@ class OneupUploaderExtension extends Extension protected function processOrphanageConfig() { - $this->config['orphanage']['directory'] = is_null($this->config['orphanage']['directory']) ? - sprintf('%s/uploader/orphanage', $this->container->getParameter('kernel.cache_dir')) : + 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']) ; } @@ -75,7 +80,7 @@ class OneupUploaderExtension extends Extension protected function createController($key, $config) { // create the storage service according to the configuration - $storageService = $this->createStorageService($config['storage'], $key, isset($config['orphanage']) ? :null); + $storageService = $this->createStorageService($config['storage'], $key, $config['use_orphanage']); if ($config['frontend'] != 'custom') { $controllerName = sprintf('oneup_uploader.controller.%s', $key); @@ -149,13 +154,15 @@ class OneupUploaderExtension extends Extension $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; } } - protected function createStorageService(&$config, $key, $orphanage = null) + protected function createStorageService(&$config, $key, $orphanage = false) { $storageService = null; @@ -201,6 +208,7 @@ class OneupUploaderExtension extends Extension ->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) ; diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 66c7e70..c970994 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -11,7 +11,7 @@ <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> diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index 19fea99..95667fd 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 diff --git a/Tests/Uploader/Storage/OrphanageStorageTest.php b/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php similarity index 89% rename from Tests/Uploader/Storage/OrphanageStorageTest.php rename to Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php index b2eed0a..2278b96 100644 --- a/Tests/Uploader/Storage/OrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FilesystemOrphanageStorageTest.php @@ -3,16 +3,17 @@ 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; 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 +class FilesystemOrphanageStorageTest extends \PHPUnit_Framework_TestCase { protected $tempDirectory; protected $realDirectory; @@ -45,6 +46,8 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase // create underlying storage $this->storage = new FilesystemStorage($this->realDirectory); + // is ignored anyways + $chunkStorage = new FilesystemChunkStorage('/tmp/'); // create orphanage $session = new Session(new MockArraySessionStorage()); @@ -52,7 +55,7 @@ class OrphanageStorageTest extends \PHPUnit_Framework_TestCase $config = array('directory' => $this->tempDirectory); - $this->orphanage = new OrphanageStorage($this->storage, $session, $config, 'cat'); + $this->orphanage = new FilesystemOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat'); } public function testUpload() diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index 4f5a286..cfd55e3 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -27,9 +27,18 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface $this->streamWrapperPrefix = $streamWrapperPrefix; } - public function clear($maxAge) + /** + * 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) { - $matches = $this->filesystem->listKeys($this->prefix); + $prefix = $prefix ? :$this->prefix; + $matches = $this->filesystem->listKeys($prefix); $limit = time()+$maxAge; $toDelete = array(); @@ -140,4 +149,9 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface { return $this->filesystem->listKeys($this->prefix.'/'.$uuid)['keys']; } + + public function getFilesystem() + { + return $this->filesystem; + } } diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php index 3ae16c5..58868b8 100644 --- a/Uploader/Gaufrette/StreamManager.php +++ b/Uploader/Gaufrette/StreamManager.php @@ -10,7 +10,7 @@ use Oneup\UploaderBundle\Uploader\File\GaufretteFile; class StreamManager { protected $filesystem; - protected $buffersize; + public $buffersize; protected function createSourceStream(FileInterface $file) { 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 85% rename from Uploader/Storage/OrphanageStorage.php rename to Uploader/Storage/FilesystemOrphanageStorage.php index 22656aa..e0026cc 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -2,6 +2,7 @@ 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; @@ -12,17 +13,18 @@ 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; diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php new file mode 100644 index 0000000..40f83f9 --- /dev/null +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -0,0 +1,93 @@ +<?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) { + // don't delete the file, if the upload failed beaces + // 1, it may not exist and deleting would throw another exception; + // 2, don't lose it on network related errors + continue; + } + + $this->chunkStorage->getFilesystem()->delete($key); + } + + return $return; + } catch (\Exception $e) { + return array(); + } + } + + public function getFiles() + { + $keys = $this->chunkStorage->getFilesystem()->listKeys($this->getPath())['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); + } + +}
0
334a88dc634812fa36697255f7c0bebf9ce37c7e
1up-lab/OneupUploaderBundle
Change dropzone.js path in the example (#313)
commit 334a88dc634812fa36697255f7c0bebf9ce37c7e Author: Łukasz Chruściel <[email protected]> Date: Mon Jan 29 14:12:25 2018 +0100 Change dropzone.js path in the example (#313) diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md index 875fb3d..c6b2c64 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://raw.github.com/enyo/dropzone/master/dist/dropzone.js"></script> +<script type="text/javascript" src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script> <form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone" style="width:200px; height:200px; border:4px dashed black"> </form>
0
41ac1d8ce5e72f2d12e935400b1d066e06e71402
1up-lab/OneupUploaderBundle
DI: replace direct params usage with %param.name% After that, finally we can override 'oneup_uploader.orphanage.class' for example in parameters.yml as described in http://symfony.com/doc/current/cookbook/bundles/override.html
commit 41ac1d8ce5e72f2d12e935400b1d066e06e71402 Author: Veniamin Albaev <[email protected]> Date: Thu Jul 18 14:52:40 2013 +0400 DI: replace direct params usage with %param.name% After that, finally we can override 'oneup_uploader.orphanage.class' for example in parameters.yml as described in http://symfony.com/doc/current/cookbook/bundles/override.html diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 108394c..a7cdbba 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -66,7 +66,7 @@ class OneupUploaderExtension extends Extension ; $container - ->register($storageName, $container->getParameter(sprintf('oneup_uploader.storage.%s.class', $mapping['storage']['type']))) + ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $mapping['storage']['type'])) ->addArgument($mapping['storage']['directory']) ; } @@ -79,7 +79,7 @@ class OneupUploaderExtension extends Extension throw new ServiceNotFoundException('Empty service name'); $container - ->register($storageName, $container->getParameter(sprintf('oneup_uploader.storage.%s.class', $mapping['storage']['type']))) + ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $mapping['storage']['type'])) ->addArgument(new Reference($mapping['storage']['filesystem'])) ; } @@ -92,7 +92,7 @@ class OneupUploaderExtension extends Extension // this mapping wants to use the orphanage, so create // a masked filesystem for the controller $container - ->register($orphanageName, $container->getParameter('oneup_uploader.orphanage.class')) + ->register($orphanageName, '%oneup_uploader.orphanage.class%') ->addArgument($storageService) ->addArgument(new Reference('session')) ->addArgument($config['orphanage'])
0
d9413ed05dda52578ba5e63af60f1be8965f482c
1up-lab/OneupUploaderBundle
Merge branch 'mhlavac-patch-2'
commit d9413ed05dda52578ba5e63af60f1be8965f482c (from 4aac33eb36be7760ee5449cfc6100250e54401a2) Merge: 4aac33e 4c3304c Author: David Greminger <[email protected]> Date: Mon Jan 23 13:57:22 2017 +0100 Merge branch 'mhlavac-patch-2' diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 0d472ff..c2c14eb 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -294,7 +294,7 @@ class OneupUploaderExtension extends Extension // see: http://www.php.net/manual/en/function.ini-get.php $input = trim($input); $last = strtolower($input[strlen($input) - 1]); - $numericInput = substr($input, 0, -1); + $numericInput = (float) substr($input, 0, -1); switch ($last) { case 'g': $numericInput *= 1024;
0
c20145de1b3181b253994d00a4e4611885379c42
1up-lab/OneupUploaderBundle
Disable deprecations
commit c20145de1b3181b253994d00a4e4611885379c42 Author: David Greminger <[email protected]> Date: Tue Feb 4 14:15:41 2020 +0100 Disable deprecations diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 2e0c235..ac3d9e2 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -4,6 +4,7 @@ <php> <server name="KERNEL_DIR" value="Tests/App" /> <server name="KERNEL_CLASS" value="AppKernel" /> + <env name="SYMFONY_DEPRECATIONS_HELPER" value="disabled=1" /> </php> <listeners>
0
4c51d95f8b59b8373d351a26373cae0bcd69d650
1up-lab/OneupUploaderBundle
Add warning to custom namer doc
commit 4c51d95f8b59b8373d351a26373cae0bcd69d650 Author: JHGitty <[email protected]> Date: Sun Feb 7 19:46:38 2016 +0100 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`
0
5b1b2076daab43b3e8aaed9e0b43cb537142c456
1up-lab/OneupUploaderBundle
Merge branch 'snarktooth-master'
commit 5b1b2076daab43b3e8aaed9e0b43cb537142c456 (from c5a1ce9a0e7b2f84982ccff39ba88832e0602cae) Merge: c5a1ce9 aec4bea Author: David Greminger <[email protected]> Date: Wed May 3 11:01:35 2017 +0200 Merge branch 'snarktooth-master' diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index f78b1fc..102e954 100644 --- a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -29,15 +29,15 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $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); + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + $adapter = new Adapter($this->realDirectory, true); $filesystem = new FSAdapter($adapter); @@ -61,7 +61,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest fwrite($pointer, str_repeat('A', 1024), 1024); fclose($pointer); - //gaufrette needs the key relative to it's root + //file key needs to be relative to the root of the flysystem filesystem $fileKey = str_replace($this->realDirectory, '', $file); $this->payloads[] = new FlysystemFile(new File($filesystem, $fileKey), $filesystem); @@ -95,7 +95,9 @@ 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(); @@ -114,6 +116,10 @@ class FlysystemOrphanageStorageTest extends OrphanageTest public function checkIfTempnameMatchesAfterCreation() { - return strpos(@tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + $testName = tempnam($this->chunkDirectory, 'uploader'); + $result = strpos($testName, $this->chunkDirectory) === 0; + unlink($testName); + + return $result; } } diff --git a/Uploader/Storage/FlysystemOrphanageStorage.php b/Uploader/Storage/FlysystemOrphanageStorage.php index d9947c3..376deb5 100644 --- a/Uploader/Storage/FlysystemOrphanageStorage.php +++ b/Uploader/Storage/FlysystemOrphanageStorage.php @@ -71,13 +71,19 @@ class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageSto public function getFiles() { - $keys = $this->chunkStorage->getFilesystem()->listFiles($this->getPath()); - $keys = $keys['keys']; + $fileList = $this->chunkStorage + ->getFilesystem() + ->listContents($this->getPath()); $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()); + foreach ($fileList as $fileDetail) { + $key = $fileDetail['path']; + if ($fileDetail['type'] == 'file') { + $files[$key] = new FlysystemFile( + new File($this->chunkStorage->getFilesystem(), $key), + $this->chunkStorage->getFilesystem() + ); + } } return $files;
0
a017c39ef337176ee3b187b0463649d0aba9148e
1up-lab/OneupUploaderBundle
Wrapper for container method has
commit a017c39ef337176ee3b187b0463649d0aba9148e Author: Jonathan Schmid <[email protected]> Date: Mon Jun 1 14:38:58 2015 +0100 Wrapper for container method has diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 6903db7..9352b4e 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -17,6 +17,11 @@ class OrphanageManager $this->config = $config; } + public function has($key) + { + return $this->container->has(sprintf('oneup_uploader.orphanage.%s', $key)); + } + public function get($key) { return $this->container->get(sprintf('oneup_uploader.orphanage.%s', $key));
0
4e173b4f3863b5aca6f5d021fbc538c6bc5b5e69
1up-lab/OneupUploaderBundle
Added a test to assure you can pass values through the event listeners via the request object.
commit 4e173b4f3863b5aca6f5d021fbc538c6bc5b5e69 Author: Jim Schmid <[email protected]> Date: Fri Jun 21 23:29:29 2013 +0200 Added a test to assure you can pass values through the event listeners via the request object. diff --git a/Tests/Controller/AbstractUploadTest.php b/Tests/Controller/AbstractUploadTest.php index 1024613..6dfc7e4 100644 --- a/Tests/Controller/AbstractUploadTest.php +++ b/Tests/Controller/AbstractUploadTest.php @@ -54,6 +54,10 @@ abstract class AbstractUploadTest extends AbstractControllerTest $preValidation -= 2; $file = $event->getFile(); + $request = $event->getRequest(); + + // add a new key to the attribute list + $request->attributes->set('grumpy', 'cat'); $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $file); }); @@ -63,9 +67,11 @@ abstract class AbstractUploadTest extends AbstractControllerTest $preValidation *= -1; $file = $event->getFile(); + $request = $event->getRequest(); $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $file); $me->assertEquals(128, $file->getSize()); + $me->assertEquals('cat', $request->get('grumpy')); }); $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile()));
0
94e6ecaf329c99169cebeb0d71acbc2a145ec439
1up-lab/OneupUploaderBundle
Added the possibility to add your own custom frontend class.
commit 94e6ecaf329c99169cebeb0d71acbc2a145ec439 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 16:23:58 2013 +0200 Added the possibility to add your own custom frontend class. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index e33d623..da81832 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,9 +35,16 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload', 'custom')) ->defaultValue('fineuploader') ->end() + ->arrayNode('custom_frontend') + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('name')->defaultNull()->end() + ->scalarNode('class')->defaultNull()->end() + ->end() + ->end() ->arrayNode('storage') ->addDefaultsIfNotSet() ->children() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index a9747a1..e8a53dd 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -104,18 +104,31 @@ class OneupUploaderExtension extends Extension } } - $controllerName = sprintf('oneup_uploader.controller.%s', $key); - $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $mapping['frontend']); + if($mapping['frontent'] != '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['class']); + $controllerType = $customFrontend['name']; + + if(empty($controllerName) || empty($controllerType)) + throw new ServiceNotFoundException('Empty controller class. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); + } // create controllers based on mapping $container ->register($controllerName, $controllerType) - + ->addArgument(new Reference('service_container')) ->addArgument($storageService) ->addArgument($mapping) ->addArgument($key) - + ->addTag('oneup_uploader.routable', array('type' => $key)) ->setScope('request') ; diff --git a/Resources/doc/custom_uploader.md b/Resources/doc/custom_uploader.md new file mode 100644 index 0000000..43dbd6f --- /dev/null +++ b/Resources/doc/custom_uploader.md @@ -0,0 +1,6 @@ +Support a custom Uploader +========================= + +If you have written your own Uploader or you want to use an implementation that is currently not supported by the OneupUploaderBundle follow these steps to integrate it to your Symfony2 application. + +## \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 2a49f75..db17308 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -112,6 +112,7 @@ some more advanced features. * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) * [Testing this bundle](testing.md) +* [Support a custom uploader](custom_uploader.md) * [Configuration Reference](configuration_reference.md) ## FAQ
0
6e22a38c661c71c86ecc6061902bb07be6679f2f
1up-lab/OneupUploaderBundle
Introducing mappings in configuration.
commit 6e22a38c661c71c86ecc6061902bb07be6679f2f Author: Jim Schmid <[email protected]> Date: Mon Mar 11 15:49:21 2013 +0100 Introducing mappings in configuration. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 902be76..0c09a89 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -20,6 +20,18 @@ class Configuration implements ConfigurationInterface ->scalarNode('directory')->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->end() + ->end() + ->arrayNode('mappings') + ->useAttributeAsKey('id') + ->isRequired() + ->requiresAtLeastOneElement() + ->prototype('array') + ->children() + ->scalarNode('namer')->defaultNull()->end() + ->scalarNode('storage')->isRequired()->end() + ->end() + ->end() + ->end() ->end() ;
0
0a5c5d1453b1517da06bb335a3ae2eb8b4c60584
1up-lab/OneupUploaderBundle
Merge pull request #57 from 1up-lab/release-1.0 Release 1.0
commit 0a5c5d1453b1517da06bb335a3ae2eb8b4c60584 (from 706cb283b790498efc22f67c4cd3deb31237b245) Merge: 706cb28 8e21e81 Author: Jim Schmid <[email protected]> Date: Wed Oct 23 06:56:17 2013 -0700 Merge pull request #57 from 1up-lab/release-1.0 Release 1.0 diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 764db5d..dc9dd29 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,6 +1,13 @@ tools: php_code_sniffer: true php_cs_fixer: true - php_mess_detector: true + php_mess_detector: + config: + code_size_rules: + too_many_fields: false + too_many_methods: false + + design_rules: + coupling_between_objects: false php_analyzer: true sensiolabs_security_checker: true \ No newline at end of file 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..62f9df1 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -48,19 +48,22 @@ 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 (null !== $chunk) { + $this->dispatchChunkEvents($chunk, $response, $request, $last); + } if ($chunkManager->getLoadDistribution()) { $chunks = $chunkManager->getChunks($uuid); $assembled = $chunkManager->assembleChunks($chunks, true, $last); + + if (null === $chunk) { + $this->dispatchChunkEvents($assembled, $response, $request, $last); + } } // if all chunks collected and stored, proceed @@ -73,9 +76,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 30b0519..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,10 +168,10 @@ abstract class AbstractController } } - protected function validate(UploadedFile $file) + protected function validate(FileInterface $file) { $dispatcher = $this->container->get('event_dispatcher'); - $event = new ValidationEvent($file, $this->config, $this->type, $this->container->get('request')); + $event = new ValidationEvent($file, $this->container->get('request'), $this->config, $this->type); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); } diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index f10f776..64e1b88 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -61,7 +61,7 @@ class BlueimpController extends AbstractChunkedController $attachmentName = rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $request->headers->get('content-disposition'))); // split the header string to the appropriate parts - list($tmp, $startByte, $endByte, $totalBytes) = preg_split('/[^0-9]+/', $headerRange); + list(, $startByte, $endByte, $totalBytes) = preg_split('/[^0-9]+/', $headerRange); // getting information about chunks // note: We don't have a chance to get the last $total @@ -73,7 +73,6 @@ class BlueimpController extends AbstractChunkedController $size = ($endByte + 1 - $startByte); $last = ($endByte + 1) == $totalBytes; $index = $last ? \PHP_INT_MAX : floor($startByte / $size); - $total = ceil($totalBytes / $size); // it is possible, that two clients send a file with the // exact same filename, therefore we have to add the session diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 17d6ba9..b7b6e94 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -18,7 +18,7 @@ class DropzoneController extends AbstractController foreach ($files as $file) { try { - $uploaded = $this->handleUpload($file, $response, $request); + $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); } diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index 8901b2e..e36979e 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -18,7 +18,7 @@ class FancyUploadController extends AbstractController foreach ($files as $file) { try { - $uploaded = $this->handleUpload($file, $response, $request); + $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); } diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index 8b6cce5..a33ee43 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -17,9 +17,6 @@ class MooUploadController extends AbstractChunkedController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new MooUploadResponse(); $headers = $request->headers; diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index a98f7e8..8b8fcf3 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -18,7 +18,7 @@ class UploadifyController extends AbstractController foreach ($files as $file) { try { - $uploaded = $this->handleUpload($file, $response, $request); + $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); } diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index 8638ad6..05d3bcb 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -18,7 +18,7 @@ class YUI3Controller extends AbstractController foreach ($files as $file) { try { - $uploaded = $this->handleUpload($file, $response, $request); + $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index e18268a..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() @@ -38,7 +51,6 @@ class Configuration implements ConfigurationInterface ->children() ->enumNode('frontend') ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload', 'dropzone', 'custom')) - ->defaultValue('fineuploader') ->end() ->arrayNode('custom_frontend') ->addDefaultsIfNotSet() @@ -57,15 +69,10 @@ 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() - ->arrayNode('allowed_extensions') - ->prototype('scalar')->end() - ->end() - ->arrayNode('disallowed_extensions') - ->prototype('scalar')->end() - ->end() ->arrayNode('allowed_mimetypes') ->prototype('scalar')->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index fae9056..f6720a6 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['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 0fa90b0..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, array $config, $type, Request $request = null) + public function __construct(FileInterface $file, Request $request, array $config, $type) { $this->file = $file; $this->config = $config; diff --git a/EventListener/AllowedExtensionValidationListener.php b/EventListener/AllowedExtensionValidationListener.php deleted file mode 100644 index 68c26e8..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 = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); - - if (count($config['allowed_extensions']) > 0 && !in_array($extension, $config['allowed_extensions'])) { - throw new ValidationException('error.whitelist'); - } - } -} 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/DisallowedExtensionValidationListener.php b/EventListener/DisallowedExtensionValidationListener.php deleted file mode 100644 index 9cdac58..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 = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); - - if (count($config['disallowed_extensions']) > 0 && in_array($extension, $config['disallowed_extensions'])) { - throw new ValidationException('error.blacklist'); - } - } -} 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/README.md b/README.md index a8b708b..0abe5c1 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- +* 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). * Event dispatching [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/a408548b241f47af3539b2137c1817a21a51fde9) in Version **0.9.5**. The dispatching is now handled in the `upload*` functions. So if you have created your own implementation, be sure to remove the call to the `dispatchEvents` function, otherwise it will be called twice. Furthermore no `POST_UPLOAD` event will be fired anymore after uploading a chunk. You can get more information on this topic in the [documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_logic.md#using-chunked-uploads). 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/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/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 b75fee4..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,9 +32,8 @@ oneup_uploader: type: filesystem filesystem: ~ 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/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/frontend_blueimp.md b/Resources/doc/frontend_blueimp.md index f6935c2..db30fdf 100644 --- a/Resources/doc/frontend_blueimp.md +++ b/Resources/doc/frontend_blueimp.md @@ -41,4 +41,14 @@ security: main: pattern: ^/ anonymous: true -``` \ No newline at end of file +``` + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md index 0be52b3..66fc318 100644 --- a/Resources/doc/frontend_dropzone.md +++ b/Resources/doc/frontend_dropzone.md @@ -21,4 +21,14 @@ oneup_uploader: frontend: dropzone ``` -Be sure to check out the [official manual](http://www.dropzonejs.com/) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](http://www.dropzonejs.com/) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_fancyupload.md b/Resources/doc/frontend_fancyupload.md index 02bef21..09896f0 100644 --- a/Resources/doc/frontend_fancyupload.md +++ b/Resources/doc/frontend_fancyupload.md @@ -28,13 +28,13 @@ window.addEvent('domready', function() debug: true, target: 'demo-browse' }); - + $('demo-browse').addEvent('click', function() { swiffy.browse(); return false; }); - + $('demo-select-images').addEvent('change', function() { var filter = null; @@ -71,7 +71,7 @@ window.addEvent('domready', function() <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> | @@ -106,3 +106,13 @@ oneup_uploader: ``` Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md index b024857..cd8a019 100644 --- a/Resources/doc/frontend_fineuploader.md +++ b/Resources/doc/frontend_fineuploader.md @@ -32,6 +32,14 @@ oneup_uploader: 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. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_mooupload.md b/Resources/doc/frontend_mooupload.md index 5c31868..6a1db2c 100644 --- a/Resources/doc/frontend_mooupload.md +++ b/Resources/doc/frontend_mooupload.md @@ -32,4 +32,14 @@ oneup_uploader: frontend: mooupload ``` -Be sure to check out the [official manual](https://github.com/juanparati/MooUpload) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](https://github.com/juanparati/MooUpload) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md index 34c1dc5..deb1ce0 100644 --- a/Resources/doc/frontend_plupload.md +++ b/Resources/doc/frontend_plupload.md @@ -47,4 +47,14 @@ security: main: pattern: ^/ anonymous: true -``` \ No newline at end of file +``` + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_uploadify.md b/Resources/doc/frontend_uploadify.md index 072f22c..ec7bcc9 100644 --- a/Resources/doc/frontend_uploadify.md +++ b/Resources/doc/frontend_uploadify.md @@ -16,7 +16,7 @@ $(document).ready(function() swf: "{{ asset('bundles/acmedemo/js/uploadify.swf') }}", uploader: "{{ oneup_uploader_endpoint('gallery') }}" }); - + }); </script> @@ -34,4 +34,14 @@ oneup_uploader: 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 +Be sure to check out the [official manual](http://www.uploadify.com/documentation/) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) 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 64fba4e..0fd9169 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": "0.9.*@dev" + "oneup/uploader-bundle": "1.0.*@dev" } } ``` @@ -71,7 +71,8 @@ This bundle was designed to just work out of the box. The only thing you have to oneup_uploader: mappings: - gallery: ~ + gallery: + frontend: blueimp # or any uploader you use in the frontend ``` To enable the dynamic routes, add the following to your routing configuration file. @@ -128,6 +129,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/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/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index 8909345..c584b7f 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -18,7 +18,7 @@ abstract class AbstractControllerTest extends WebTestCase $this->helper = $this->container->get('oneup_uploader.templating.uploader_helper'); $this->createdFiles = array(); - $routes = $this->container->get('router')->getRouteCollection()->all(); + $this->container->get('router')->getRouteCollection()->all(); } abstract protected function getConfigKey(); diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 01b0a6d..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; @@ -56,11 +34,11 @@ 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; }); - $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 4bbfa1c..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 @@ -23,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; @@ -52,29 +31,15 @@ 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; }); - $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 @@ -131,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( 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 d0787d0..e0026cc 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -2,33 +2,36 @@ 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; -use Symfony\Component\Filesystem\Filesystem; 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.'); @@ -38,14 +41,12 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte public function uploadFiles() { - $filesystem = new Filesystem(); - try { $files = $this->getFiles(); $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 ed7931e..ce62631 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -2,10 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpFoundation\File\File; - -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; +use Oneup\UploaderBundle\Uploader\File\FileInterface; class FilesystemStorage implements StorageInterface { @@ -16,10 +13,8 @@ class FilesystemStorage implements StorageInterface $this->directory = $directory; } - public function upload(File $file, $name, $path = null) + public function upload(FileInterface $file, $name, $path = null) { - $filesystem = new Filesystem(); - $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 2fbd349..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); - $written = $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 0a5c5d1453b1517da06bb335a3ae2eb8b4c60584 (from 8e21e8100a4dba50a1f2175e822d9e77e73cb918) Merge: 706cb28 8e21e81 Author: Jim Schmid <[email protected]> Date: Wed Oct 23 06:56:17 2013 -0700 Merge pull request #57 from 1up-lab/release-1.0 Release 1.0 diff --git a/Resources/doc/index.md b/Resources/doc/index.md index bf97ce0..0fd9169 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -85,6 +85,10 @@ oneup_uploader: type: uploader ``` +The default directory that is used to upload files to is `web/uploads/{mapping_name}`. + +> 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. + ### 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
4f9c299f45028d9b1f27cd529b1713b8b2465d6d
1up-lab/OneupUploaderBundle
Removed the deletable-feature.
commit 4f9c299f45028d9b1f27cd529b1713b8b2465d6d Author: Jim Schmid <[email protected]> Date: Wed Mar 27 17:48:54 2013 +0100 Removed the deletable-feature. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 4e14207..a90043b 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -46,7 +46,6 @@ class Configuration implements ConfigurationInterface ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->scalarNode('directory_prefix')->defaultNull()->end() ->booleanNode('use_orphanage')->defaultFalse()->end() - ->booleanNode('deletable')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() ->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 3a0d2f2..91e4520 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -71,8 +71,6 @@ class OneupUploaderExtension extends Extension // inject the actual gaufrette filesystem ->addArgument(new Reference($storage)) - - ->addArgument(new Reference('oneup_uploader.deletable_manager')) ; self::$storageServices[] = $name; diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index fad0080..63abc4e 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -4,7 +4,6 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <parameters> - <parameter key="oneup_uploader.deletable.manager.class">Oneup\UploaderBundle\Uploader\Deletable\DeletableManager</parameter> <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> @@ -30,11 +29,6 @@ <!-- namer --> <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" /> - <!-- deletable --> - <service id="oneup_uploader.deletable_manager" class="%oneup_uploader.deletable.manager.class%"> - <argument type="service" id="session" /> - </service> - <!-- routing --> <service id="oneup_uploader.routing.loader" class="%oneup_uploader.routing.loader.class%"> <tag name="routing.loader" /> @@ -47,12 +41,6 @@ <tag name="kernel.event_subscriber" /> </service> - <service id="oneup_uploader.listener.deletable" class="%oneup_uploader.listener.deletable.class%"> - <argument type="service" id="oneup_uploader.deletable_manager" /> - - <tag name="kernel.event_subscriber" /> - </service> - </services> </container> \ No newline at end of file diff --git a/Uploader/Deletable/DeletableManager.php b/Uploader/Deletable/DeletableManager.php deleted file mode 100644 index 69ba85c..0000000 --- a/Uploader/Deletable/DeletableManager.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Deletable; - -use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; -use Symfony\Component\HttpFoundation\Session\SessionInterface; - -use Oneup\UploaderBundle\Uploader\Deletable\DeletableManagerInterface; - -class DeletableManager implements DeletableManagerInterface -{ - protected $session; - - public function __construct(SessionInterface $session) - { - $this->session = $session; - } - - public function addFile($type, $uuid, $name) - { - $session = $this->session; - $key = sprintf('oneup_uploader.deletable.%s', $type); - - // get bag - $arr = $session->get($key, array()); - - $arr[$uuid] = $name; - - // and reattach it to session - $session->set($key, $arr); - - return true; - } - - public function getFile($type, $uuid) - { - $session = $this->session; - $key = sprintf('oneup_uploader.deletable.%s', $type); - - // get bag - $arr = $session->get($key, array()); - - if(!array_key_exists($uuid, $arr)) - throw new \InvalidArgumentException(sprintf('No file with the uuid "%s" found', $uuid)); - - return $arr[$uuid]; - } - - public function removeFile($type, $uuid) - { - $session = $this->session; - $key = sprintf('oneup_uploader.deletable.%s', $type); - - // get bag - $arr = $session->get($key, array()); - - if(!array_key_exists($uuid, $arr)) - throw new \InvalidArgumentException(sprintf('No file with the uuid "%s" found', $uuid)); - - unset($arr[$uuid]); - - $session->set($key, $arr); - - return true; - } -} \ No newline at end of file diff --git a/Uploader/Deletable/DeletableManagerInterface.php b/Uploader/Deletable/DeletableManagerInterface.php deleted file mode 100644 index 02afdf1..0000000 --- a/Uploader/Deletable/DeletableManagerInterface.php +++ /dev/null @@ -1,7 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Deletable; - -interface DeletableManagerInterface -{ -} \ No newline at end of file
0
79faf20be3cb7555d55f403c45975b079091ddff
1up-lab/OneupUploaderBundle
Allow versions >=2.0 of paragonie/random_compat
commit 79faf20be3cb7555d55f403c45975b079091ddff Author: Jérôme Parmentier <[email protected]> Date: Mon Sep 18 15:08:47 2017 +0200 Allow versions >=2.0 of paragonie/random_compat diff --git a/composer.json b/composer.json index a5cea42..497d403 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "php":">=5.4", "symfony/framework-bundle": "^2.4.0|~3.0", "symfony/finder": "^2.4.0|~3.0", - "paragonie/random_compat": "^1.1" + "paragonie/random_compat": "^1.1|^2.0" }, "require-dev": {
0
44520b0d94cca0e13a42f9a3776b1ad49c572d3d
1up-lab/OneupUploaderBundle
Refactored the whole story so you can choose to use Gaufrette but you are not forced to.
commit 44520b0d94cca0e13a42f9a3776b1ad49c572d3d Author: Jim Schmid <[email protected]> Date: Fri Apr 5 16:57:54 2013 +0200 Refactored the whole story so you can choose to use Gaufrette but you are not forced to. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index a0072cc..50b11cf 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -2,49 +2,41 @@ namespace Oneup\UploaderBundle\Controller; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\JsonResponse; -use Symfony\Component\HttpKernel\Exception\HttpException; -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; use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; class UploaderController implements UploadControllerInterface { - protected $request; - protected $namer; + protected $container; protected $storage; protected $config; - protected $dispatcher; protected $type; - protected $chunkManager; - public function __construct(Request $request, NamerInterface $namer, StorageInterface $storage, EventDispatcherInterface $dispatcher, $type, array $config, ChunkManagerInterface $chunkManager) + public function __construct(ContainerInterface $container, StorageInterface $storage, array $config, $type) { - $this->request = $request; - $this->namer = $namer; + $this->container = $container; $this->storage = $storage; $this->config = $config; - $this->dispatcher = $dispatcher; $this->type = $type; - $this->chunkManager = $chunkManager; } public function upload() { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $response = new UploaderResponse(); - $totalParts = $this->request->get('qqtotalparts', 1); - $files = $this->request->files; + $totalParts = $request->get('qqtotalparts', 1); + $files = $request->files; $chunked = $totalParts > 1; foreach($files as $file) @@ -53,14 +45,14 @@ class UploaderController implements UploadControllerInterface { $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); - $postUploadEvent = new PostUploadEvent($uploaded, $response, $this->request, $this->type, $this->config); - $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); + $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, $this->request, $this->type, $this->config); - $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); + $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); + $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); } } catch(UploadException $e) @@ -79,7 +71,11 @@ class UploaderController implements UploadControllerInterface { $this->validate($file); - $name = $this->namer->name($file, $this->config['directory_prefix']); + // 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; @@ -87,7 +83,8 @@ class UploaderController implements UploadControllerInterface protected function handleChunkedUpload(UploadedFile $file) { - $request = $this->request; + $request = $this->container->get('request'); + $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); $uploaded = null; // getting information about chunks @@ -96,7 +93,7 @@ class UploaderController implements UploadControllerInterface $uuid = $request->get('qquuid'); $orig = $request->get('qqfilename'); - $this->chunkManager->addChunk($uuid, $index, $file, $orig); + $chunkManager->addChunk($uuid, $index, $file, $orig); // if all chunks collected and stored, proceed // with reassembling the parts @@ -104,10 +101,10 @@ class UploaderController implements UploadControllerInterface { // we'll take the first chunk and append the others to it // this way we don't need another file in temporary space for assembling - $chunks = $this->chunkManager->getChunks($uuid); + $chunks = $chunkManager->getChunks($uuid); // assemble parts - $assembled = $this->chunkManager->assembleChunks($chunks); + $assembled = $chunkManager->assembleChunks($chunks); $path = $assembled->getPath(); // create a temporary uploaded file to meet the interface restrictions @@ -117,7 +114,7 @@ class UploaderController implements UploadControllerInterface $this->validate($uploadedFile); $uploaded = $this->handleUpload($uploadedFile); - $this->chunkManager->cleanup($path); + $chunkManager->cleanup($path); } return $uploaded; diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index a19fb50..6fc060c 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -18,17 +18,16 @@ class Configuration implements ConfigurationInterface ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled')->defaultFalse()->end() - ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() + ->scalarNode('directory')->defaultNull()->end() ->end() ->end() ->arrayNode('orphanage') ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled')->defaultFalse()->end() - ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() - ->scalarNode('directory')->defaultValue('orphanage')->end() + ->scalarNode('directory')->defaultNull()->end() ->end() ->end() ->arrayNode('mappings') @@ -37,7 +36,19 @@ class Configuration implements ConfigurationInterface ->requiresAtLeastOneElement() ->prototype('array') ->children() - ->scalarNode('filesystem')->isRequired()->end() + + ->arrayNode('storage') + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('service')->defaultNull()->end() + ->enumNode('type') + ->values(array('filesystem', 'gaufrette')) + ->defaultValue('filesystem') + ->end() + ->scalarNode('filesystem')->defaultNull()->end() + ->scalarNode('directory')->defaultNull()->end() + ->end() + ->end() ->arrayNode('allowed_types') ->prototype('scalar')->end() ->end() @@ -45,7 +56,6 @@ class Configuration implements ConfigurationInterface ->prototype('scalar')->end() ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() - ->scalarNode('directory_prefix')->defaultNull()->end() ->booleanNode('use_orphanage')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 97bb48f..bf67881 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -20,22 +20,15 @@ class OneupUploaderExtension extends Extension $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); - // handling chunk configuration - if(!array_key_exists('directory', $config['chunks'])) - { - $config['chunks']['directory'] = sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')); - } - - if(!array_key_exists('domain', $config['orphanage'])) - { - $tmpArr = explode('.', $config['orphanage']['filesystem']); - $tmpArr = explode('_', end($tmpArr)); - - $domain = reset($tmpArr); - - $config['orphanage']['domain'] = $domain; - } + $config['chunks']['directory'] = !array_key_exists('directory', $config['chunks']) ? + sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')) : + $this->normalizePath($config['chunks']['directory']) + ; + $config['orphanage']['directory'] = !array_key_exists('directory', $config['orphanage']) ? + sprintf('%s/uploader/orphanage', $container->getParameter('kernel.cache_dir')) : + $this->normalizePath($config['orphanage']['directory']) + ; $container->setParameter('oneup_uploader.chunks', $config['chunks']); $container->setParameter('oneup_uploader.orphanage', $config['orphanage']); @@ -43,89 +36,59 @@ class OneupUploaderExtension extends Extension // handle mappings foreach($config['mappings'] as $key => $mapping) { - if(is_null($mapping['directory_prefix'])) + $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); + + // 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'])) { - $mapping['directory_prefix'] = $key; + $storageService = new Reference($mapping['storage']['service']); } + else + { + // no service was given, so we create one + $storageName = sprintf('oneup_uploader.storage.%s', $key); - $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); - - $mapping['storage'] = $this->registerStorageService($container, $mapping['filesystem']); - $this->registerServicesPerMap($container, $key, $mapping, $config); - } - } - - protected function registerStorageService(ContainerBuilder $container, $filesystem) - { - // get base name of gaufrette storage - $name = explode('.', $filesystem); - $name = end($name); - - // if service has already been declared, return - if(in_array($name, $this->storageServices)) - return; - - // create name of new storage service - $service = sprintf('oneup_uploader.storage.%s', $name); + 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, $container->getParameter(sprintf('oneup_uploader.storage.%s.class', $mapping['storage']['type']))) + ->addArgument($mapping['storage']['directory']) + ; + } - $container - ->register($service, $container->getParameter('oneup_uploader.storage.class')) + if($mapping['storage']['type'] == 'gaufrette') + { + $container + ->register($storageName, $container->getParameter(sprintf('oneup_uploader.storage.%s.class', $mapping['storage']['type']))) + ->addArgument($mapping['storage']['filesystem']) + ; + } - // inject the actual gaufrette filesystem - ->addArgument(new Reference($filesystem)) - ; - - $this->storageServices[] = $name; - - return $service; - } - - protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping, $config) - { - if($mapping['use_orphanage']) - { - $orphanage = sprintf('oneup_uploader.orphanage.%s', $type); + $storageService = new Reference($storageName); + } - // this mapping wants to use the orphanage, so create - // a masked filesystem for the controller + // create controllers based on mapping $container - ->register($orphanage, $container->getParameter('oneup_uploader.orphanage.class')) + ->register(sprintf('oneup_uploader.controller.%s', $key), $container->getParameter('oneup_uploader.controller.class')) + + ->addArgument(new Reference('service_container')) + ->addArgument($storageService) + ->addArgument($mapping) + ->addArgument($key) - ->addArgument(new Reference($config['orphanage']['filesystem'])) - ->addArgument(new Reference($mapping['filesystem'])) - ->addArgument(new Reference('session')) - ->addArgument($config['orphanage']) - ->addArgument($type) + ->addTag('oneup_uploader.routable', array('type' => $key)) + ->setScope('request') ; - - // switch storage of mapping to orphanage - $mapping['storage'] = $orphanage; } - - // create controllers based on mapping - $container - ->register(sprintf('oneup_uploader.controller.%s', $type), $container->getParameter('oneup_uploader.controller.class')) - - ->addArgument(new Reference('request')) - - // add the correct namer as argument - ->addArgument(new Reference($mapping['namer'])) - - // add the correspoding storage service as argument - ->addArgument(new Reference($mapping['storage'])) - - // we need the EventDispatcher for post upload events - ->addArgument(new Reference('event_dispatcher')) - - // after all, add the type and config as argument - ->addArgument($type) - ->addArgument($mapping) - - ->addArgument(new Reference('oneup_uploader.chunk_manager')) - - ->addTag('oneup_uploader.routable', array('type' => $type)) - ->setScope('request') - ; } protected function getMaxUploadSize($input) @@ -152,4 +115,9 @@ class OneupUploaderExtension extends Extension return $input; } + + protected function normalizePath($input) + { + return rtrim($input, '/'); + } } \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index e5bfa70..e8f6be2 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -9,12 +9,16 @@ <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.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> </parameters> <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/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php new file mode 100644 index 0000000..1058a0d --- /dev/null +++ b/Uploader/Storage/FilesystemStorage.php @@ -0,0 +1,49 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\File; + +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; + +class FilesystemStorage implements StorageInterface +{ + protected $directory; + + public function __construct($directory) + { + $this->directory = $directory; + } + + public function upload(File $file, $name = null, $path = null) + { + $filesystem = new Filesystem(); + + $name = is_null($name) ? $file->getRelativePathname() : $name; + $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); + $path = sprintf('%s/%s', $this->directory, $path); + + // now that we have the correct path, compute the correct name + // and target directory + $targetName = basename($path); + $targetDir = dirname($path); + + $file->move($targetDir, $targetName); + + return $file; + } + + public function remove($path) + { + $filesystem = new Filesystem(); + + if($filesystem->exists($path)) + { + $filesystem->remove($path); + return true; + } + + return false; + } +} \ No newline at end of file diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 7f3978e..76633fb 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -46,4 +46,18 @@ class GaufretteStorage implements StorageInterface return $this->filesystem->get($path); } + + public function remove($path) + { + try + { + $this->filesystem->delete($path); + } + catch(\RuntimeException $e) + { + return false; + } + + return true; + } } \ No newline at end of file diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 3684604..96c807c 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -7,4 +7,5 @@ use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { public function upload(File $file, $name = null, $path = null); + public function remove($path); } \ No newline at end of file
0
4b7e0aab49b5cfe268d47f760ead43a5b71fe251
1up-lab/OneupUploaderBundle
Added Next Steps section to frontend documentations.
commit 4b7e0aab49b5cfe268d47f760ead43a5b71fe251 Author: Jim Schmid <[email protected]> Date: Tue Oct 8 22:46:59 2013 +0200 Added Next Steps section to frontend documentations. diff --git a/Resources/doc/frontend_blueimp.md b/Resources/doc/frontend_blueimp.md index f6935c2..db30fdf 100644 --- a/Resources/doc/frontend_blueimp.md +++ b/Resources/doc/frontend_blueimp.md @@ -41,4 +41,14 @@ security: main: pattern: ^/ anonymous: true -``` \ No newline at end of file +``` + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md index 0be52b3..66fc318 100644 --- a/Resources/doc/frontend_dropzone.md +++ b/Resources/doc/frontend_dropzone.md @@ -21,4 +21,14 @@ oneup_uploader: frontend: dropzone ``` -Be sure to check out the [official manual](http://www.dropzonejs.com/) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](http://www.dropzonejs.com/) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_fancyupload.md b/Resources/doc/frontend_fancyupload.md index 02bef21..09896f0 100644 --- a/Resources/doc/frontend_fancyupload.md +++ b/Resources/doc/frontend_fancyupload.md @@ -28,13 +28,13 @@ window.addEvent('domready', function() debug: true, target: 'demo-browse' }); - + $('demo-browse').addEvent('click', function() { swiffy.browse(); return false; }); - + $('demo-select-images').addEvent('change', function() { var filter = null; @@ -71,7 +71,7 @@ window.addEvent('domready', function() <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> | @@ -106,3 +106,13 @@ oneup_uploader: ``` Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md index 50ea10d..cd8a019 100644 --- a/Resources/doc/frontend_fineuploader.md +++ b/Resources/doc/frontend_fineuploader.md @@ -33,3 +33,13 @@ oneup_uploader: ``` Be sure to check out the [official manual](https://github.com/Widen/fine-uploader/blob/master/readme.md) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_mooupload.md b/Resources/doc/frontend_mooupload.md index 5c31868..6a1db2c 100644 --- a/Resources/doc/frontend_mooupload.md +++ b/Resources/doc/frontend_mooupload.md @@ -32,4 +32,14 @@ oneup_uploader: frontend: mooupload ``` -Be sure to check out the [official manual](https://github.com/juanparati/MooUpload) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](https://github.com/juanparati/MooUpload) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md index 34c1dc5..deb1ce0 100644 --- a/Resources/doc/frontend_plupload.md +++ b/Resources/doc/frontend_plupload.md @@ -47,4 +47,14 @@ security: main: pattern: ^/ anonymous: true -``` \ No newline at end of file +``` + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/frontend_uploadify.md b/Resources/doc/frontend_uploadify.md index 072f22c..ec7bcc9 100644 --- a/Resources/doc/frontend_uploadify.md +++ b/Resources/doc/frontend_uploadify.md @@ -16,7 +16,7 @@ $(document).ready(function() swf: "{{ asset('bundles/acmedemo/js/uploadify.swf') }}", uploader: "{{ oneup_uploader_endpoint('gallery') }}" }); - + }); </script> @@ -34,4 +34,14 @@ oneup_uploader: 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 +Be sure to check out the [official manual](http://www.uploadify.com/documentation/) for details on the configuration. + +Next steps +---------- + +After this setup, you can move on and implement some of the more advanced features. A full list is available [here](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md#next-steps). + +* [Process uploaded files using custom logic](custom_logic.md) +* [Return custom data to frontend](response.md) +* [Include your own Namer](custom_namer.md) +* [Configuration Reference](configuration_reference.md)
0
2e531ea28b62082920c46c28e1963e95ce17f807
1up-lab/OneupUploaderBundle
Don't use phar archive of phpunit (https://github.com/symfony/symfony/issues/19532#issuecomment-266307266)
commit 2e531ea28b62082920c46c28e1963e95ce17f807 Author: David Greminger <[email protected]> Date: Thu Dec 15 12:04:13 2016 +0100 Don't use phar archive of phpunit (https://github.com/symfony/symfony/issues/19532#issuecomment-266307266) diff --git a/.travis.yml b/.travis.yml index 44b121f..7884714 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,3 +43,5 @@ before_script: - composer selfupdate - composer require symfony/http-kernel:${SYMFONY_VERSION} --prefer-source - composer install --dev --prefer-source + +script: ./vendor/bin/phpunit
0
94d6d30f78c96faa59f3b90fc8994571d89d73b6
1up-lab/OneupUploaderBundle
typo
commit 94d6d30f78c96faa59f3b90fc8994571d89d73b6 Author: mitom <[email protected]> Date: Fri Oct 11 13:18:30 2013 +0200 typo diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index 40f83f9..ec02d6b 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -55,7 +55,7 @@ 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 beaces + // 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 continue;
0
578e870cd10e7ab7a35e23e161fcd93126308305
1up-lab/OneupUploaderBundle
Removed unused namespace.
commit 578e870cd10e7ab7a35e23e161fcd93126308305 Author: Jim Schmid <[email protected]> Date: Fri Apr 5 20:23:52 2013 +0200 Removed unused namespace. diff --git a/Uploader/Storage/OrphanageStorageInterface.php b/Uploader/Storage/OrphanageStorageInterface.php index cfd9acb..35e275f 100644 --- a/Uploader/Storage/OrphanageStorageInterface.php +++ b/Uploader/Storage/OrphanageStorageInterface.php @@ -2,7 +2,6 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\HttpFoundation\File\File; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; interface OrphanageStorageInterface extends StorageInterface
0
4b9eac4d9a49dc5a14d4fd739d8f914af84ee4a6
1up-lab/OneupUploaderBundle
Enables and fixes some skipped Flysystem tests This also updates the FlysystemOrphanStorage component to avoid reliance on the Flysystem filesystem's listFiles method which has been moved out of the core and into a plugin in current releases of Flysystem.
commit 4b9eac4d9a49dc5a14d4fd739d8f914af84ee4a6 Author: snarktooth <[email protected]> Date: Thu May 26 09:42:33 2016 -0500 Enables and fixes some skipped Flysystem tests This also updates the FlysystemOrphanStorage component to avoid reliance on the Flysystem filesystem's listFiles method which has been moved out of the core and into a plugin in current releases of Flysystem. diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index a277d7e..102e954 100644 --- a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -29,15 +29,15 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $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); + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + $adapter = new Adapter($this->realDirectory, true); $filesystem = new FSAdapter($adapter); @@ -61,7 +61,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest fwrite($pointer, str_repeat('A', 1024), 1024); fclose($pointer); - //gaufrette needs the key relative to it's root + //file key needs to be relative to the root of the flysystem filesystem $fileKey = str_replace($this->realDirectory, '', $file); $this->payloads[] = new FlysystemFile(new File($filesystem, $fileKey), $filesystem); @@ -95,7 +95,9 @@ 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(); @@ -114,6 +116,10 @@ class FlysystemOrphanageStorageTest extends OrphanageTest public function checkIfTempnameMatchesAfterCreation() { - return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + $testName = tempnam($this->chunkDirectory, 'uploader'); + $result = strpos($testName, $this->chunkDirectory) === 0; + unlink($testName); + + return $result; } } diff --git a/Uploader/Storage/FlysystemOrphanageStorage.php b/Uploader/Storage/FlysystemOrphanageStorage.php index d9947c3..376deb5 100644 --- a/Uploader/Storage/FlysystemOrphanageStorage.php +++ b/Uploader/Storage/FlysystemOrphanageStorage.php @@ -71,13 +71,19 @@ class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageSto public function getFiles() { - $keys = $this->chunkStorage->getFilesystem()->listFiles($this->getPath()); - $keys = $keys['keys']; + $fileList = $this->chunkStorage + ->getFilesystem() + ->listContents($this->getPath()); $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()); + foreach ($fileList as $fileDetail) { + $key = $fileDetail['path']; + if ($fileDetail['type'] == 'file') { + $files[$key] = new FlysystemFile( + new File($this->chunkStorage->getFilesystem(), $key), + $this->chunkStorage->getFilesystem() + ); + } } return $files;
0
924f1c216d0191393b34a72b886f984f7969a3f0
1up-lab/OneupUploaderBundle
Removed the warmup function in ChunkManager and corresponding Interface.
commit 924f1c216d0191393b34a72b886f984f7969a3f0 Author: Jim Schmid <[email protected]> Date: Fri Apr 5 19:27:01 2013 +0200 Removed the warmup function in ChunkManager and corresponding Interface. diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index b35f5f9..2403fd0 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -16,12 +16,6 @@ class ChunkManager implements ChunkManagerInterface $this->configuration = $configuration; } - public function warmup() - { - $filesystem = new FileSystem(); - $filesystem->mkdir($this->configuration['directory']); - } - public function clear() { $system = new Filesystem(); diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index 7900c61..f0059bb 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -6,7 +6,6 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; interface ChunkManagerInterface { - public function warmup(); public function clear(); public function addChunk($uuid, $index, UploadedFile $chunk, $original); public function assembleChunks(\Traversable $chunks);
0
5e82365a40d187de263c9588693ecf853aa3f32c
1up-lab/OneupUploaderBundle
Added Symfony version 2.4 to testing environments.
commit 5e82365a40d187de263c9588693ecf853aa3f32c Author: Jim Schmid <[email protected]> Date: Wed Dec 4 11:15:38 2013 +0100 Added Symfony version 2.4 to testing environments. diff --git a/.travis.yml b/.travis.yml index fc9e984..3381bd6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,7 @@ php: env: - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* + - SYMFONY_VERSION=2.4.* before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source
0
051829418cbc6a8d22ca00e439762476259d8e38
1up-lab/OneupUploaderBundle
Fix code coverage in Response object test.
commit 051829418cbc6a8d22ca00e439762476259d8e38 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 16:21:50 2013 +0200 Fix code coverage in Response object test. diff --git a/Tests/Uploader/Response/UploaderResponseTest.php b/Tests/Uploader/Response/UploaderResponseTest.php index a232436..37728a0 100644 --- a/Tests/Uploader/Response/UploaderResponseTest.php +++ b/Tests/Uploader/Response/UploaderResponseTest.php @@ -20,10 +20,18 @@ class TestUploaderResponse extends \PHPUnit_Framework_TestCase $cat = 'is grumpy'; $dog = 'has no idea'; + $del = 'nothing here'; $response['cat'] = $cat; $response['dog'] = $dog; + $response['del'] = $del; $response->setSuccess(false); + + // the next three lines are from code coverage + $this->assertTrue(isset($response['cat'])); + $this->assertEquals($response['cat'], $cat); + + unset($response['del']); $assembled = $response->assemble();
0
0d566d029538b907044f43748549871757941abc
1up-lab/OneupUploaderBundle
Custom endpoint routes (#280)
commit 0d566d029538b907044f43748549871757941abc Author: Mark de Haan <[email protected]> Date: Tue Nov 21 16:19:34 2017 +0100 Custom endpoint routes (#280) diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 75d64b4..ef2d38e 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') ->prototype('scalar')->end() ->end() 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/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/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()); + } + } }
0
9f7f3fbe988d3df5e0f6fc68b82b34cf1445a406
1up-lab/OneupUploaderBundle
Expose configuration of this bundle via container parameters. This can be useful to extend file upload/deletion logic, for an example head to #96. Close #96.
commit 9f7f3fbe988d3df5e0f6fc68b82b34cf1445a406 Author: Jim Schmid <[email protected]> Date: Wed Mar 26 12:00:10 2014 +0100 Expose configuration of this bundle via container parameters. This can be useful to extend file upload/deletion logic, for an example head to #96. Close #96. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 480d8ec..34e707d 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -45,8 +45,11 @@ class OneupUploaderExtension extends Extension foreach ($this->config['mappings'] as $key => $mapping) { $controllers[$key] = $this->processMapping($key, $mapping); $maxsize[$key] = $this->getMaxUploadSize($mapping['max_size']); + + $container->setParameter(sprintf('oneup_uploader.config.%s', $key), $mapping); } + $container->setParameter('oneup_uploader.config', $this->config); $container->setParameter('oneup_uploader.controllers', $controllers); $container->setParameter('oneup_uploader.maxsize', $maxsize); }
0
f812b78d203429f133eebb8bf3188cebf6628097
1up-lab/OneupUploaderBundle
Added configure and clean-up sections to chunked_uploads documentation.
commit f812b78d203429f133eebb8bf3188cebf6628097 Author: Jim Schmid <[email protected]> Date: Sun Apr 7 19:45:58 2013 +0200 Added configure and clean-up sections to chunked_uploads documentation. diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index c4b7861..bd1238b 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -1,6 +1,8 @@ Using Chunked Uploads ===================== +## Enable + 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. ```js @@ -21,4 +23,25 @@ $(document).ready(function() The `partSize` property defines the maximum size of a blob, in this case 10MB. -> Be sure to select a partSize that fits your requirement. If it is too small, the speed of the overall upload drops significantly. \ No newline at end of file +> Be sure to select a partSize that fits your requirement. If it is too small, the speed of the overall upload drops significantly. + +## Configure + +You can configure the `ChunkManager` by using the following configuration parameters. + +``` +oneup_uploader: + chunk_manager: + maxage: 86400 + directory: %kernel.cache_dir%/uploader/chunks +``` + +You can choose a custom directory to save the chunks temporarily while uploading by changing the parameter `directory`. + +## Clean up + +The ChunkManager can be forced to clean up old and orphanaged chunks by using the command provided by the OneupUploaderBundle. + + $> php app/console oneup:uploader:clean-chunks + +This parameter will clean all chunk files older than the `maxage` value in your configuration.
0
5ab25698416d07fbf5574f15e567ed6049e0aab2
1up-lab/OneupUploaderBundle
Added package-definition of valums/file-uploader
commit 5ab25698416d07fbf5574f15e567ed6049e0aab2 Author: Jim Schmid <[email protected]> Date: Fri Mar 8 18:27:37 2013 +0100 Added package-definition of valums/file-uploader diff --git a/composer.json b/composer.json index 42ecd5c..2728f5d 100644 --- a/composer.json +++ b/composer.json @@ -10,5 +10,24 @@ "name": "Jim Schmid", "email": "[email protected]" } - ] + ], + + "repositories": { + "file-uploader": { + "type": "package", + "package": { + "name": "valums/file-uploader", + "version": "3.3.0", + "source": { + "url": "git://github.com/valums/file-uploader.git", + "type": "git", + "reference": "origin/master" + } + } + } + }, + + "require": { + "valums/file-uploader": "3.3.*" + } } \ No newline at end of file
0
3b23e61e90e8078b74401578c7a9394613e85a8d
1up-lab/OneupUploaderBundle
Update CI status badge
commit 3b23e61e90e8078b74401578c7a9394613e85a8d Author: David Greminger <[email protected]> Date: Thu May 14 13:38:01 2020 +0200 Update CI status badge diff --git a/README.md b/README.md index c404bb7..8ef49c0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ OneupUploaderBundle =================== +![CI](https://github.com/1up-lab/OneupUploaderBundle/workflows/CI/badge.svg) +[![Total Downloads](https://poser.pugx.org/oneup/uploader-bundle/d/total.png)](https://packagist.org/packages/oneup/uploader-bundle) + 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/) @@ -22,9 +25,6 @@ Features included: * Supports [Session upload progress & cancelation of uploads](http://php.net/manual/en/session.upload-progress.php) as of PHP 5.4 * Fully unit tested -[![Build Status](https://travis-ci.org/1up-lab/OneupUploaderBundle.png?branch=master)](https://travis-ci.org/1up-lab/OneupUploaderBundle) -[![Total Downloads](https://poser.pugx.org/oneup/uploader-bundle/d/total.png)](https://packagist.org/packages/oneup/uploader-bundle) - Documentation -------------
0
c57af49653c22110a065c01296bfdb283c9f045d
1up-lab/OneupUploaderBundle
Added (dis)allowed_mimetypes to the configuration reference in the documentation.
commit c57af49653c22110a065c01296bfdb283c9f045d Author: Jim Schmid <[email protected]> Date: Sun Apr 28 10:58:52 2013 +0200 Added (dis)allowed_mimetypes to the configuration reference in the documentation. diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 51bd42d..bea28a9 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -25,8 +25,10 @@ oneup_uploader: type: filesystem filesystem: ~ directory: ~ - allowed_extensions: [] - disallowed_extensions: [] + allowed_extensions: [] + disallowed_extensions: [] + allowed_mimetypes: [] + disallowed_mimetypes: [] max_size: 9223372036854775807 use_orphanage: false namer: oneup_uploader.namer.uniqid
0
63beecbc814d3047feb9448a7e383703930d01ac
1up-lab/OneupUploaderBundle
Reduced amount of copied code in ValidationTest.
commit 63beecbc814d3047feb9448a7e383703930d01ac Author: Jim Schmid <[email protected]> Date: Sat Apr 6 14:51:54 2013 +0200 Reduced amount of copied code in ValidationTest. diff --git a/Tests/Controller/ControllerValidationTest.php b/Tests/Controller/ControllerValidationTest.php index e33c096..fd4c2d0 100644 --- a/Tests/Controller/ControllerValidationTest.php +++ b/Tests/Controller/ControllerValidationTest.php @@ -17,15 +17,7 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase $config['allowed_extensions'] = array(); $config['disallowed_extensions'] = array(); - // 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); + $this->performConfigTest($config); } public function testMaxSizeValidationPasses() @@ -36,18 +28,7 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase $config['allowed_extensions'] = array(); $config['disallowed_extensions'] = array(); - // 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); + $this->performConfigTest($config); } /** @@ -61,18 +42,7 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase $config['allowed_extensions'] = array('txt', 'pdf'); $config['disallowed_extensions'] = array(); - // 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); + $this->performConfigTest($config); } public function testAllowedExtensionValidationPasses() @@ -83,18 +53,7 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase $config['allowed_extensions'] = array('png', 'jpg', 'jpeg', 'gif'); $config['disallowed_extensions'] = array(); - // 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); + $this->performConfigTest($config); } /** @@ -108,18 +67,7 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase $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); + $this->performConfigTest($config); } public function testDisallowedExtensionValidationPasses() @@ -130,6 +78,11 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase $config['allowed_extensions'] = array(); $config['disallowed_extensions'] = array('exe', 'bat'); + $this->performConfigTest($config); + } + + protected function performConfigTest($config) + { // prepare mock $file = $this->getUploadedFileMock(); $method = $this->getValidationMethod();
0
b4895c170f41a9c4bbf884be73f4be37303eab45
1up-lab/OneupUploaderBundle
Merge pull request #12 from 1up-lab/custom_frontend Added the possibility to add a custom backend through configuration.
commit b4895c170f41a9c4bbf884be73f4be37303eab45 (from da09f881c78b58a869ade9ecfa00b730f02bb9aa) Merge: da09f88 d84b721 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 08:16:27 2013 -0700 Merge pull request #12 from 1up-lab/custom_frontend Added the possibility to add a custom backend through configuration. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index e33d623..da81832 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,9 +35,16 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload', 'custom')) ->defaultValue('fineuploader') ->end() + ->arrayNode('custom_frontend') + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('name')->defaultNull()->end() + ->scalarNode('class')->defaultNull()->end() + ->end() + ->end() ->arrayNode('storage') ->addDefaultsIfNotSet() ->children() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index a9747a1..f643686 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -104,18 +104,31 @@ class OneupUploaderExtension extends Extension } } - $controllerName = sprintf('oneup_uploader.controller.%s', $key); - $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $mapping['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']; + + 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.'); + } // create controllers based on mapping $container ->register($controllerName, $controllerType) - + ->addArgument(new Reference('service_container')) ->addArgument($storageService) ->addArgument($mapping) ->addArgument($key) - + ->addTag('oneup_uploader.routable', array('type' => $key)) ->setScope('request') ; diff --git a/Resources/doc/custom_uploader.md b/Resources/doc/custom_uploader.md new file mode 100644 index 0000000..786e7a6 --- /dev/null +++ b/Resources/doc/custom_uploader.md @@ -0,0 +1,128 @@ +Support a custom Uploader +========================= + +If you have written your own Uploader or you want to use an implementation that is currently not supported by the OneupUploaderBundle follow these steps to integrate it to your Symfony2 application. + +## Configuration + +Configure your custom uploader according to the following example. + +```yml +oneup_uploader: + mappings: + gallery: + frontend: custom + custom_frontend: + class: Acme\DemoBundle\Controller\CustomController + name: MyFancyCustomUploader +``` + +This will automatically create everything you need later. +The next step is to include the logic of your custom Uploader to your provided Controller. For having a consistent interface consider extending one of the following classes: + +* `Oneup\UploaderBundle\Controller\AbstractController`: For any implementation that don't support chunked uploads. +* `Oneup\UploaderBundle\Controller\AbstractChunkedController`: For any implementation that should support chunked uploads. + +## The Controller part + +If you decided to extend the AbstractController, do the following + +```php +namespace Acme\DemoBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; +use Oneup\UploaderBundle\Controller\UploaderController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class CustomUploader extends UploaderController +{ + public function upload() + { + // get some basic stuff together + $request = $this->container->get('request'); + $response = new EmptyResponse(); + + // get file from request (your own logic) + $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 assembled response + return new JsonResponse($response->assemble()); + } +} +``` + +## Implement chunked upload +If you want to additionaly support chunked upload, you have to overwrite the `AbstractChunkedController` and implement the `parseChunkedRequest` method. This method should return an array containing the following values: + +* `$last`: Is this the last chunk of a file (`true`/`false`) +* `$uuid`: A truly unique id which will become the directory name for the `ChunkManager` to use. +* `$index`: Which part (chunk) is it? Its not important that you provide exact numbers, but they must be higher for a subsequent chunk! +* `$orig`: The original filename. + +Take any chunked upload implementation in `Oneup\UploaderBundle\Controller` as an example. + +After that, you manually have to check if you have to do a chunked upload or not. This differs from implementation to implementation, so heres an example of the jQuery File Uploader: + +```php +$chunked = !is_null($request->headers->get('content-range')); +$uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); +``` + +## Using a custom Response class +If your frontend implementation relies on specific data returned, it is highly recommended to create your own `Response` class. Here is an example for FineUploader, I guess you'll get the point: + +```php +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class FineUploaderResponse extends AbstractResponse +{ + protected $success; + protected $error; + + public function __construct() + { + $this->success = true; + $this->error = null; + + 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['success'] = $this->success; + + if($this->success) + unset($data['error']); + + if(!$this->success) + $data['error'] = $this->error; + + return $data; + } + + // ... snip, setters/getters +} + +## Notes + +It is highly recommended to use the internal and inherited methods `handleUpload` and `handleChunkedUpload` as these will mind your configuration file. Nonetheless; it is possible to overwrite the behaviour completely in your Controller class. \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 2a49f75..cb24aa1 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -112,10 +112,15 @@ some more advanced features. * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) * [Testing this bundle](testing.md) +* [Support a custom uploader](custom_uploader.md) * [Configuration Reference](configuration_reference.md) ## FAQ +> I want to use a frontend library you don't yet support + +This is absolutely no problem, just follow the instructions given in the corresponding [documentation file](custom_uploader.md). If you think that others could profit of your code, please consider making a pull request. I'm always happy for any kind of contribution. + > Why didn't you implement the _delete_ feature provided by Fine Uploader? FineUploaders _delete Feature_ is using generated unique names we would have to store in order to track down which file to delete. But both the storage and the deletetion of files are tight-coupled with the logic of your very own implementation. This means we leave the _delete Feature_ open for you to implement. Information on how the route must be crafted can be found on the [official documentation](https://github.com/Widen/fine-uploader/blob/master/docs/options-fineuploaderbasic.md#deletefile-option-properties) and on [the blog](http://blog.fineuploader.com/2013/01/delete-uploaded-file-in-33.html) of Fine Uploader.
0
6c061a2d1843bc30dfa3d925511227e50ddce5cd
1up-lab/OneupUploaderBundle
Update README.md
commit 6c061a2d1843bc30dfa3d925511227e50ddce5cd Author: David Greminger <[email protected]> Date: Fri Mar 27 16:53:01 2020 +0100 Update README.md diff --git a/README.md b/README.md index c95129c..cd057cb 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- +* Version **3.0.0** supports now Symfony 5 (kudos to @steveWinter, @gubler, @patrickbussmann, @ErnadoO and @enumag), see [#373](https://github.com/1up-lab/OneupUploaderBundle/pull/373)! Symfony 3.x support was dropped. * 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).
0
716de1f05cf73024b89eed6f5f23657d626f8383
1up-lab/OneupUploaderBundle
Added poser badge to readme.
commit 716de1f05cf73024b89eed6f5f23657d626f8383 Author: Jim Schmid <[email protected]> Date: Fri Jul 19 15:39:04 2013 +0200 Added poser badge to readme. diff --git a/README.md b/README.md index 3737275..07e647c 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Features included: [![Build Status](https://travis-ci.org/1up-lab/OneupUploaderBundle.png?branch=master)](https://travis-ci.org/1up-lab/OneupUploaderBundle) [![Dependencies Status](https://d2xishtp1ojlk0.cloudfront.net/d/8654803)](http://depending.in/1up-lab/OneupUploaderBundle) +[![Total Downloads](https://poser.pugx.org/oneup/uploader-bundle/d/total.png)](https://packagist.org/packages/symfony/symfony) Documentation -------------
0
4440594d67f4317b0caefc8dfa5af88345578a8d
1up-lab/OneupUploaderBundle
Added some entries to the next step section
commit 4440594d67f4317b0caefc8dfa5af88345578a8d Author: Jim Schmid <[email protected]> Date: Sun Apr 7 13:18:13 2013 +0200 Added some entries to the next step section diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 47145c2..85994bd 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -102,4 +102,9 @@ 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. +* Enable chunked uploads +* Using the Orphanage +* Use Gaufrette as storage layer +* Include your own Namer +* Testing this bundle * [Configuration Reference](configuration_reference.md) \ No newline at end of file
0
0d9e6a8141fe6e9ca94d7560fe33086a34d7ddb4
1up-lab/OneupUploaderBundle
Enable framework.annotations in tests (#410)
commit 0d9e6a8141fe6e9ca94d7560fe33086a34d7ddb4 Author: David Greminger <[email protected]> Date: Tue Aug 3 12:27:49 2021 +0200 Enable framework.annotations in tests (#410) diff --git a/composer.json b/composer.json index 63f1a46..ef6d10f 100644 --- a/composer.json +++ b/composer.json @@ -46,13 +46,14 @@ }, "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", - "doctrine/common": "^2.12", + "doctrine/common": "^2.12 || ^3.0", + "doctrine/doctrine-bundle": "^2.4", "friendsofphp/php-cs-fixer": "^2.16", "knplabs/gaufrette": "^0.9", "oneup/flysystem-bundle": "^1.2 || ^2.0 || ^3.0", "phpstan/phpstan": "^0.12.10", "phpunit/phpunit": "^8.5", - "sensio/framework-extra-bundle": "^5.0", + "sensio/framework-extra-bundle": "^5.0 || ^6.0", "symfony/browser-kit": "^4.4 || ^5.0", "symfony/phpunit-bridge": "^5.0", "symfony/security-bundle": "^4.4 || ^5.0", diff --git a/tests/App/config/config.yml b/tests/App/config/config.yml index ac75528..ac4945d 100644 --- a/tests/App/config/config.yml +++ b/tests/App/config/config.yml @@ -1,4 +1,6 @@ framework: + annotations: + enabled: true translator: { fallback: en } secret: secret router:
0
93c28aa71d31ddf16dbb42aaa2c44082afbd44c6
1up-lab/OneupUploaderBundle
Fixed conflict.
commit 93c28aa71d31ddf16dbb42aaa2c44082afbd44c6 (from b8811ba876cb7634cc4238fb1463890f4a6de26c) Merge: b8811ba 2a92723 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 18:20:45 2013 +0200 Fixed conflict. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 5a3bb15..a8fe6f9 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -86,7 +86,7 @@ oneup_uploader: ### Step 4: Prepare your frontend -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. To get a url for a specific mapping you can use the `oneup_uploader.templating.uploader_helper` service as follows: +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: ```php $helper = $this->container->get('oneup_uploader.templating.uploader_helper'); @@ -134,4 +134,4 @@ FineUploaders _delete Feature_ is using generated unique names we would have to > Why didn't you implement the _delete_ feature provided by another library? -See the answer to the previous question and replace _FineUploader_ by the library you have chosen. \ No newline at end of file +See the answer to the previous question and replace _FineUploader_ by the library you have chosen. commit 93c28aa71d31ddf16dbb42aaa2c44082afbd44c6 (from 2a927237ab0f617eb40e63d4c701f5da35c2fbb7) Merge: b8811ba 2a92723 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 18:20:45 2013 +0200 Fixed conflict. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index da81832..89051cd 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -28,6 +28,7 @@ class Configuration implements ConfigurationInterface ->scalarNode('directory')->defaultNull()->end() ->end() ->end() + ->scalarNode('twig')->defaultTrue()->end() ->arrayNode('mappings') ->useAttributeAsKey('id') ->isRequired() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index f643686..bf0121f 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -21,6 +21,12 @@ class OneupUploaderExtension extends Extension $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); + $loader->load('templating.xml'); + + if($config['twig']) + { + $loader->load('twig.xml'); + } $config['chunks']['directory'] = is_null($config['chunks']['directory']) ? sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')) : diff --git a/Resources/config/templating.xml b/Resources/config/templating.xml new file mode 100644 index 0000000..4593804 --- /dev/null +++ b/Resources/config/templating.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"> + + <services> + + <service id="oneup_uploader.templating.uploader_helper" class="Oneup\UploaderBundle\Templating\Helper\UploaderHelper"> + <argument type="service" id="router" /> + <tag name="templating.helper" alias="oneup_uploader" /> + </service> + + </services> + +</container> \ No newline at end of file diff --git a/Resources/config/twig.xml b/Resources/config/twig.xml new file mode 100644 index 0000000..95c0c2d --- /dev/null +++ b/Resources/config/twig.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"> + + <services> + + <service id="oneup_uploader.twig.extension.uploader" class="Oneup\UploaderBundle\Twig\Extension\UploaderExtension" public="true"> + <argument type="service" id="oneup_uploader.templating.uploader_helper" /> + <tag name="twig.extension" /> + </service> + + </services> + +</container> \ No newline at end of file diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index af3b780..d649a14 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -9,7 +9,7 @@ $(document).ready(function() var uploader = new qq.FineUploader({ element: document.getElementById('uploader'), request: { - endpoint: "{{ path('_uploader_gallery') }}" + endpoint: "{{ oneup_uploader_endpoint('gallery') }}" }, chunking: { enabled: true, diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 741e1f2..84af61e 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -48,7 +48,7 @@ FineUploader supports passing custom data through the request as the following e var uploader = new qq.FineUploader({ element: document.getElementById('fine-uploader'), request: { - endpoint: "{{ path('_uploader_gallery') }}", + endpoint: "{{ oneup_uploader_endpoint('gallery') }}", params: { gallery: "{{ gallery.id }}" } diff --git a/Resources/doc/frontend_blueimp.md b/Resources/doc/frontend_blueimp.md index 453dd54..f6935c2 100644 --- a/Resources/doc/frontend_blueimp.md +++ b/Resources/doc/frontend_blueimp.md @@ -15,7 +15,7 @@ $(document).ready(function() }); </script> -<input id="fileupload" type="file" name="files[]" data-url="{{ path('_uploader_gallery') }}" multiple /> +<input id="fileupload" type="file" name="files[]" data-url="{{ oneup_uploader_endpoint('gallery') }}" multiple /> ``` Configure the OneupUploaderBundle to use the correct controller: diff --git a/Resources/doc/frontend_fancyupload.md b/Resources/doc/frontend_fancyupload.md index da918c2..02bef21 100644 --- a/Resources/doc/frontend_fancyupload.md +++ b/Resources/doc/frontend_fancyupload.md @@ -59,7 +59,7 @@ window.addEvent('domready', function() </script> -<form action="{{ path('_uploader_gallery') }}" method="post" enctype="multipart/form-data" id="form-demo"> +<form action="{{ oneup_uploader_endpoint('gallery') }}" method="post" enctype="multipart/form-data" id="form-demo"> <fieldset id="demo-fallback"> <legend>File Upload</legend> <p> diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md index dbe3d67..91a0f77 100644 --- a/Resources/doc/frontend_fineuploader.md +++ b/Resources/doc/frontend_fineuploader.md @@ -12,7 +12,7 @@ $(document).ready(function() var uploader = new qq.FineUploader({ element: $('#uploader'), request: { - endpoint: "{{ path('_uploader_gallery') }}" + endpoint: "{{ oneup_uploader_endpoint('gallery') }}" } }); }); diff --git a/Resources/doc/frontend_mooupload.md b/Resources/doc/frontend_mooupload.md index 5dfa4cb..5c31868 100644 --- a/Resources/doc/frontend_mooupload.md +++ b/Resources/doc/frontend_mooupload.md @@ -12,7 +12,7 @@ window.addEvent("domready", function() { var myUpload = new MooUpload("fileupload", { - action: "{{ path('_uploader_gallery') }}", + action: "{{ oneup_uploader_endpoint('gallery') }}", method: "auto" }); }); diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md index b27657c..34c1dc5 100644 --- a/Resources/doc/frontend_plupload.md +++ b/Resources/doc/frontend_plupload.md @@ -16,7 +16,7 @@ $(document).ready(function() $("#fileupload").plupload( { runtimes: "html5", - url: "{{ path('_uploader_gallery') }}" + url: "{{ oneup_uploader_endpoint('gallery') }}" }); }); </script> diff --git a/Resources/doc/frontend_uploadify.md b/Resources/doc/frontend_uploadify.md index e84c7d5..072f22c 100644 --- a/Resources/doc/frontend_uploadify.md +++ b/Resources/doc/frontend_uploadify.md @@ -14,7 +14,7 @@ $(document).ready(function() $('#fileupload').uploadify( { swf: "{{ asset('bundles/acmedemo/js/uploadify.swf') }}", - uploader: "{{ path('_uploader_gallery') }}" + uploader: "{{ oneup_uploader_endpoint('gallery') }}" }); }); diff --git a/Resources/doc/frontend_yui3.md b/Resources/doc/frontend_yui3.md index 5b267fd..88e9e4c 100644 --- a/Resources/doc/frontend_yui3.md +++ b/Resources/doc/frontend_yui3.md @@ -11,7 +11,7 @@ YUI().use('uploader', function (Y) { var uploader = new Y.Uploader( { multipleFiles: true, - uploadURL: "{{ path('_uploader_gallery') }}" + uploadURL: "{{ oneup_uploader_endpoint('gallery') }}" }).render("#fileupload"); uploader.on('fileselect', function() diff --git a/Resources/doc/index.md b/Resources/doc/index.md index b85b8fd..a8fe6f9 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -86,9 +86,16 @@ oneup_uploader: ### 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. It has the following form: +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: - _uploader_{mapping_key} +```php +$helper = $this->container->get('oneup_uploader.templating.uploader_helper'); +$endpoint = $helper->endpoint('gallery'); +``` + +or in a Twig template you can use the `oneup_uploader_endpoint` function: + + {{ oneup_uploader_endpoint('gallery') }} 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: diff --git a/Templating/Helper/UploaderHelper.php b/Templating/Helper/UploaderHelper.php new file mode 100644 index 0000000..b5c376a --- /dev/null +++ b/Templating/Helper/UploaderHelper.php @@ -0,0 +1,26 @@ +<?php + +namespace Oneup\UploaderBundle\Templating\Helper; + +use Symfony\Component\Routing\RouterInterface; +use Symfony\Component\Templating\Helper\Helper; + +class UploaderHelper extends Helper +{ + protected $router; + + public function __construct(RouterInterface $router) + { + $this->router = $router; + } + + public function getName() + { + return 'oneup_uploader'; + } + + public function endpoint($key) + { + return $this->router->generate(sprintf('_uploader_%s', $key)); + } +} \ No newline at end of file diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php new file mode 100644 index 0000000..910a0f9 --- /dev/null +++ b/Twig/Extension/UploaderExtension.php @@ -0,0 +1,30 @@ +<?php + +namespace Oneup\UploaderBundle\Twig\Extension; + +use Oneup\UploaderBundle\Templating\Helper\UploaderHelper; + +class UploaderExtension extends \Twig_Extension +{ + protected $helper; + + public function __construct(UploaderHelper $helper) + { + $this->helper = $helper; + } + + public function getName() + { + return 'oneup_uploader'; + } + + public function getFunctions() + { + return array('oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint')); + } + + public function endpoint($key) + { + return $this->helper->endpoint($key); + } +} \ No newline at end of file
0
e5feb4d95c542375df39663b090eb202b0ecebc3
1up-lab/OneupUploaderBundle
Added gaufrette to require-dev, as we need it to test the bundle.
commit e5feb4d95c542375df39663b090eb202b0ecebc3 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 22:13:42 2013 +0200 Added gaufrette to require-dev, as we need it to test the bundle. diff --git a/composer.json b/composer.json index 1327e02..35989f8 100644 --- a/composer.json +++ b/composer.json @@ -17,6 +17,10 @@ "symfony/finder": ">=2.0.16,<2.3-dev" }, + "require-dev": { + "knplabs/knp-gaufrette-bundle": "0.1.*" + }, + "suggest": { "knplabs/knp-gaufrette-bundle": "0.1.*" },
0
2a6daa73e00801ecc0e065d2dee52592147208ee
1up-lab/OneupUploaderBundle
Merge pull request #256 from mediafigaro/patch-1 Add example to personalize upload path
commit 2a6daa73e00801ecc0e065d2dee52592147208ee (from eb609baf31012cf67fb776953bdee2bd484e58eb) Merge: eb609ba 39d0c0a Author: David Greminger <[email protected]> Date: Thu Jun 23 12:22:19 2016 +0200 Merge pull request #256 from mediafigaro/patch-1 Add example to personalize upload path diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 0c18f92..7b6601e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -92,6 +92,18 @@ 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: + 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
14f0f3b618d9e73f99636a5695927caf8214a2d4
1up-lab/OneupUploaderBundle
Add mixin \ArrayAccess annotation to ResponseInterface (#392)
commit 14f0f3b618d9e73f99636a5695927caf8214a2d4 Author: Nathan Dench <[email protected]> Date: Mon Dec 7 18:49:15 2020 +1100 Add mixin \ArrayAccess annotation to ResponseInterface (#392) diff --git a/src/Uploader/Response/ResponseInterface.php b/src/Uploader/Response/ResponseInterface.php index 160bbcf..1b3ce9b 100644 --- a/src/Uploader/Response/ResponseInterface.php +++ b/src/Uploader/Response/ResponseInterface.php @@ -4,6 +4,9 @@ declare(strict_types=1); namespace Oneup\UploaderBundle\Uploader\Response; +/** + * @mixin \ArrayAccess + */ interface ResponseInterface { /**
0
a1eb4ed8aa3cf3f2b4e3b6b760706a880ac35d52
1up-lab/OneupUploaderBundle
ErrorHandlerInterface - tune method param types ErrorHandlerInterface::addException($response, $exception) Replace $response type ResponseInterface with AbstractResponse because ErrorHandlerInterface descendants newer uses the ResponseInterface::assembly() method but uses AbstractResponse::addToOffsetMethod so ResponseInterface parameter does not guarantees a typesafe method call, but AbstractResponse does! Replace UploadException $exception with \Exception which allow add any required exception in controllers
commit a1eb4ed8aa3cf3f2b4e3b6b760706a880ac35d52 Author: Veniamin Albaev <[email protected]> Date: Tue Jul 16 16:44:34 2013 +0400 ErrorHandlerInterface - tune method param types ErrorHandlerInterface::addException($response, $exception) Replace $response type ResponseInterface with AbstractResponse because ErrorHandlerInterface descendants newer uses the ResponseInterface::assembly() method but uses AbstractResponse::addToOffsetMethod so ResponseInterface parameter does not guarantees a typesafe method call, but AbstractResponse does! Replace UploadException $exception with \Exception which allow add any required exception in controllers diff --git a/Uploader/ErrorHandler/BlueimpErrorHandler.php b/Uploader/ErrorHandler/BlueimpErrorHandler.php index 600d933..c8839b7 100644 --- a/Uploader/ErrorHandler/BlueimpErrorHandler.php +++ b/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -2,15 +2,15 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Exception; use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; -use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; class BlueimpErrorHandler implements ErrorHandlerInterface { - public function addException(ResponseInterface $response, UploadException $exception) + public function addException(AbstractResponse $response, Exception $exception) { - $message = $exception->getErrorMessage(); + $message = $exception->getMessage(); $response->addToOffset(array('error' => $message), array('files')); } } diff --git a/Uploader/ErrorHandler/ErrorHandlerInterface.php b/Uploader/ErrorHandler/ErrorHandlerInterface.php index a2614a1..4d59aa3 100644 --- a/Uploader/ErrorHandler/ErrorHandlerInterface.php +++ b/Uploader/ErrorHandler/ErrorHandlerInterface.php @@ -2,10 +2,10 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; +use Exception; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; interface ErrorHandlerInterface { - public function addException(ResponseInterface $response, UploadException $exception); + public function addException(AbstractResponse $response, Exception $exception); } diff --git a/Uploader/ErrorHandler/NoopErrorHandler.php b/Uploader/ErrorHandler/NoopErrorHandler.php index e131408..c2d7121 100644 --- a/Uploader/ErrorHandler/NoopErrorHandler.php +++ b/Uploader/ErrorHandler/NoopErrorHandler.php @@ -2,13 +2,13 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Exception; use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; -use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; class NoopErrorHandler implements ErrorHandlerInterface { - public function addException(ResponseInterface $response, UploadException $exception) + public function addException(AbstractResponse $response, Exception $exception) { // noop }
0
b1a1162587f74c21412ffff1242a5154b922cbdb
1up-lab/OneupUploaderBundle
Removed 2, because of also 3.
commit b1a1162587f74c21412ffff1242a5154b922cbdb Author: David Greminger <[email protected]> Date: Mon Sep 25 15:18:13 2017 +0200 Removed 2, because of also 3. 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/)
0
b71aa839e83db7a4cd113968f5c448d9691f788e
1up-lab/OneupUploaderBundle
Added OrphanageStorage test.
commit b71aa839e83db7a4cd113968f5c448d9691f788e Author: Jim Schmid <[email protected]> Date: Sat Apr 6 21:05:10 2013 +0200 Added OrphanageStorage test. diff --git a/Tests/Uploader/Storage/OrphanageStorageTest.php b/Tests/Uploader/Storage/OrphanageStorageTest.php new file mode 100644 index 0000000..043f7a2 --- /dev/null +++ b/Tests/Uploader/Storage/OrphanageStorageTest.php @@ -0,0 +1,82 @@ +<?php + +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 +{ + protected $tempDirectory; + protected $realDirectory; + protected $orphanage; + protected $storage; + protected $payloads; + protected $numberOfPayloads; + + public function setUp() + { + $this->numberOfPayloads = 5; + $this->tempDirectory = sys_get_temp_dir() . '/storage'; + $this->realDirectory = sys_get_temp_dir() . '/orphanage'; + $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->tempDirectory); + + // 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 ++) + { + $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 tearDown() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->tempDirectory); + $filesystem->remove($this->realDirectory); + } +} \ No newline at end of file
0
ddc0c39b3d3f05b1e3fc47a91ae75b90fbf0ff36
1up-lab/OneupUploaderBundle
Fix deprecation notice in EventDispatcher in Symfony 4.3+ (#362)
commit ddc0c39b3d3f05b1e3fc47a91ae75b90fbf0ff36 Author: Igor Tarasov <[email protected]> Date: Tue Sep 3 23:06:08 2019 +0300 Fix deprecation notice in EventDispatcher in Symfony 4.3+ (#362) diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 73450a9..d36e384 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -90,11 +90,8 @@ abstract class AbstractChunkedController extends AbstractController */ protected function dispatchChunkEvents($uploaded, ResponseInterface $response, Request $request, $isLast) { - $dispatcher = $this->container->get('event_dispatcher'); - // dispatch post upload event (both the specific and the general) $postUploadEvent = new PostChunkUploadEvent($uploaded, $response, $request, $isLast, $this->type, $this->config); - $dispatcher->dispatch(UploadEvents::POST_CHUNK_UPLOAD, $postUploadEvent); - $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_CHUNK_UPLOAD, $this->type), $postUploadEvent); + $this->dispatchEvent($postUploadEvent, UploadEvents::POST_CHUNK_UPLOAD); } } diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 1a12021..fc6bd8c 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -17,6 +17,7 @@ use Symfony\Component\HttpFoundation\FileBag; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Kernel; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; abstract class AbstractController { @@ -136,12 +137,9 @@ abstract class AbstractController */ protected function dispatchPreUploadEvent(FileInterface $uploaded, ResponseInterface $response, Request $request) { - $dispatcher = $this->container->get('event_dispatcher'); - // dispatch pre upload event (both the specific and the general) $preUploadEvent = new PreUploadEvent($uploaded, $response, $request, $this->type, $this->config); - $dispatcher->dispatch(UploadEvents::PRE_UPLOAD, $preUploadEvent); - $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::PRE_UPLOAD, $this->type), $preUploadEvent); + $this->dispatchEvent($preUploadEvent, UploadEvents::PRE_UPLOAD); } /** @@ -154,28 +152,22 @@ abstract class AbstractController */ protected function dispatchPostEvents($uploaded, ResponseInterface $response, Request $request) { - $dispatcher = $this->container->get('event_dispatcher'); - // dispatch post upload event (both the specific and the general) $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config); - $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); - $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_UPLOAD, $this->type), $postUploadEvent); + $this->dispatchEvent($postUploadEvent, UploadEvents::POST_UPLOAD); if (!$this->config['use_orphanage']) { // dispatch post persist event (both the specific and the general) $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); - $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); - $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_PERSIST, $this->type), $postPersistEvent); + $this->dispatchEvent($postPersistEvent, UploadEvents::POST_PERSIST); } } protected function validate(FileInterface $file, Request $request, ResponseInterface $response = null) { - $dispatcher = $this->container->get('event_dispatcher'); $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); + $this->dispatchEvent($event, UploadEvents::VALIDATION); } /** @@ -215,4 +207,23 @@ abstract class AbstractController return $this->container->get('request_stack')->getMasterRequest(); } + + /** + * Event dispatch proxy that avoids using deprecated interfaces. + * + * @param $event + * @param string $eventName + */ + protected function dispatchEvent($event, string $eventName) + { + $dispatcher = $this->container->get('event_dispatcher'); + + if ($dispatcher instanceof EventDispatcherInterface) { + $dispatcher->dispatch($event, $eventName); + $dispatcher->dispatch($event, sprintf('%s.%s', $eventName, $this->type)); + } else { + $dispatcher->dispatch($eventName, $event); + $dispatcher->dispatch(sprintf('%s.%s', $eventName, $this->type), $event); + } + } }
0
b1a9b687fdb7d6be85d9eea0d5a0080561b6690f
1up-lab/OneupUploaderBundle
Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle
commit b1a9b687fdb7d6be85d9eea0d5a0080561b6690f (from 8c355cf1a9dfc5ec103193eb022c1c6b90ca9677) Merge: 8c355cf 5879360 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 09:09:13 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle 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) diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 18a156e..65cf43c 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -1,7 +1,7 @@ Configuration Reference ======================= -All available configuration options are listed below with their default values. +All available configuration options along with their default values are listed below. ``` yaml oneup_uploader: @@ -25,4 +25,4 @@ oneup_uploader: max_size: 9223372036854775807 use_orphanage: false namer: oneup_uploader.namer.uniqid -``` \ No newline at end of file +``` diff --git a/Resources/doc/namer.md b/Resources/doc/custom_namer.md similarity index 97% rename from Resources/doc/namer.md rename to Resources/doc/custom_namer.md index 65fe084..4aaeabc 100644 --- a/Resources/doc/namer.md +++ b/Resources/doc/custom_namer.md @@ -43,4 +43,4 @@ oneup_uploader: namer: acme_demo.custom_namer ``` -Every file uploaded through the `Controller` of this mapping will be named with your custom namer. \ No newline at end of file +Every file uploaded through the `Controller` of this mapping will be named with your custom namer. diff --git a/Resources/doc/gaufrette_storage.md b/Resources/doc/gaufrette_storage.md index 74ec3fe..14e1788 100644 --- a/Resources/doc/gaufrette_storage.md +++ b/Resources/doc/gaufrette_storage.md @@ -45,6 +45,8 @@ public function registerBundles() The following is a sample configuration for the KnpGaufretteBundle. It will create a filystem service called `gaufrette.gallery_filesystem` which can be used in the OneupUploaderBundle. For a complete list of features refer to the [official documentation](https://github.com/KnpLabs/KnpGaufretteBundle). ```yml +# app/config/config.yml + knp_gaufrette: adapters: gallery: @@ -55,8 +57,6 @@ knp_gaufrette: filesystems: gallery: adapter: gallery - - stream_wrapper: ~ ``` ## Configure your mappings @@ -64,6 +64,8 @@ knp_gaufrette: Activate Gaufrette by switching the `type` property to `gaufrette` and pass the Gaufrette filesystem configured in the previous step. ```yml +# app/config/config.yml + oneup_uploader: mappings: gallery: commit b1a9b687fdb7d6be85d9eea0d5a0080561b6690f (from 587936016b1d4b906b7d27401cb3ba4c1aa9d609) Merge: 8c355cf 5879360 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 09:09:13 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 29a4395..c4c35a8 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -117,5 +117,5 @@ some more advanced features. * Using the Orphanage * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) -* Testing this bundle +* [Testing this bundle](testing.md) * [Configuration Reference](configuration_reference.md) diff --git a/Resources/doc/testing.md b/Resources/doc/testing.md new file mode 100644 index 0000000..8db8597 --- /dev/null +++ b/Resources/doc/testing.md @@ -0,0 +1,62 @@ +Testing the Bundle +================== + +## Install the Environment + +In order to run the UnitTests of this bundle, clone it first + + $> git clone git://github.com/1up-lab/OneupUploaderBundle.git + +After the cloning process, install all vendors by running the corresponding composer command. + + $> php composer.phar udpate --dev + +## Run UnitTests +You can run the unit tests by simply performing the follwowing command. + + $> phpunit + +## Testing Code Coverage +PHPUnit comes bundles with a handy feature to test the code coverage of a project. I recommend using the following configuration to enable the creation of code coverage reports in the `log` directory in the root of this bundle. This directory is gitignored by default. + +Copy the `phpunit.xml.dist` to `phpunit.xml` and use this configuration. + +```xml +<?xml version="1.0" encoding="UTF-8"?> + +<phpunit bootstrap="./Tests/bootstrap.php" colors="true"> + + <testsuites> + <testsuite name="OneupUploaderBundle test suite"> + <directory suffix="Test.php">./Tests</directory> + </testsuite> + </testsuites> + + <filter> + <whitelist> + <directory>./</directory> + <exclude> + <directory>./Command</directory> + <directory>./DependencyInjection</directory> + <directory>./Event</directory> + <directory>./Resources</directory> + <directory>./Tests</directory> + <directory>./vendor</directory> + <directory>./OneupUploaderBundle.php</directory> + </exclude> + </whitelist> + </filter> + + <logging> + <log type="coverage-html" target="./log/codeCoverage" charset="UTF-8" yui="true" highlight="true" + lowUpperBound="50" highLowerBound="80"/> + </logging> + +</phpunit> +``` + +The directories `Command`, `DependencyInjection` and `Event` are excluded from the code coverage report, as these directories contain files that don't necessarily need to be unit tested. + +Run the test suite and generate reports by running: + + $> phpunit \ No newline at end of file
0
bd423e4d41a820e0e3f3d06fc7e7f5e3a5257027
1up-lab/OneupUploaderBundle
Added function add() to OrphanageInterface.
commit bd423e4d41a820e0e3f3d06fc7e7f5e3a5257027 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 12:06:37 2013 +0100 Added function add() to OrphanageInterface. diff --git a/Uploader/Orphanage/OrphanageInterface.php b/Uploader/Orphanage/OrphanageInterface.php index d585a9a..07b5558 100644 --- a/Uploader/Orphanage/OrphanageInterface.php +++ b/Uploader/Orphanage/OrphanageInterface.php @@ -2,7 +2,9 @@ namespace Oneup\UploaderBundle\Uploader\Orphanage; +use Symfony\Component\HttpFoundation\File\File; + interface OrphanageInterface { - + public function add(File $file, $name); }
0
2f1fa5513ce57e1316316d8710182dc5394c5121
1up-lab/OneupUploaderBundle
AbstractChunkedController: phpdoc fix Fix param naming as of PHPStorm inpections warnings and add param types to phpdoc
commit 2f1fa5513ce57e1316316d8710182dc5394c5121 Author: Veniamin Albaev <[email protected]> Date: Tue Jul 16 12:19:53 2013 +0400 AbstractChunkedController: phpdoc fix Fix param naming as of PHPStorm inpections warnings and add param types to phpdoc diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index f053703..d7d00ba 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -25,8 +25,8 @@ abstract class AbstractChunkedController extends AbstractController * chunk. Must be higher that in the previous request. * - orig: The original file name. * - * @param request The request object - * @return array + * @param Request $request - The request object + * @return array */ abstract protected function parseChunkedRequest(Request $request); @@ -38,9 +38,9 @@ abstract class AbstractChunkedController extends AbstractController * parseChunkedRequest has set true for the "last" key of the * returned array to reassemble the uploaded chunks. * - * @param file The uploaded chunk. - * @param response A response object. - * @param request The request object. + * @param UploadedFile $file - The uploaded chunk. + * @param ResponseInterface $response - A response object. + * @param Request $request - The request object. */ protected function handleChunkedUpload(UploadedFile $file, ResponseInterface $response, Request $request) { @@ -57,7 +57,7 @@ abstract class AbstractChunkedController extends AbstractController $chunk = $chunkManager->addChunk($uuid, $index, $file, $orig); $this->dispatchChunkEvents($chunk, $response, $request, $last); - + if ($chunkManager->getLoadDistribution()) { $chunks = $chunkManager->getChunks($uuid); $assembled = $chunkManager->assembleChunks($chunks); @@ -70,7 +70,7 @@ abstract class AbstractChunkedController extends AbstractController $chunks = $chunkManager->getChunks($uuid); $assembled = $chunkManager->assembleChunks($chunks); } - + $path = $assembled->getPath(); // create a temporary uploaded file to meet the interface restrictions @@ -87,10 +87,10 @@ abstract class AbstractChunkedController extends AbstractController /** * This function is a helper function which dispatches post chunk upload event. * - * @param uploaded The uploaded chunk. - * @param response A response object. - * @param request The request object. - * @param isLast True if this is the last chunk, false otherwise. + * @param mixed $uploaded - The uploaded chunk. + * @param ResponseInterface $response - A response object. + * @param Request $request - The request object. + * @param bool $isLast - True if this is the last chunk, false otherwise. */ protected function dispatchChunkEvents($uploaded, ResponseInterface $response, Request $request, $isLast) {
0
14eda43b90ac9d08485daf98017c67f1827920fd
1up-lab/OneupUploaderBundle
Merge pull request #276 from glukose/patch-1 Added example code for response return
commit 14eda43b90ac9d08485daf98017c67f1827920fd (from d9413ed05dda52578ba5e63af60f1be8965f482c) Merge: d9413ed f679316 Author: David Greminger <[email protected]> Date: Thu Feb 2 13:11:22 2017 +0100 Merge pull request #276 from glukose/patch-1 Added example code for response return diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 1aa1cfd..3471492 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -31,6 +31,11 @@ class UploadListener public function onUpload(PostPersistEvent $event) { //... + + //if everything went fine + $response = $event->getResponse(); + $response['success'] = true; + return $response; } } ```
0
4f98131894c0aca5daa067e382469204c406de76
1up-lab/OneupUploaderBundle
Update index.md Addresses #60.
commit 4f98131894c0aca5daa067e382469204c406de76 Author: Jim Schmid <[email protected]> Date: Tue Oct 15 21:36:12 2013 +0200 Update index.md Addresses #60. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index fe69b15..64fba4e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -84,6 +84,10 @@ oneup_uploader: type: uploader ``` +The default directory that is used to upload files to is `web/uploads/{mapping_name}`. + +> 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. + ### 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