commit_id
string
repo
string
commit_message
string
diff
string
label
int64
9943e13681bdb6620bc7f1f7b95804e399b5cdff
1up-lab/OneupUploaderBundle
Move files to orphanage if mentioned in config.
commit 9943e13681bdb6620bc7f1f7b95804e399b5cdff Author: Jim Schmid <[email protected]> Date: Wed Mar 13 12:04:11 2013 +0100 Move files to orphanage if mentioned in config. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index afa18b3..7c2b423 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -6,6 +6,7 @@ use Symfony\Component\HttpFoundation\JsonResponse; use Oneup\UploaderBundle\UploadEvents; use Oneup\UploaderBundle\Event\PostPersistEvent; +use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Controller\UploadControllerInterface; class UploaderController implements UploadControllerInterface @@ -38,16 +39,20 @@ class UploaderController implements UploadControllerInterface { $name = $this->namer->name($file, $this->config['directory_prefix']); + $postUploadEvent = new PostUploadEvent($file, $this->request, array( + 'use_orphanage' => $this->config['use_orphanage'], + 'file_name' => $name, + )); + $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); + if(!$this->config['use_orphanage']) { $uploaded = $this->storage->upload($file, $name); // dispatch post upload event - $event = new PostPersistEvent($uploaded, $this->request); - $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $event); + $postPersistEvent = new PostPersistEvent($uploaded, $this->request); + $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); } - - } return new JsonResponse(array('success' => true)); diff --git a/Event/PostUploadEvent.php b/Event/PostUploadEvent.php index 76d4e70..709095b 100644 --- a/Event/PostUploadEvent.php +++ b/Event/PostUploadEvent.php @@ -12,10 +12,11 @@ class PostUploadEvent extends Event protected $file; protected $request; - public function __construct(File $file, Request $request) + public function __construct(File $file, Request $request, array $options = array()) { $this->file = $file; $this->request = $request; + $this->options = $options; } public function getFile() @@ -27,4 +28,9 @@ class PostUploadEvent extends Event { return $this->request; } + + public function getOptions() + { + return $this->options; + } } \ No newline at end of file diff --git a/EventListener/OrphanageListener.php b/EventListener/OrphanageListener.php index ec40914..a7d909f 100644 --- a/EventListener/OrphanageListener.php +++ b/EventListener/OrphanageListener.php @@ -18,18 +18,22 @@ class OrphanageListener implements EventSubscriberInterface $this->orphanage = $orphanage; } - public function addToSession(PostUploadEvent $event) + public function add(PostUploadEvent $event) { + $options = $event->getOptions(); $request = $event->getRequest(); $file = $event->getFile(); - $this->orphanage->addFile($file); + if(!$options['use_orphanage']) + return; + + $this->orphanage->addFile($file, $options['file_name']); } public static function getSubscribedEvents() { return array( - UploadEvents::POST_UPLOAD => 'addToSession', + UploadEvents::POST_UPLOAD => 'add', ); } } \ No newline at end of file diff --git a/UploadEvents.php b/UploadEvents.php index 4e90860..6a9967b 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -5,5 +5,5 @@ namespace Oneup\UploaderBundle; final class UploadEvents { const POST_PERSIST = 'oneup.uploader.post.persist'; - const POST_UPLOAD = 'oneup.uploader.post.upload': + const POST_UPLOAD = 'oneup.uploader.post.upload'; } \ No newline at end of file diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php index 8731c09..c7a5506 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Orphanage/Orphanage.php @@ -18,14 +18,17 @@ class Orphanage implements OrphanageInterface $this->config = $config; } - public function addFile(File $file) + public function addFile(File $file, $name) { + if(!$this->session->isStarted()) + throw new \RuntimeException('You need a running session in order to run the Orphanage.'); + // prefix directory with session id - $id = $session->getId(); - $path = sprintf('%s/%s/%s', $this->config['directory'], $id, $file->getRealPath()); + $id = $this->session->getId(); + $path = sprintf('%s/%s', $this->config['directory'], $id); - var_dump($path); - die(); + // move file to orphanage + return $file->move($path, $name); } public function removeFile(File $file)
0
2397664cf1ce3fd87fde6628713193eb32f2de3f
1up-lab/OneupUploaderBundle
Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle
commit 2397664cf1ce3fd87fde6628713193eb32f2de3f (from c0d9cce3e2c5b2ecb6253d719d8471049451ae2b) Merge: c0d9cce b1973d8 Author: Jim Schmid <[email protected]> Date: Tue Aug 13 13:07:45 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Resources/doc/testing.md b/Resources/doc/testing.md index 91a37a6..4fd96cb 100644 --- a/Resources/doc/testing.md +++ b/Resources/doc/testing.md @@ -34,6 +34,9 @@ Copy the `phpunit.xml.dist` to `phpunit.xml` and use this configuration. <?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="./Tests/bootstrap.php" colors="true"> + <php> + <server name="KERNEL_DIR" value="Tests/App" /> + </php> <testsuites> <testsuite name="OneupUploaderBundle test suite"> commit 2397664cf1ce3fd87fde6628713193eb32f2de3f (from b1973d8e3dac0f12b6e48ef71cd0843f0ff93fe5) Merge: c0d9cce b1973d8 Author: Jim Schmid <[email protected]> Date: Tue Aug 13 13:07:45 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index 1ba2c15..0991a3e 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -6,9 +6,50 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; interface ChunkManagerInterface { - public function clear(); + /** + * Adds a new Chunk to a given uuid. + * + * @param string $uuid + * @param int $index + * @param UploadedFile $chunk + * @param string $original The file name of the original file + * + * @return File The moved chunk file. + */ public function addChunk($uuid, $index, UploadedFile $chunk, $original); + + /** + * 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. + * + * @return File + */ public function assembleChunks(\IteratorAggregate $chunks, $removeChunk = true, $renameChunk = false); - public function cleanup($path); + + /** + * Get chunks associated with the given uuid. + * + * @param string $uuid + * + * @return Finder A finder instance + */ public function getChunks($uuid); + + /** + * Clean a given path. + * + * @param string $path + * @return bool + */ + public function cleanup($path); + + /** + * Clears the chunk manager directory. Remove all files older than the configured maxage. + * + * @return void + */ + public function clear(); }
0
bbf9ab86d226a8a1dac92f744949835d932f1f38
1up-lab/OneupUploaderBundle
Fix typo in composer constraint (see #306)
commit bbf9ab86d226a8a1dac92f744949835d932f1f38 Author: Nikola Kuzmanović <[email protected]> Date: Thu Dec 14 14:06:09 2017 +0100 Fix typo in composer constraint (see #306) diff --git a/composer.json b/composer.json index 25b7e00..dc5b01b 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "paragonie/random_compat": "^1.1|^2.0", "symfony/asset": "^3.0|^4.0", "symfony/finder": "^3.0|^4.0", - "symfony/framework-bundle": "^3.0|4.0", + "symfony/framework-bundle": "^3.0|^4.0", "symfony/templating": "^3.0|^4.0", "symfony/translation": "^3.0|^4.0", "symfony/yaml": "^3.0|^4.0"
0
e6a0773c36ca172feae24e7117aebf6e4ff22c73
1up-lab/OneupUploaderBundle
Removed unused variables on FancyUploadController.
commit e6a0773c36ca172feae24e7117aebf6e4ff22c73 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:24:17 2013 +0200 Removed unused variables on FancyUploadController. diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index ee69af0..c2e32bd 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -13,9 +13,6 @@ class FancyUploadController extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files;
0
b9aef6ac357e09061a6051a3cca7ffee07f8a473
1up-lab/OneupUploaderBundle
Updated description in composer.json
commit b9aef6ac357e09061a6051a3cca7ffee07f8a473 Author: David Greminger <[email protected]> Date: Fri Mar 27 17:05:15 2020 +0100 Updated description in composer.json diff --git a/composer.json b/composer.json index f53221a..278b963 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "oneup/uploader-bundle", "type": "symfony-bundle", - "description": "Handles multi file uploads in Symfony2. Features included: Chunked upload, Orphans management, Gaufrette support.", + "description": "This Symfony bundle provides a server implementation for handling single and multiple file uploads using either FineUploader, jQuery File Uploader, YUI3 Uploader, Uploadify, FancyUpload, MooUpload, Plupload or Dropzone. Features include chunked uploads, orphanages, Gaufrette and Flysystem support.", "keywords": ["fileupload", "upload", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload", "Plupload", "Dropzone"], "homepage": "https://1up.io", "license": "MIT",
0
9c9a403eba5b8e4fa73a76ab5c33fd63d4297d9b
1up-lab/OneupUploaderBundle
Translate the error message if upload fails.
commit 9c9a403eba5b8e4fa73a76ab5c33fd63d4297d9b Author: Jim Schmid <[email protected]> Date: Sat Apr 6 23:19:22 2013 +0200 Translate the error message if upload fails. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 21cf3d9..f7880cb 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -33,6 +33,7 @@ class UploaderController implements UploadControllerInterface { $request = $this->container->get('request'); $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); $response = new UploaderResponse(); $totalParts = $request->get('qqtotalparts', 1); @@ -58,6 +59,7 @@ class UploaderController implements UploadControllerInterface 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()); diff --git a/Tests/Controller/UploaderControllerTest.php b/Tests/Controller/UploaderControllerTest.php index 967ca51..e9bd236 100644 --- a/Tests/Controller/UploaderControllerTest.php +++ b/Tests/Controller/UploaderControllerTest.php @@ -98,6 +98,9 @@ class UploaderControllerTest extends \PHPUnit_Framework_TestCase if($inp == 'namer') return new UniqidNamer(); + + if($inp == 'translator') + return $this->getTranslatorMock(); } protected function getEventDispatcherMock() @@ -129,6 +132,18 @@ class UploaderControllerTest extends \PHPUnit_Framework_TestCase return $mock; } + protected function getTranslatorMock() + { + $mock = $this->getMock('Symfony\Component\Translation\TranslatorInterface'); + $mock + ->expects($this->any()) + ->method('trans') + ->will($this->returnValue('A translated error.')) + ; + + return $mock; + } + protected function getUploadedFile() { return new UploadedFile($this->tempFile, 'grumpy-cat.jpeg', 'image/jpeg', 1024, null, true);
0
2b371a081148ea71feecf5f9137afbcfe57bef4b
1up-lab/OneupUploaderBundle
Fixes a typo introduced in 3745b3af2e19c7c8be02d6552bd2708b7f86d51d
commit 2b371a081148ea71feecf5f9137afbcfe57bef4b Author: Jim Schmid <[email protected]> Date: Sun Apr 14 13:38:38 2013 +0200 Fixes a typo introduced in 3745b3af2e19c7c8be02d6552bd2708b7f86d51d diff --git a/composer.json b/composer.json index a59d0c0..b312ae5 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "oneup/uploader-bundle", "type": "symfony-bundle", - "description": "Handles multi file uploads in Symonfy2. Features included: Chunked upload, Orphans management, Gaufrette support.", + "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"], "homepage": "http://1up.io", "license": "MIT",
0
da8f5e0dfd8064d215e76eb1a44e6a0738270fdd
1up-lab/OneupUploaderBundle
Merge pull request #19 from eXtreme/patch-1 Fixed wrong event name for persist
commit da8f5e0dfd8064d215e76eb1a44e6a0738270fdd (from fdebca99c4c4b55ce2cfa71f89942b2e5c343cbf) Merge: fdebca9 3b43437 Author: Jim Schmid <[email protected]> Date: Mon Jun 17 08:10:02 2013 -0700 Merge pull request #19 from eXtreme/patch-1 Fixed wrong event name for persist diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 47e07a4..49bce30 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -76,7 +76,7 @@ abstract class AbstractController // 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_UPLOAD, $this->type), $postPersistEvent); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_PERSIST, $this->type), $postPersistEvent); } }
0
207d2f19d89f37ca61831ff1a79e2557aa9464f1
1up-lab/OneupUploaderBundle
Added a documentation topic: How to use Chunked Uploads behind Load Balancers. This is WIP.
commit 207d2f19d89f37ca61831ff1a79e2557aa9464f1 Author: Jim Schmid <[email protected]> Date: Fri Oct 11 19:19:16 2013 +0200 Added a documentation topic: How to use Chunked Uploads behind Load Balancers. This is WIP. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index fe69b15..430fc08 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -124,6 +124,7 @@ some more advanced features. * [Validate your uploads](custom_validator.md) * [General/Generic Events](events.md) * [Enable Session upload progress / upload cancelation](progress.md) +* [Use Chunked Uploads behind Load Balancers](load_balancers.md) * [Configuration Reference](configuration_reference.md) * [Testing this bundle](testing.md) diff --git a/Resources/doc/load_balancers.md b/Resources/doc/load_balancers.md new file mode 100644 index 0000000..0667b94 --- /dev/null +++ b/Resources/doc/load_balancers.md @@ -0,0 +1,6 @@ +Use Chunked Uploads behind Load Balancers +========================================= + +If you want to use Chunked Uploads behind load balancers that is not configured to use sticky sessions you'll eventually end up with a bunch of chunks on every instance and the bundle is not able to reassemble the file on the server. + +You can avoid this problem by using Gaufrette as an abstract filesystem. \ No newline at end of file
0
47613dcec6054ff9923da0665e277b488ff6911e
1up-lab/OneupUploaderBundle
Make ResponseInterface extends \ArrayAccess (#391)
commit 47613dcec6054ff9923da0665e277b488ff6911e Author: Nathan Dench <[email protected]> Date: Wed Jul 20 18:52:44 2022 +1000 Make ResponseInterface extends \ArrayAccess (#391) diff --git a/src/Uploader/Response/ResponseInterface.php b/src/Uploader/Response/ResponseInterface.php index 1b3ce9b..c5c66d1 100644 --- a/src/Uploader/Response/ResponseInterface.php +++ b/src/Uploader/Response/ResponseInterface.php @@ -4,10 +4,7 @@ declare(strict_types=1); namespace Oneup\UploaderBundle\Uploader\Response; -/** - * @mixin \ArrayAccess - */ -interface ResponseInterface +interface ResponseInterface extends \ArrayAccess { /** * Transforms this object to an array of data.
0
9bb4c8c69bd0366d0bd077365bbfc7f394635165
1up-lab/OneupUploaderBundle
Added an Uploadify implementation.
commit 9bb4c8c69bd0366d0bd077365bbfc7f394635165 Author: Jim Schmid <[email protected]> Date: Thu Apr 11 20:04:24 2013 +0200 Added an Uploadify implementation. diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php new file mode 100644 index 0000000..7c94966 --- /dev/null +++ b/Controller/UploadifyController.php @@ -0,0 +1,40 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\Controller\AbstractController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class UploadifyController extends AbstractController +{ + public function upload() + { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new EmptyResponse(); + $files = $request->files; + + foreach($files as $file) + { + try + { + $uploaded = $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + } + + return new JsonResponse($response->assemble()); + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 8848e0d..6e065bb 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp')) + ->values(array('fineuploader', 'blueimp', 'uploadify')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 7083edf..454f024 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -13,6 +13,7 @@ <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> <parameter key="oneup_uploader.controller.fineuploader.class">Oneup\UploaderBundle\Controller\FineUploaderController</parameter> <parameter key="oneup_uploader.controller.blueimp.class">Oneup\UploaderBundle\Controller\BlueimpController</parameter> + <parameter key="oneup_uploader.controller.uploadify.class">Oneup\UploaderBundle\Controller\UploadifyController</parameter> </parameters> <services>
0
6287770f9450be2662739bdc360ff910cdff8126
1up-lab/OneupUploaderBundle
Fix link
commit 6287770f9450be2662739bdc360ff910cdff8126 Author: David Greminger <[email protected]> Date: Thu May 14 13:44:46 2020 +0200 Fix link diff --git a/README.md b/README.md index 8ef49c0..b717f2b 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ OneupUploaderBundle =================== -![CI](https://github.com/1up-lab/OneupUploaderBundle/workflows/CI/badge.svg) +[![CI](https://github.com/1up-lab/OneupUploaderBundle/workflows/CI/badge.svg)](https://github.com/1up-lab/OneupUploaderBundle/actions) [![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).
0
c084d7cc8840f66eb422f5748c1c45a79df46208
1up-lab/OneupUploaderBundle
Added missing hint to include the routing part.
commit c084d7cc8840f66eb422f5748c1c45a79df46208 Author: Jim Schmid <[email protected]> Date: Mon Apr 8 11:40:06 2013 +0300 Added missing hint to include the routing part. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index f609759..df1378e 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -72,6 +72,17 @@ oneup_uploader: gallery: ~ ``` +To enable the dynamic routes, add the following to your routing configuration file. + +```yaml +# app/config/routing.yml + +oneup_uploader: + resource: . + type: uploader + +``` + ### Step 4: Prepare your frontend As this is a server implementation for Fine Uploader, you have to include this library in order to upload files through this bundle. You can find them on the [official page](http://fineuploader.com) of Fine Uploader. Be sure to connect the endpoint property to the dynamic route created from your mapping. It has the following form:
0
4f8c95c89eb33908a266949bde01232e91d25f5e
1up-lab/OneupUploaderBundle
CS Fixes
commit 4f8c95c89eb33908a266949bde01232e91d25f5e Author: David Greminger <[email protected]> Date: Mon Jul 16 12:48:41 2018 +0200 CS Fixes diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index cff222d..73450a9 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -47,7 +47,7 @@ abstract class AbstractChunkedController extends AbstractController $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); // get information about this chunked request - list($last, $uuid, $index, $orig) = $this->parseChunkedRequest($request); + [$last, $uuid, $index, $orig] = $this->parseChunkedRequest($request); $chunk = $chunkManager->addChunk($uuid, $index, $file, $orig); diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 563bb94..434dc27 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -58,7 +58,7 @@ class BlueimpController extends AbstractChunkedController $attachmentName = rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $request->headers->get('content-disposition'))); // split the header string to the appropriate parts - list(, $startByte, $endByte, $totalBytes) = preg_split('/[^0-9]+/', $headerRange); + [, $startByte, $endByte, $totalBytes] = preg_split('/[^0-9]+/', $headerRange); // getting information about chunks // note: We don't have a chance to get the last $total diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index 16d22ac..5de4e19 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -17,7 +17,7 @@ class MooUploadController extends AbstractChunkedController $response = new MooUploadResponse(); $headers = $request->headers; - list($file, $uploadFileName) = $this->getUploadedFile($request); + [$file, $uploadFileName] = $this->getUploadedFile($request); // we have to get access to this object in another method $this->response = $response; diff --git a/DependencyInjection/Compiler/OneUpPass.php b/DependencyInjection/Compiler/ControllerPass.php similarity index 73% rename from DependencyInjection/Compiler/OneUpPass.php rename to DependencyInjection/Compiler/ControllerPass.php index 2fff4b7..347cb4a 100644 --- a/DependencyInjection/Compiler/OneUpPass.php +++ b/DependencyInjection/Compiler/ControllerPass.php @@ -5,21 +5,19 @@ namespace Oneup\UploaderBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; -class OneUpPass implements CompilerPassInterface +class ControllerPass implements CompilerPassInterface { - public function process(ContainerBuilder $container) + public function process(ContainerBuilder $container): void { // Find autowired controllers $autowired_controllers = $container->findTaggedServiceIds('controller.service_arguments'); // Find OneUp controllers $controllers = $container->findTaggedServiceIds('oneup_uploader.controller'); - foreach($controllers as $id => $tags) { - + foreach ($controllers as $id => $tags) { // Get fully qualified name of service $fqdn = $container->getDefinition($id)->getClass(); - if(isset($autowired_controllers[$fqdn])) { - + if (isset($autowired_controllers[$fqdn])) { // Retrieve auto wired controller $autowired_definition = $container->getDefinition($fqdn); @@ -27,17 +25,17 @@ class OneUpPass implements CompilerPassInterface $arguments = $container->getDefinition($id)->getArguments(); // Add arguments to auto wired controller - if(empty($autowired_definition->getArguments())) { - foreach($arguments as $argument) { + if (empty($autowired_definition->getArguments())) { + foreach ($arguments as $argument) { $autowired_definition->addArgument($argument); } } // Remove autowire - if(method_exists($autowired_definition, 'setAutowired')) { + if (method_exists($autowired_definition, 'setAutowired')) { $autowired_definition->setAutowired(false); } } } } -} \ No newline at end of file +} diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 6285220..6ae8f8f 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -61,7 +61,7 @@ class OneupUploaderExtension extends Extension protected function processOrphanageConfig() { - if ($this->config['chunks']['storage']['type'] === 'filesystem') { + if ('filesystem' === $this->config['chunks']['storage']['type']) { $defaultDir = sprintf('%s/uploader/orphanage', $this->container->getParameter('kernel.cache_dir')); } else { $defaultDir = 'orphanage'; @@ -207,7 +207,7 @@ class OneupUploaderExtension extends Extension // root_folder is true, remove the mapping name folder from path $folder = $this->config['mappings'][$key]['root_folder'] ? '' : $key; - $config['directory'] = null === $config['directory'] ? + $config['directory'] = null === $config['directory'] ? \sprintf('%s/uploads/%s', $this->getTargetDir(), $folder) : $this->normalizePath($config['directory']) ; @@ -332,7 +332,7 @@ class OneupUploaderExtension extends Extension return rtrim($input, '/').'/'; } - + protected function getTargetDir() { $projectDir = $this->container->hasParameter('kernel.project_dir') ? diff --git a/OneupUploaderBundle.php b/OneupUploaderBundle.php index 66e21b9..2d3f0c3 100644 --- a/OneupUploaderBundle.php +++ b/OneupUploaderBundle.php @@ -2,15 +2,15 @@ namespace Oneup\UploaderBundle; -use Symfony\Component\HttpKernel\Bundle\Bundle; +use Oneup\UploaderBundle\DependencyInjection\Compiler\ControllerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Oneup\UploaderBundle\DependencyInjection\Compiler\OneUpPass; +use Symfony\Component\HttpKernel\Bundle\Bundle; class OneupUploaderBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); - $container->addCompilerPass(new OneUpPass()); + $container->addCompilerPass(new ControllerPass()); } -} \ No newline at end of file +} diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index d0c5cef..e72f144 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -98,7 +98,7 @@ abstract class AbstractControllerTest extends WebTestCase abstract protected function getConfigKey(); - protected function implTestCallBy($method, $expectedStatusCode = 200, $expectedContentType='application/json') + protected function implTestCallBy($method, $expectedStatusCode = 200, $expectedContentType = 'application/json') { $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); @@ -110,7 +110,7 @@ abstract class AbstractControllerTest extends WebTestCase $client->request($method, $endpoint, [], [], $this->requestHeaders); $response = $client->getResponse(); - $this->assertEquals($expectedStatusCode, $response->getStatusCode()); + $this->assertSame($expectedStatusCode, $response->getStatusCode()); $this->assertContains($expectedContentType, $response->headers->get('Content-Type')); } diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index 7f1bff2..913de52 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -40,9 +40,9 @@ class FlysystemStorage implements StorageInterface if ($file instanceof FilesystemFile) { $stream = fopen($file->getPathname(), 'r+b'); - $this->filesystem->putStream($path, $stream, array( - 'mimetype' => $file->getMimeType() - )); + $this->filesystem->putStream($path, $stream, [ + 'mimetype' => $file->getMimeType(), + ]); if (is_resource($stream)) { fclose($stream);
0
f39398941c735187038a6f4b65ac4fff6fbfa4f4
1up-lab/OneupUploaderBundle
Removed fine-uploader repository from the list of dependencies. You are now forced to include it in your own (prefered) way.
commit f39398941c735187038a6f4b65ac4fff6fbfa4f4 Author: Jim Schmid <[email protected]> Date: Fri Apr 5 19:35:57 2013 +0200 Removed fine-uploader repository from the list of dependencies. You are now forced to include it in your own (prefered) way. diff --git a/composer.json b/composer.json index be9a578..9b70844 100644 --- a/composer.json +++ b/composer.json @@ -12,27 +12,11 @@ } ], - "repositories": { - "fine-uploader": { - "type": "package", - "package": { - "name": "widen/fine-uploader", - "version": "3.3.1", - "source": { - "url": "git://github.com/Widen/fine-uploader.git", - "type": "git", - "reference": "origin/master" - } - } - } - }, - "require": { "symfony/finder": ">=2.0.16,<2.3-dev", "symfony/filesystem": ">=2.0.16,<2.3-dev", "symfony/event-dispatcher": ">=2.0.16,<2.3-dev", - "knplabs/knp-gaufrette-bundle": "0.1.*", - "widen/fine-uploader": "3.3.*" + "knplabs/knp-gaufrette-bundle": "0.1.*" }, "autoload": {
0
69d0819038a736e02bb5cbb420b06e502efc22e8
1up-lab/OneupUploaderBundle
Merge branch 'dropzone-chunk' of git://github.com/tompiard/OneupUploaderBundle into tompiard-dropzone-chunk
commit 69d0819038a736e02bb5cbb420b06e502efc22e8 (from e1e139af3c63d0a19f6f8b06591987fb4ca0d6bb) Merge: e1e139a bf10b7b Author: David Greminger <[email protected]> Date: Tue Nov 21 17:19:30 2017 +0100 Merge branch 'dropzone-chunk' of git://github.com/tompiard/OneupUploaderBundle into tompiard-dropzone-chunk diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index b4fdc99..feab508 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -2,11 +2,12 @@ namespace Oneup\UploaderBundle\Controller; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; - use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\File\Exception\UploadException; -class DropzoneController extends AbstractController +class DropzoneController extends AbstractChunkedController { public function upload() { @@ -14,9 +15,15 @@ class DropzoneController extends AbstractController $response = new EmptyResponse(); $files = $this->getFiles($request->files); $statusCode = 200; + + $chunked = !is_null($request->request->get('dzchunkindex')); + foreach ($files as $file) { try { - $this->handleUpload($file, $response, $request); + $chunked ? + $this->handleChunkedUpload($file, $response, $request) : + $this->handleUpload($file, $response, $request) + ; } catch (UploadException $e) { $statusCode = 500; //Dropzone displays error if HTTP response is 40x or 50x $this->errorHandler->addException($response, $e); @@ -24,10 +31,26 @@ class DropzoneController extends AbstractController $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); $response = $this->createSupportedJsonResponse(array('error'=>$message )); $response->setStatusCode(400); - return $response; + return $response; } } return $this->createSupportedJsonResponse($response->assemble(), $statusCode); } + + protected function parseChunkedRequest(Request $request) + { + $totalChunkCount = $request->get('dztotalchunkcount'); + $index = $request->get('dzchunkindex'); + $last = ($index + 1) === (int) $totalChunkCount; + $uuid = $request->get('dzuuid'); + + /** + * @var UploadedFile $file + */ + $file = $request->files->get('file')->getClientOriginalName(); + $orig = $file; + + return [$last, $uuid, $index, $orig]; + } } commit 69d0819038a736e02bb5cbb420b06e502efc22e8 (from bf10b7b1a6a831cc5eabe4a84b68378482cf9f5e) Merge: e1e139a bf10b7b Author: David Greminger <[email protected]> Date: Tue Nov 21 17:19:30 2017 +0100 Merge branch 'dropzone-chunk' of git://github.com/tompiard/OneupUploaderBundle into tompiard-dropzone-chunk diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 75d3518..fac6246 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -113,7 +113,7 @@ abstract class AbstractController if (!($file instanceof FileInterface)) { $file = new FilesystemFile($file); } - $this->validate($file); + $this->validate($file, $response, $request); $this->dispatchPreUploadEvent($file, $response, $request); @@ -169,10 +169,10 @@ abstract class AbstractController } } - protected function validate(FileInterface $file) + protected function validate(FileInterface $file,ResponseInterface $response, Request $request) { $dispatcher = $this->container->get('event_dispatcher'); - $event = new ValidationEvent($file, $this->getRequest(), $this->config, $this->type); + $event = new ValidationEvent($file, $response, $request, $this->config, $this->type); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::VALIDATION, $this->type), $event); 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/Event/ValidationEvent.php b/Event/ValidationEvent.php index 15e1c18..4240059 100644 --- a/Event/ValidationEvent.php +++ b/Event/ValidationEvent.php @@ -3,6 +3,7 @@ namespace Oneup\UploaderBundle\Event; use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\Request; @@ -12,13 +13,15 @@ class ValidationEvent extends Event protected $config; protected $type; protected $request; + protected $response; - public function __construct(FileInterface $file, Request $request, array $config, $type) + public function __construct(FileInterface $file, ResponseInterface $response, Request $request, array $config, $type) { $this->file = $file; $this->config = $config; $this->type = $type; $this->request = $request; + $this->response = $response; } public function getFile() @@ -40,4 +43,10 @@ class ValidationEvent extends Event { return $this->request; } + + public function getResponse() + { + return $this->response; + } + } diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index 1f51fb2..d6aefe2 100644 --- a/Resources/config/errorhandler.xml +++ b/Resources/config/errorhandler.xml @@ -6,6 +6,7 @@ <parameters> <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter> <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter> + <parameter key="oneup_uploader.error_handler.plupload.class">Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler</parameter> <parameter key="oneup_uploader.error_handler.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter> </parameters> @@ -19,8 +20,8 @@ <service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> - <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.dropzone.class%" public="false" /> + <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.plupload.class%" public="false" /> <service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" /> </services> diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index a7cee8a..5e89c4a 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -35,6 +35,10 @@ oneup_uploader: stream_wrapper: ~ sync_buffer_size: 100K route_prefix: + endpoints: + upload: ~ + progress: ~ + cancel: ~ allowed_mimetypes: [] disallowed_mimetypes: [] error_handler: oneup_uploader.error_handler.noop diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index cd8c070..6dbdc4a 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -30,7 +30,7 @@ class RouteLoader extends Loader $options = $controllerArray[1]; $upload = new Route( - sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), + $options['endpoints']['upload'] ?: sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), array('_controller' => $service . ':upload', '_format' => 'json'), array(), array(), @@ -41,7 +41,7 @@ class RouteLoader extends Loader if ($options['enable_progress'] === true) { $progress = new Route( - sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), + $options['endpoints']['progress'] ?: sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), array('_controller' => $service . ':progress', '_format' => 'json'), array(), array(), @@ -55,7 +55,7 @@ class RouteLoader extends Loader if ($options['enable_cancelation'] === true) { $progress = new Route( - sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), + $options['endpoints']['cancel'] ?: sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), array('_controller' => $service . ':cancel', '_format' => 'json'), array(), array(), diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 95b35ab..d462101 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -15,12 +15,22 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase 'cat' => array($cat, array( 'enable_progress' => false, 'enable_cancelation' => false, - 'route_prefix' => '' + 'route_prefix' => '', + 'endpoints' => array( + 'upload' => null, + 'progress' => null, + 'cancel' => null, + ), )), 'dog' => array($dog, array( 'enable_progress' => true, 'enable_cancelation' => true, - 'route_prefix' => '' + 'route_prefix' => '', + 'endpoints' => array( + 'upload' => null, + 'progress' => null, + 'cancel' => null, + ), )), )); @@ -47,7 +57,12 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase 'cat' => array($cat, array( 'enable_progress' => false, 'enable_cancelation' => false, - 'route_prefix' => $prefix + 'route_prefix' => $prefix, + 'endpoints' => array( + 'upload' => null, + 'progress' => null, + 'cancel' => null, + ), )) )); @@ -61,4 +76,33 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals(0, strpos($route->getPath(), $prefix)); } } + + public function testCustomEndpointRoutes() + { + $customEndpointUpload = '/grumpy/cats/upload'; + $cat = 'GrumpyCatController'; + + $routeLoader = new RouteLoader(array( + 'cat' => array($cat, array( + 'enable_progress' => false, + 'enable_cancelation' => false, + 'route_prefix' => '', + 'endpoints' => array( + 'upload' => $customEndpointUpload, + 'progress' => null, + 'cancel' => null, + ), + )) + )); + + $routes = $routeLoader->load(null); + + foreach ($routes as $route) { + $this->assertInstanceOf('Symfony\Component\Routing\Route', $route); + $this->assertEquals('json', $route->getDefault('_format')); + $this->assertContains('POST', $route->getMethods()); + + $this->assertEquals($customEndpointUpload, $route->getPath()); + } + } } diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index 9d22fd6..d7f581b 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -3,10 +3,10 @@ namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; use Gaufrette\Adapter\StreamFactory; +use Gaufrette\Filesystem; +use Gaufrette\FilesystemInterface; use Oneup\UploaderBundle\Uploader\File\FilesystemFile; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; -use Gaufrette\Filesystem; - use Oneup\UploaderBundle\Uploader\Gaufrette\StreamManager; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -16,13 +16,27 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface protected $prefix; protected $streamWrapperPrefix; - public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) + /** + * @param FilesystemInterface|Filesystem $filesystem + * @param int $bufferSize + * @param string $streamWrapperPrefix + * @param string $prefix + */ + public function __construct($filesystem, $bufferSize, $streamWrapperPrefix, $prefix) { + $base = interface_exists('Gaufrette\FilesystemInterface') + ? 'Gaufrette\FilesystemInterface' + : 'Gaufrette\Filesystem'; + + if (!$filesystem instanceof $base) { + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, is_object($filesystem) ? get_class($filesystem) : gettype($filesystem))); + } + if (!($filesystem->getAdapter() instanceof StreamFactory)) { throw new \InvalidArgumentException('The filesystem used as chunk storage must implement StreamFactory'); } $this->filesystem = $filesystem; - $this->bufferSize = $bufferSize; + $this->buffersize = $bufferSize; $this->prefix = $prefix; $this->streamWrapperPrefix = $streamWrapperPrefix; } diff --git a/Uploader/ErrorHandler/PluploadErrorHandler.php b/Uploader/ErrorHandler/PluploadErrorHandler.php new file mode 100644 index 0000000..6716c87 --- /dev/null +++ b/Uploader/ErrorHandler/PluploadErrorHandler.php @@ -0,0 +1,19 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Exception; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class PluploadErrorHandler implements ErrorHandlerInterface +{ + public function addException(AbstractResponse $response, Exception $exception) + { + /* Plupload only needs an error message so it can be handled client side */ + $message = $exception->getMessage(); + $response['error'] = $message; + } +} + +?> diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php index 39c9234..1d38ab8 100644 --- a/Uploader/File/GaufretteFile.php +++ b/Uploader/File/GaufretteFile.php @@ -4,16 +4,30 @@ namespace Oneup\UploaderBundle\Uploader\File; use Gaufrette\Adapter\StreamFactory; use Gaufrette\File; -use Gaufrette\Filesystem; use Gaufrette\Adapter\AwsS3; +use Gaufrette\Filesystem; +use Gaufrette\FilesystemInterface; class GaufretteFile extends File implements FileInterface { protected $streamWrapperPrefix; protected $mimeType; - public function __construct(File $file, Filesystem $filesystem, $streamWrapperPrefix = null) + /** + * @param File $file + * @param FilesystemInterface|Filesystem $filesystem + * @param string|null $streamWrapperPrefix + */ + public function __construct(File $file, $filesystem, $streamWrapperPrefix = null) { + $base = interface_exists('Gaufrette\FilesystemInterface') + ? 'Gaufrette\FilesystemInterface' + : 'Gaufrette\Filesystem'; + + if (!$filesystem instanceof $base) { + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, is_object($filesystem) ? get_class($filesystem) : gettype($filesystem))); + } + parent::__construct($file->getKey(), $filesystem); $this->streamWrapperPrefix = $streamWrapperPrefix; } diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php index 7fcc83a..e745eef 100644 --- a/Uploader/Gaufrette/StreamManager.php +++ b/Uploader/Gaufrette/StreamManager.php @@ -46,7 +46,7 @@ class StreamManager $this->openStream($src, 'r'); while (!$src->eof()) { - $data = $src->read($this->bufferSize); + $data = $src->read($this->buffersize); $dst->write($data); } diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index 4be4daa..b003236 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -4,7 +4,6 @@ namespace Oneup\UploaderBundle\Uploader\Storage; use Gaufrette\File; use Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage as GaufretteChunkStorage; -use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; use Symfony\Component\HttpFoundation\Session\SessionInterface; @@ -30,7 +29,7 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto * initiate the storage on the chunk storage's filesystem * the stream wrapper is useful for metadata. */ - parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, $chunkStorage->getStreamWrapperPrefix()); + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->buffersize, $chunkStorage->getStreamWrapperPrefix()); $this->storage = $storage; $this->chunkStorage = $chunkStorage; diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 7b9bc7e..d83687e 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; +use Gaufrette\FilesystemInterface; use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; use Gaufrette\Filesystem; @@ -13,10 +14,23 @@ class GaufretteStorage extends StreamManager implements StorageInterface { protected $streamWrapperPrefix; - public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix = null) + /** + * @param FilesystemInterface|Filesystem $filesystem + * @param int $bufferSize + * @param string|null $streamWrapperPrefix + */ + public function __construct($filesystem, $bufferSize, $streamWrapperPrefix = null) { + $base = interface_exists('Gaufrette\FilesystemInterface') + ? 'Gaufrette\FilesystemInterface' + : 'Gaufrette\Filesystem'; + + if (!$filesystem instanceof $base) { + throw new \InvalidArgumentException(sprintf('Expected an instance of "%s", got "%s".', $base, is_object($filesystem) ? get_class($filesystem) : gettype($filesystem))); + } + $this->filesystem = $filesystem; - $this->bufferSize = $bufferSize; + $this->buffersize = $bufferSize; $this->streamWrapperPrefix = $streamWrapperPrefix; }
0
8d1b10eb56c2f9db969902518d5013935836f092
1up-lab/OneupUploaderBundle
Added a hint for the new Session upload progress implementation to the readme file.
commit 8d1b10eb56c2f9db969902518d5013935836f092 Author: Jim Schmid <[email protected]> Date: Tue Jun 25 16:54:09 2013 +0200 Added a hint for the new Session upload progress implementation to the readme file. diff --git a/README.md b/README.md index 2592a61..f72f219 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Features included: * Chunked uploads * Supports [Gaufrette](https://github.com/KnpLabs/Gaufrette) and/or local filesystem * Provides an orphanage for cleaning up orphaned files +* 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)
0
ac864c6d7b3e127970d4ced1b83ca99c80c176fe
1up-lab/OneupUploaderBundle
Tested FancyUpload controller.
commit ac864c6d7b3e127970d4ced1b83ca99c80c176fe Author: Jim Schmid <[email protected]> Date: Mon May 6 22:55:34 2013 +0200 Tested FancyUpload controller. diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index de85d76..7e78b16 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -29,6 +29,11 @@ oneup_uploader: storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + fancyupload: + frontend: fancyupload + storage: + directory: %kernel.root_dir%/cache/%kernel.environment%/upload + blueimp: frontend: blueimp storage: diff --git a/Tests/Controller/FancyUploadTest.php b/Tests/Controller/FancyUploadTest.php new file mode 100644 index 0000000..e3069c5 --- /dev/null +++ b/Tests/Controller/FancyUploadTest.php @@ -0,0 +1,29 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; + +class FancyUploadTest extends AbstractControllerTest +{ + protected function getConfigKey() + { + return 'fancyupload'; + } + + protected function getRequestParameters() + { + return array(); + } + + protected function getRequestFile() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txt', + 'text/plain', + 128 + ); + } +}
0
98a34307e1c291e92424ecdfc97193e572449e9e
1up-lab/OneupUploaderBundle
Update LICENSE
commit 98a34307e1c291e92424ecdfc97193e572449e9e Author: David Greminger <[email protected]> Date: Fri Jan 30 18:34:15 2015 +0100 Update LICENSE diff --git a/Resources/meta/LICENSE b/Resources/meta/LICENSE index 44d421f..bebab95 100644 --- a/Resources/meta/LICENSE +++ b/Resources/meta/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2013 1up GmbH +Copyright (c) 2015 1up GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -16,4 +16,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file +THE SOFTWARE.
0
33b37d19978b3068edd7dc74036026e0fe3cb13c
1up-lab/OneupUploaderBundle
Exclude logs/ directory as there will code coverage reports go.
commit 33b37d19978b3068edd7dc74036026e0fe3cb13c Author: Jim Schmid <[email protected]> Date: Sat Apr 6 16:24:18 2013 +0200 Exclude logs/ directory as there will code coverage reports go. diff --git a/.gitignore b/.gitignore index e1c36a4..820d851 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ composer.lock phpunit.xml -vendor \ No newline at end of file +vendor +log
0
03d5a6fea4e2f20504e27fb50adc1c649bbaeac2
1up-lab/OneupUploaderBundle
Added notes for 1.3.x
commit 03d5a6fea4e2f20504e27fb50adc1c649bbaeac2 Author: David Greminger <[email protected]> Date: Mon Jan 4 11:58:06 2016 +0100 Added notes for 1.3.x diff --git a/Resources/doc/index.md b/Resources/doc/index.md index f5d2e21..5850164 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -1,11 +1,12 @@ Getting started =============== -The OneupUploaderBundle is a Symfony2 bundle developed and tested for versions 2.1+. This bundle does only provide a solid backend for the supported types of Javascript libraries. It does however not provide the assets itself. So in order to use any uploader, you first have to download and integrate it by yourself. +The OneupUploaderBundle is a Symfony2 bundle developed and tested for versions 2.4+. This bundle does only provide a solid backend for the supported types of Javascript libraries. It does however not provide the assets itself. So in order to use any uploader, you first have to download and integrate it by yourself. ## Prerequisites -This bundle is tested using Symfony2 versions 2.4+. +This bundle is tested using Symfony 2.4+. +If you want to use the bundle with Symfony 2.3, head over to the documentation for [1.3.x](https://github.com/1up-lab/OneupUploaderBundle/blob/release-1.3.x/Resources/doc/index.md). ### Translations If you wish to use the default texts provided with this bundle, you have to make sure that you have translator
0
42ee22e20fb113e5f0b3b4a6606b3c1fd0c3cee8
1up-lab/OneupUploaderBundle
added version compare so tests are valid
commit 42ee22e20fb113e5f0b3b4a6606b3c1fd0c3cee8 Author: Martin Aarhof <[email protected]> Date: Wed Dec 9 10:35:52 2015 +0100 added version compare so tests are valid diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 4cf0f13..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->getRequest(); $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 7341727..d20bf8f 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 { @@ -206,6 +207,10 @@ abstract class AbstractController */ protected function getRequest() { + if (version_compare(Kernel::VERSION, '2.4') === -1) { + return $this->container->get('request'); + } + return $this->container->get('request_stack')->getMasterRequest(); }
0
cbb87b59746d2b035a4981e5ce945b6d0239d19e
1up-lab/OneupUploaderBundle
Merge pull request #22 from 1up-lab/upload-progress Upload progress
commit cbb87b59746d2b035a4981e5ce945b6d0239d19e (from 5364f980335109d5ae946d5ae540c327eeea8376) Merge: 5364f98 434a8ed Author: Jim Schmid <[email protected]> Date: Tue Jun 25 09:02:16 2013 -0700 Merge pull request #22 from 1up-lab/upload-progress Upload progress diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index ab4db65..c72861e 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Controller; +use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -33,6 +34,40 @@ abstract class AbstractController abstract public function upload(); + public function progress() + { + $request = $this->container->get('request'); + $session = $this->container->get('session'); + + $prefix = ini_get('session.upload_progress.prefix'); + $name = ini_get('session.upload_progress.name'); + + // assemble session key + // ref: http://php.net/manual/en/session.upload-progress.php + $key = sprintf('%s.%s', $prefix, $request->get($name)); + $value = $session->get($key); + + return new JsonResponse($value); + } + + public function cancel() + { + $request = $this->container->get('request'); + $session = $this->container->get('session'); + + $prefix = ini_get('session.upload_progress.prefix'); + $name = ini_get('session.upload_progress.name'); + + $key = sprintf('%s.%s', $prefix, $request->get($name)); + + $progress = $session->get($key); + $progress['cancel_upload'] = false; + + $session->set($key, $progress); + + return new JsonResponse(true); + } + /** * 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 41736a2..607797b 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -36,6 +36,27 @@ class BlueimpController extends AbstractChunkedController return new JsonResponse($response->assemble()); } + public function progress() + { + $request = $this->container->get('request'); + $session = $this->container->get('session'); + + $prefix = ini_get('session.upload_progress.prefix'); + $name = ini_get('session.upload_progress.name'); + + // ref: https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress + $key = sprintf('%s.%s', $prefix, $request->get($name)); + $value = $session->get($key); + + $progress = array( + 'lengthComputable' => true, + 'loaded' => $value['bytes_processed'], + 'total' => $value['content_length'] + ); + + return new JsonResponse($progress); + } + protected function parseChunkedRequest(Request $request) { $session = $this->container->get('session'); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c38cf24..9b4c457 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -72,6 +72,8 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->booleanNode('use_orphanage')->defaultFalse()->end() + ->booleanNode('enable_progress')->defaultFalse()->end() + ->booleanNode('enable_cancelation')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() ->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 24c872a..d1435fa 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -129,7 +129,16 @@ class OneupUploaderExtension extends Extension ->setScope('request') ; - $controllers[$key] = $controllerName; + 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.'); + } + } + + $controllers[$key] = array($controllerName, array( + 'enable_progress' => $mapping['enable_progress'], + 'enable_cancelation' => $mapping['enable_cancelation'] + )); } $container->setParameter('oneup_uploader.controllers', $controllers); diff --git a/README.md b/README.md index 2592a61..f72f219 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Features included: * Chunked uploads * Supports [Gaufrette](https://github.com/KnpLabs/Gaufrette) and/or local filesystem * Provides an orphanage for cleaning up orphaned files +* 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) diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index bea28a9..144c091 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -31,5 +31,7 @@ oneup_uploader: disallowed_mimetypes: [] max_size: 9223372036854775807 use_orphanage: false + enable_progress: false + enable_cancelation: false namer: oneup_uploader.namer.uniqid ``` diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 7e5a2ce..d5b5721 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -122,6 +122,7 @@ some more advanced features. * [Support a custom uploader](custom_uploader.md) * [Validate your uploads](custom_validator.md) * [General/Generic Events](events.md) +* [Enable Session upload progress / upload cancelation](progress.md) * [Configuration Reference](configuration_reference.md) ## FAQ diff --git a/Resources/doc/progress.md b/Resources/doc/progress.md new file mode 100644 index 0000000..f3a6833 --- /dev/null +++ b/Resources/doc/progress.md @@ -0,0 +1,88 @@ +Enable Session Upload Progress +============================== + +As of PHP 5.4, there is the possibility to track the upload progress of individual files being uploaded. +To enable this feature be sure you enable it in your configuration. + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + enable_progress: true +``` + +The OneupUploaderBundle generates a new route for you to probe the status of a file currently being uploaded. +Once again, there are frontend helpers to simplify this process: + +* `{{ oneup_uploader_progress('gallery') }}` This helper will return the path where you can send your progress request to. +* `{{ oneup_uploader_upload_key() }}` This helper will return the ini option `session.upload_progress.name`. + +An example of this feature using the jQuery File Upload plugin can be found in the [corresponding wiki article](https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress): + +```js +$('#fileupload').bind('fileuploadsend', function (e, data) { + if (data.dataType.substr(0, 6) === 'iframe') { + var progressObj = { + name: '{{ oneup_uploader_upload_key() }}', + value: (new Date()).getTime() // pseudo unique ID + }; + + data.formData.push(progressObj); + data.context.data('interval', setInterval(function () { + $.get('{{ oneup_uploader_progress("gallery") }}', $.param([progressObj]), function (result) { + e = $.Event( 'progress', {bubbles: false, cancelable: true}); + $.extend(e, result); + ($('#fileupload').data('blueimp-fileupload') || + $('#fileupload').data('fileupload'))._onProgress(e, data); + }, 'json'); + }, 1000)); + } +}).bind('fileuploadalways', function (e, data) { + clearInterval(data.context.data('interval')); +}); +``` + +Be sure to initially send the key/value in your upload request for this to work. Or to quote the [PHP-Manual](http://php.net/manual/en/session.upload-progress.php): + +> The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. + + +Enable Cancelation Route +------------------------ + +The new API also comes with a handy new feature to cancel uploads currently in process. +To activate the corresponding route, simply enable it in your configuration file. + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + enable_cancelation: true +``` + +If enabled, you can use the frontend helper function to get the correct route: + +```twig +{{ oneup_uploader_cancel('gallery') }} +``` + +You still need to send the correct value for the `oneup_uploader_upload_key`. + +Caveats +------- + +You'll need an activated session for this feature to work correctly. Be sure to enable the session for anonymous users, if you provide anonymous uploads: + +```yml +# app/config/security.yml + +security: + firewalls: + main: + pattern: ^/ + anonymous: true +``` diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 236f950..a464dc2 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -24,14 +24,38 @@ class RouteLoader extends Loader { $routes = new RouteCollection(); - foreach ($this->controllers as $type => $service) { + foreach ($this->controllers as $type => $controllerArray) { + + $service = $controllerArray[0]; + $options = $controllerArray[1]; + $upload = new Route( sprintf('/_uploader/%s/upload', $type), array('_controller' => $service . ':upload', '_format' => 'json'), array('_method' => 'POST') ); - $routes->add(sprintf('_uploader_%s', $type), $upload); + if ($options['enable_progress'] === true) { + $progress = new Route( + sprintf('/_uploader/%s/progress', $type), + array('_controller' => $service . ':progress', '_format' => 'json'), + array('_method' => 'POST') + ); + + $routes->add(sprintf('_uploader_progress_%s', $type), $progress); + } + + if ($options['enable_cancelation'] === true) { + $progress = new Route( + sprintf('/_uploader/%s/cancel', $type), + array('_controller' => $service . ':cancel', '_format' => 'json'), + array('_method' => 'POST') + ); + + $routes->add(sprintf('_uploader_cancel_%s', $type), $progress); + } + + $routes->add(sprintf('_uploader_upload_%s', $type), $upload); } return $routes; diff --git a/Templating/Helper/UploaderHelper.php b/Templating/Helper/UploaderHelper.php index 1882766..c433675 100644 --- a/Templating/Helper/UploaderHelper.php +++ b/Templating/Helper/UploaderHelper.php @@ -21,6 +21,21 @@ class UploaderHelper extends Helper public function endpoint($key) { - return $this->router->generate(sprintf('_uploader_%s', $key)); + return $this->router->generate(sprintf('_uploader_upload_%s', $key)); + } + + public function progress($key) + { + return $this->router->generate(sprintf('_uploader_progress_%s', $key)); + } + + public function cancel($key) + { + return $this->router->generate(sprintf('_uploader_cancel_%s', $key)); + } + + public function uploadKey() + { + return ini_get('session.upload_progress.name'); } } diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 017a94e..08d433c 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -12,8 +12,14 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $dog = 'HelloThisIsDogController'; $routeLoader = new RouteLoader(array( - 'cat' => $cat, - 'dog' => $dog + 'cat' => array($cat, array( + 'enable_progress' => false, + 'enable_cancelation' => false + )), + 'dog' => array($dog, array( + 'enable_progress' => true, + 'enable_cancelation' => true + )), )); $routes = $routeLoader->load(null); @@ -21,7 +27,7 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase // for code coverage $this->assertTrue($routeLoader->supports('grumpy', 'uploader')); $this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $routes); - $this->assertCount(2, $routes); + $this->assertCount(4, $routes); foreach ($routes as $route) { $this->assertInstanceOf('Symfony\Component\Routing\Route', $route); diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index 8849b79..2665a89 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -20,11 +20,31 @@ class UploaderExtension extends \Twig_Extension public function getFunctions() { - return array('oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint')); + return array( + 'oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint'), + 'oneup_uploader_progress' => new \Twig_Function_Method($this, 'progress'), + 'oneup_uploader_cancel' => new \Twig_Function_Method($this, 'cancel'), + 'oneup_uploader_upload_key' => new \Twig_Function_Method($this, 'uploadKey') + ); } public function endpoint($key) { return $this->helper->endpoint($key); } + + public function progress($key) + { + return $this->helper->progress($key); + } + + public function cancel($key) + { + return $this->helper->cancel($key); + } + + public function uploadKey() + { + return $this->helper->uploadKey(); + } }
0
130bef29476e69601526ca47adbdc18ad8ee3f6f
1up-lab/OneupUploaderBundle
separated storages both in definition and configuration
commit 130bef29476e69601526ca47adbdc18ad8ee3f6f Author: mitom <[email protected]> Date: Thu Oct 10 12:27:42 2013 +0200 separated storages both in definition and configuration diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index ab37255..1cf8414 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -28,6 +28,7 @@ class Configuration implements ConfigurationInterface ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('directory')->defaultNull()->end() ->scalarNode('sync_buffer_size')->defaultValue('100K')->end() + ->scalarNode('prefix')->defaultValue('chunks')->end() ->end() ->end() ->booleanNode('load_distribution')->defaultTrue()->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 72445fa..6a8bff1 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -32,17 +32,7 @@ class OneupUploaderExtension extends Extension $loader->load('twig.xml'); } - if ($this->config['chunks']['storage']['type'] === 'filesystem' && - !isset($this->config['chunks']['storage']['directory'])) { - $this->config['chunks']['storage']['directory'] = sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')); - } elseif ($this->config['chunks']['storage']['type'] === 'gaufrette' ) { - // Force load distribution when using gaufrette chunk storage - $this->config['chunks']['load_distribution'] = true; - } - - // register the service for the chunk storage - $this->createStorageService($this->config['chunks']['storage'], 'chunk'); - + $this->createChunkStorageService(); $this->config['orphanage']['directory'] = is_null($this->config['orphanage']['directory']) ? sprintf('%s/uploader/orphanage', $container->getParameter('kernel.cache_dir')) : @@ -56,10 +46,6 @@ class OneupUploaderExtension extends Extension // handle mappings foreach ($this->config['mappings'] as $key => $mapping) { - if ($key === 'chunk') { - throw new InvalidArgumentException('"chunk" is a protected mapping name, please use a different one.'); - } - $mapping['max_size'] = $mapping['max_size'] < 0 ? $this->getMaxUploadSize($mapping['max_size']) : $mapping['max_size'] @@ -114,42 +100,57 @@ class OneupUploaderExtension extends Extension $container->setParameter('oneup_uploader.controllers', $controllers); } - protected function createStorageService($storage, $key, $orphanage = null) + protected function createChunkStorageService() + { + $config = &$this->config['chunks']['storage']; + + $storageClass = sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type']); + if ($config['type'] === 'filesystem') { + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : + $this->normalizePath($config['directory']) + ; + + $this->container + ->register('oneup_uploader.chunks_storage', sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type'])) + ->addArgument($config['directory']) + ; + } else { + $this->registerGaufretteStorage('oneup_uploader.chunks_storage', $storageClass, $config['filesystem'], $config['sync_buffer_size'], $config['prefix']); + + // 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) { $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 (isset($storage['service']) && !is_null($storage['service'])) { - $storageService = new Reference($storage['storage']['service']); + if (!is_null($config['service'])) { + $storageService = new Reference($config['storage']['service']); } else { // no service was given, so we create one $storageName = sprintf('oneup_uploader.storage.%s', $key); + $storageClass = sprintf('%%oneup_uploader.storage.%s.class%%', $config['type']); - if ($storage['type'] == 'filesystem') { - $storage['directory'] = is_null($storage['directory']) ? + if ($config['type'] == 'filesystem') { + $config['directory'] = is_null($config['directory']) ? sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : - $this->normalizePath($storage['directory']) + $this->normalizePath($config['directory']) ; $this->container - ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $storage['type'])) - ->addArgument($storage['directory']) + ->register($storageName, $storageClass) + ->addArgument($config['directory']) ; } - if ($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($storage['filesystem']) <= 0) - throw new ServiceNotFoundException('Empty service name'); - - $this->container - ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $storage['type'])) - ->addArgument(new Reference($storage['filesystem'])) - ->addArgument($this->getValueInBytes($storage['sync_buffer_size'])) - ; + if ($config['type'] == 'gaufrette') { + $this->registerGaufretteStorage($storageName, $storageClass, $config['filesystem'], $config['sync_buffer_size']); } $storageService = new Reference($storageName); @@ -175,6 +176,21 @@ class OneupUploaderExtension extends Extension return $storageService; } + protected function registerGaufretteStorage($key, $class, $filesystem, $buffer, $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'); + + $this->container + ->register($key, $class) + ->addArgument(new Reference($filesystem)) + ->addArgument($this->getValueInBytes($buffer)) + ->addArgument($prefix) + ; + } protected function getMaxUploadSize($input) { diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 3c95386..66c7e70 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -5,6 +5,8 @@ <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> @@ -26,7 +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.storage.chunk" /> + <argument type="service" id="oneup_uploader.chunks_storage" /> </service> <service id="oneup_uploader.orphanage_manager" class="%oneup_uploader.orphanage.manager.class%"> diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 39bd2d2..49050c0 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -2,11 +2,8 @@ namespace Oneup\UploaderBundle\Uploader\Chunk; -use Oneup\UploaderBundle\Uploader\Storage\ChunkStorageInterface; -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; diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index 99ad60c..c89d9bf 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -21,9 +21,9 @@ interface ChunkManagerInterface /** * Assembles the given chunks and return the resulting file. * - * @param $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 */ diff --git a/Uploader/Storage/ChunkStorageInterface.php b/Uploader/Chunk/Storage/ChunkStorageInterface.php similarity index 86% rename from Uploader/Storage/ChunkStorageInterface.php rename to Uploader/Chunk/Storage/ChunkStorageInterface.php index b9fa1f6..2be1146 100644 --- a/Uploader/Storage/ChunkStorageInterface.php +++ b/Uploader/Chunk/Storage/ChunkStorageInterface.php @@ -1,7 +1,6 @@ <?php -namespace Oneup\UploaderBundle\Uploader\Storage; - +namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -16,4 +15,4 @@ interface ChunkStorageInterface public function cleanup($path); public function getChunks($uuid); -} \ No newline at end of file +} 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..00b0031 --- /dev/null +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -0,0 +1,143 @@ +<?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; + + public function __construct(Filesystem $filesystem, $bufferSize, $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; + } + + public function clear($maxAge) + { + $matches = $this->filesystem->listKeys($this->prefix); + + $limit = time()+$maxAge; + $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 ($limit < $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 ($limit < $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) { + //do nothing + } + } + } + + /** + * 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 + ); + + return; + } + + 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); + } + + public function cleanup($path) + { + $this->filesystem->delete($path); + } + + public function getChunks($uuid) + { + return $this->filesystem->listKeys($this->prefix.'/'.$uuid)['keys']; + } +} diff --git a/Uploader/File/FileInterface.php b/Uploader/File/FileInterface.php index 47e4266..511169d 100644 --- a/Uploader/File/FileInterface.php +++ b/Uploader/File/FileInterface.php @@ -21,10 +21,17 @@ interface FileInterface public function getSize(); /** - * Returns the directory of the file without the filename + * 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(); /** @@ -35,11 +42,11 @@ interface FileInterface public function getMimeType(); /** - * Returns the filename of the file + * Returns the basename of the file * * @return string */ - public function getName(); + public function getBasename(); /** * Returns the guessed extension of the file @@ -47,4 +54,4 @@ interface FileInterface * @return mixed */ public function getExtension(); -} \ No newline at end of file +} diff --git a/Uploader/File/FilesystemFile.php b/Uploader/File/FilesystemFile.php index eed8d67..f30d028 100644 --- a/Uploader/File/FilesystemFile.php +++ b/Uploader/File/FilesystemFile.php @@ -10,6 +10,6 @@ class FilesystemFile extends UploadedFile implements FileInterface public function __construct(UploadedFile $file) { $this->file = $file; - parent::__construct($file->getPath(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); + parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); } -} \ No newline at end of file +} diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php index 7771c4a..fd0701a 100644 --- a/Uploader/File/GaufretteFile.php +++ b/Uploader/File/GaufretteFile.php @@ -9,7 +9,8 @@ class GaufretteFile extends File implements FileInterface { protected $filesystem; - public function __construct(File $file, Filesystem $filesystem) { + public function __construct(File $file, Filesystem $filesystem) + { parent::__construct($file->getKey(), $filesystem); $this->filesystem = $filesystem; } @@ -30,12 +31,17 @@ class GaufretteFile extends File implements FileInterface return parent::getSize(); } + public function getPathname() + { + return $this->getKey(); + } + public function getPath() { return pathinfo($this->getKey(), PATHINFO_DIRNAME); } - public function getName() + public function getBasename() { return pathinfo($this->getKey(), PATHINFO_BASENAME); } @@ -46,6 +52,7 @@ class GaufretteFile extends File implements FileInterface public function getMimeType() { $finfo = finfo_open(FILEINFO_MIME_TYPE); + return finfo_file($finfo, $this->getKey()); } @@ -59,4 +66,4 @@ class GaufretteFile extends File implements FileInterface return $this->filesystem; } -} \ No newline at end of file +} diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php new file mode 100644 index 0000000..3ae16c5 --- /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; + protected $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 173e0b8..fabd017 100644 --- a/Uploader/Naming/NamerInterface.php +++ b/Uploader/Naming/NamerInterface.php @@ -2,7 +2,6 @@ namespace Oneup\UploaderBundle\Uploader\Naming; - use Oneup\UploaderBundle\Uploader\File\FileInterface; interface NamerInterface diff --git a/Uploader/Naming/UniqidNamer.php b/Uploader/Naming/UniqidNamer.php index 80bc741..34a7141 100644 --- a/Uploader/Naming/UniqidNamer.php +++ b/Uploader/Naming/UniqidNamer.php @@ -2,7 +2,6 @@ namespace Oneup\UploaderBundle\Uploader\Naming; - use Oneup\UploaderBundle\Uploader\File\FileInterface; class UniqidNamer implements NamerInterface diff --git a/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index d443f3c..c6c9001 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -3,14 +3,9 @@ namespace Oneup\UploaderBundle\Uploader\Storage; use Oneup\UploaderBundle\Uploader\File\FileInterface; -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 StorageInterface,ChunkStorageInterface +class FilesystemStorage implements StorageInterface { protected $directory; @@ -37,107 +32,4 @@ class FilesystemStorage implements StorageInterface,ChunkStorageInterface return $file; } - - 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/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 6c82693..35d46b7 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -4,19 +4,12 @@ namespace Oneup\UploaderBundle\Uploader\Storage; use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\File\GaufretteFile; -use Gaufrette\Stream\Local as LocalStream; -use Gaufrette\StreamMode; use Gaufrette\Filesystem; use Gaufrette\Adapter\MetadataSupporter; +use Oneup\UploaderBundle\Uploader\Gaufrette\StreamManager; -use Symfony\Component\HttpFoundation\File\UploadedFile; - -class GaufretteStorage implements StorageInterface, ChunkStorageInterface +class GaufretteStorage extends StreamManager implements StorageInterface { - protected $filesystem; - protected $bufferSize; - protected $unhandledChunk; - protected $chunkPrefix = 'chunks'; public function __construct(Filesystem $filesystem, $bufferSize) { @@ -36,138 +29,17 @@ class GaufretteStorage implements StorageInterface, ChunkStorageInterface } } - $this->stream($file, $path, $name); - - return $this->filesystem->get($path); - } - - public function clear($maxAge) - { - $matches = $this->filesystem->listKeys($this->chunkPrefix); - - $limit = time()+$maxAge; - $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 ($limit < $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 ($limit < $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) { - //do nothing - } - } - } - - /** - * 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 - ); - return; - } - - public function assembleChunks($chunks, $removeChunk, $renameChunk) - { - // the index is only added to be in sync with the filesystem storage - $path = $this->chunkPrefix.'/'.$this->unhandledChunk['uuid'].'/'; - $filename = $this->unhandledChunk['index'].'_'.$this->unhandledChunk['original']; - - if (empty($chunks)) { - $target = $filename; - } 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); - } - - $this->stream($this->unhandledChunk['chunk'], $path, $target); - - 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); - } - - public function cleanup($path) - { - $this->filesystem->delete($path); - } - - public function getChunks($uuid) - { - return $this->filesystem->listKeys($this->chunkPrefix.'/'.$uuid)['keys']; - } - - protected function stream($file, $path, $name) - { if ($this->filesystem->getAdapter() instanceof MetadataSupporter) { $this->filesystem->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); } - - $path = $path.$name; - // 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); - - $src = new LocalStream($file->getPathname()); + $this->ensureRemotePathExists($path.$name); $dst = $this->filesystem->createStream($path); - $src->open(new StreamMode('rb+')); - $dst->open(new StreamMode('ab+')); + $this->openStream($dst, 'w'); - while (!$src->eof()) { - $data = $src->read($this->bufferSize); - $dst->write($data); - } + $this->stream($file, $dst); - $dst->close(); - $src->close(); + return $this->filesystem->get($path); } }
0
2a927237ab0f617eb40e63d4c701f5da35c2fbb7
1up-lab/OneupUploaderBundle
Update index.md Removed old information about supported libraries.
commit 2a927237ab0f617eb40e63d4c701f5da35c2fbb7 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 18:34:13 2013 +0300 Update index.md Removed old information about supported libraries. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index cb24aa1..b85b8fd 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. 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. It has the following form: _uploader_{mapping_key} @@ -127,4 +127,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.
0
6dcdd88546130e157bb430ffa9589ecf60ac3213
1up-lab/OneupUploaderBundle
Tested FancyUpload controller.
commit 6dcdd88546130e157bb430ffa9589ecf60ac3213 Author: Jim Schmid <[email protected]> Date: Mon May 6 23:13:35 2013 +0200 Tested FancyUpload controller. diff --git a/Tests/Controller/PluploadTest.php b/Tests/Controller/PluploadTest.php index ddc337f..216886f 100644 --- a/Tests/Controller/PluploadTest.php +++ b/Tests/Controller/PluploadTest.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractChunkedControllerTest; -class PluploadTest extends AbstractControllerTest +class PluploadTest extends AbstractChunkedControllerTest { protected function getConfigKey() { @@ -26,4 +26,23 @@ class PluploadTest extends AbstractControllerTest 128 ); } + + protected function getNextRequestParameters($i) + { + return array( + 'chunks' => $this->total, + 'chunk' => $i, + 'name' => 'cat.txt' + ); + } + + protected function getNextFile($i) + { + return new UploadedFile( + $this->createTempFile(21), + 'cat.txt', + 'text/plain', + 21 + ); + } }
0
196580d73854debc46739ad5197c9c567f621c5f
1up-lab/OneupUploaderBundle
Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle
commit 196580d73854debc46739ad5197c9c567f621c5f (from d7a2376b3367c4ca3841d1c70acdac267da43ca6) Merge: d7a2376 66046fa Author: Jim Schmid <[email protected]> Date: Mon Apr 8 10:26:15 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 860ea15..f609759 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -68,7 +68,8 @@ This bundle was designed to just work out of the box. The only thing you have to # app/config/config.yml oneup_uploader: - gallery: ~ + mappings: + gallery: ~ ``` ### Step 4: Prepare your frontend @@ -107,4 +108,4 @@ some more advanced features. * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) * Testing this bundle -* [Configuration Reference](configuration_reference.md) \ No newline at end of file +* [Configuration Reference](configuration_reference.md) commit 196580d73854debc46739ad5197c9c567f621c5f (from 66046fa86a669d1c15e4e66f27ea83f7c7c2fcfe) Merge: d7a2376 66046fa Author: Jim Schmid <[email protected]> Date: Mon Apr 8 10:26:15 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/DependencyInjection/Compiler/ControllerCompilerPass.php b/DependencyInjection/Compiler/ControllerCompilerPass.php deleted file mode 100644 index a56ea90..0000000 --- a/DependencyInjection/Compiler/ControllerCompilerPass.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\DependencyInjection\Compiler; - -use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; - -class ControllerCompilerPass implements CompilerPassInterface -{ - public function process(ContainerBuilder $container) - { - $tags = $container->findTaggedServiceIds('oneup_uploader.routable'); - - if(count($tags) > 0 && $container->hasDefinition('oneup_uploader.routing.loader')) - { - $loader = $container->getDefinition('oneup_uploader.routing.loader'); - - foreach($tags as $id => $tag) - { - $loader->addMethodCall('addController', array($tag[0]['type'], $id)); - } - } - } -} \ No newline at end of file diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index c828879..04eb240 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -35,6 +35,8 @@ class OneupUploaderExtension extends Extension $container->setParameter('oneup_uploader.chunks', $config['chunks']); $container->setParameter('oneup_uploader.orphanage', $config['orphanage']); + $controllers = array(); + // handle mappings foreach($config['mappings'] as $key => $mapping) { @@ -102,9 +104,11 @@ class OneupUploaderExtension extends Extension } } + $controllerName = sprintf('oneup_uploader.controller.%s', $key); + // create controllers based on mapping $container - ->register(sprintf('oneup_uploader.controller.%s', $key), $container->getParameter('oneup_uploader.controller.class')) + ->register($controllerName, $container->getParameter('oneup_uploader.controller.class')) ->addArgument(new Reference('service_container')) ->addArgument($storageService) @@ -114,7 +118,11 @@ class OneupUploaderExtension extends Extension ->addTag('oneup_uploader.routable', array('type' => $key)) ->setScope('request') ; + + $controllers[$key] = $controllerName; } + + $container->setParameter('oneup_uploader.controllers', $controllers); } protected function getMaxUploadSize($input) diff --git a/OneupUploaderBundle.php b/OneupUploaderBundle.php index f359549..693f273 100644 --- a/OneupUploaderBundle.php +++ b/OneupUploaderBundle.php @@ -9,10 +9,4 @@ use Oneup\UploaderBundle\DependencyInjection\Compiler\ControllerCompilerPass; class OneupUploaderBundle extends Bundle { - public function build(ContainerBuilder $container) - { - parent::build($container); - - $container->addCompilerPass(new ControllerCompilerPass); - } } \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 0f9d511..13baac6 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -31,6 +31,7 @@ <!-- routing --> <service id="oneup_uploader.routing.loader" class="%oneup_uploader.routing.loader.class%"> + <argument>%oneup_uploader.controllers%</argument> <tag name="routing.loader" /> </service> diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index c7dfb91..9145ff1 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -10,14 +10,9 @@ class RouteLoader extends Loader { protected $controllers; - public function __construct() + public function __construct(array $controllers) { - $this->controllers = array(); - } - - public function addController($type, $controller) - { - $this->controllers[$type] = $controller; + $this->controllers = $controllers; } public function supports($resource, $type = null)
0
d0157cb77b57d088bc5c6a5ca77e092e42065098
1up-lab/OneupUploaderBundle
Added installation and configuration docs.
commit d0157cb77b57d088bc5c6a5ca77e092e42065098 Author: Jim Schmid <[email protected]> Date: Sun Apr 7 13:02:06 2013 +0200 Added installation and configuration docs. diff --git a/Resources/docs/index.md b/Resources/docs/index.md new file mode 100644 index 0000000..0fec11f --- /dev/null +++ b/Resources/docs/index.md @@ -0,0 +1,98 @@ +Getting started +=============== + +## Prerequisites + +This bundle tested using Symfony2 versions 2.1+. + +### Translations +If you wish to use the default texts provided with this bundle, you have to make sure that you have translator +enabled in your configuration file. + +``` +# app/config/config.yml + +framework: + translator: ~ +``` + +## Installation + +Perform the following step to install and use the basic functionality of the OneupUploaderBundle: + +* Download OnueupUploaderBundle using Composer +* Enable the bundle +* Configure the bundle +* Prepare your frontend + +### Step 1: Download the OneupUploaderBundle + +Add OneupUploaderBundle to your composer.json using the following construct: + +```js +{ + "require": { + "oneup/uploader-bundle": "*" + } +} +``` + +Now tell composer to download the bundle by running the following command: + + $> php composer.phar update oneup/uploader-bundle + +Composer will now fetch and install this bundle in the vendor directory ```vendor/oneup``` + +### Step 2: Enable the bundle + +Enable the bundle in the kernel: + +``` php +<?php +// app/AppKernel.php + +public function registerBundles() +{ + $bundles = array( + // ... + new Oneup\UploaderBundle\OneupUploaderBundle(), + ); +} +``` + +### Step 3: Configure the bundle + +This bundle was designed to just work out of the box. The only thing you have to configure in order to get this bundle up and running is a mapping. + +``` +# app/config/config.yml + +oneup_uploader: + gallery: ~ +``` + +### Step 4: Prepare your frontend + +As this is a server implementation for Fine Uploader, you have to include this library in order to upload files through this bundle. You can find them on the [official page](http://fineuploader.com) of Fine Uploader. Be sure to connect the endpoint property to the dynamic route created from your mapping. It has the following form: + + _uploader_{mapping_key} + +``` +<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> +<script type="text/javascript" src="js/jquery.fineuploader-3.4.1.js"></script> +<script type="text/javascript"> +$(document).ready(function() +{ + var uploader = new qq.FineUploader({ + element: $('#uploader'), + request: { + endpoint: "{{ path('_uploader_gallery') }}" + } + }); +}); +</script> + +<div id="uploader"></div> +``` + +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
0
dd5997eaa5a942434f69dad54f7311ac2f483e3a
1up-lab/OneupUploaderBundle
Fixed typo in extends usage of PHPUnit_Framework_TestCase in OrphanageTest
commit dd5997eaa5a942434f69dad54f7311ac2f483e3a Author: haeber <[email protected]> Date: Tue Oct 4 15:23:31 2016 +0200 Fixed typo in extends usage of PHPUnit_Framework_TestCase in OrphanageTest diff --git a/Tests/Uploader/Storage/OrphanageTest.php b/Tests/Uploader/Storage/OrphanageTest.php index ce3f6cd..c539e7f 100644 --- a/Tests/Uploader/Storage/OrphanageTest.php +++ b/Tests/Uploader/Storage/OrphanageTest.php @@ -6,7 +6,7 @@ use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -abstract class OrphanageTest extends \PHPUnit_Framework_Testcase +abstract class OrphanageTest extends \PHPUnit_Framework_TestCase { protected $tempDirectory; protected $realDirectory;
0
71d6118a7598701727b72b2d712ad231184a8778
1up-lab/OneupUploaderBundle
another php5.3 fix
commit 71d6118a7598701727b72b2d712ad231184a8778 Author: mitom <[email protected]> Date: Fri Oct 11 17:14:24 2013 +0200 another php5.3 fix diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index e087c1b..ea5379f 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -68,7 +68,8 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto public function getFiles() { - $keys = $this->chunkStorage->getFilesystem()->listKeys($this->getPath())['keys']; + $keys = $this->chunkStorage->getFilesystem()->listKeys($this->getPath()); + $keys = $keys['keys']; $files = array(); foreach ($keys as $key) {
0
23013aad81b049a5220756d37c09937cbf85b66f
1up-lab/OneupUploaderBundle
Add a new abstraction layer, so you are not forced to use Gaufrette.
commit 23013aad81b049a5220756d37c09937cbf85b66f Author: Jim Schmid <[email protected]> Date: Thu Apr 4 11:47:44 2013 +0200 Add a new abstraction layer, so you are not forced to use Gaufrette. diff --git a/Uploader/Filesystem/FilesystemInterface.php b/Uploader/Filesystem/FilesystemInterface.php new file mode 100644 index 0000000..d648632 --- /dev/null +++ b/Uploader/Filesystem/FilesystemInterface.php @@ -0,0 +1,8 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Filesystem; + +interface FilesystemInterface +{ + public function upload(File $file, $name = null, $path = null); +} \ No newline at end of file
0
66046fa86a669d1c15e4e66f27ea83f7c7c2fcfe
1up-lab/OneupUploaderBundle
Fixed documented config.yml file.
commit 66046fa86a669d1c15e4e66f27ea83f7c7c2fcfe Author: Jim Schmid <[email protected]> Date: Mon Apr 8 10:04:29 2013 +0300 Fixed documented config.yml file. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 860ea15..f609759 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -68,7 +68,8 @@ This bundle was designed to just work out of the box. The only thing you have to # app/config/config.yml oneup_uploader: - gallery: ~ + mappings: + gallery: ~ ``` ### Step 4: Prepare your frontend @@ -107,4 +108,4 @@ some more advanced features. * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) * Testing this bundle -* [Configuration Reference](configuration_reference.md) \ No newline at end of file +* [Configuration Reference](configuration_reference.md)
0
59621666d24849e0358617a31df2bd02c0dc5e47
1up-lab/OneupUploaderBundle
Removed unused require (comes with symfony/framework-bundle)
commit 59621666d24849e0358617a31df2bd02c0dc5e47 Author: David Greminger <[email protected]> Date: Thu Dec 10 17:18:45 2015 +0100 Removed unused require (comes with symfony/framework-bundle) diff --git a/composer.json b/composer.json index e9f912f..b2f32a3 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,6 @@ "require": { "symfony/framework-bundle": "^2.4.0|~3.0", - "symfony/http-kernel": "^2.4.0|~3.0", "symfony/finder": "^2.4.0|~3.0" },
0
09141db3d858b433677c6275e6759abaa34bf1a9
1up-lab/OneupUploaderBundle
Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle
commit 09141db3d858b433677c6275e6759abaa34bf1a9 (from e9ca3e0ca7dbe1032cada59394dcce77da9d1315) Merge: e9ca3e0 fdf8085 Author: Jim Schmid <[email protected]> Date: Tue Jun 4 10:16:08 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 2b6be7a..7e5a2ce 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": "*" + "oneup/uploader-bundle": "dev-master" } } ``` commit 09141db3d858b433677c6275e6759abaa34bf1a9 (from fdf8085cf38ee6403626c15c87e09439138d2807) Merge: e9ca3e0 fdf8085 Author: Jim Schmid <[email protected]> Date: Tue Jun 4 10:16:08 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/.travis.yml b/.travis.yml index 40d1a2d..0acf73b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,7 @@ php: env: - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* + - SYMFONY_VERSION=2.3.* before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source
0
b2a6337f00bee4db6c567ab7fe698ab8ebe55c2b
1up-lab/OneupUploaderBundle
Added the ability to enable Session Upload Progress
commit b2a6337f00bee4db6c567ab7fe698ab8ebe55c2b Author: Jim Schmid <[email protected]> Date: Mon Jun 24 20:21:04 2013 +0200 Added the ability to enable Session Upload Progress diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c38cf24..aa704c3 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -71,6 +71,7 @@ class Configuration implements ConfigurationInterface ->prototype('scalar')->end() ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() + ->booleanNode('use_upload_progress')->defaultValue(false)->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 24c872a..b5d7c58 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -129,7 +129,9 @@ class OneupUploaderExtension extends Extension ->setScope('request') ; - $controllers[$key] = $controllerName; + $controllers[$key] = array($controllerName, array( + 'use_upload_progress' => $mapping['use_upload_progress'] + )); } $container->setParameter('oneup_uploader.controllers', $controllers); diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 236f950..7771274 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -24,13 +24,25 @@ class RouteLoader extends Loader { $routes = new RouteCollection(); - foreach ($this->controllers as $type => $service) { + foreach ($this->controllers as $type => $controllerArray) { + + $service = $controllerArray[0]; + $options = $controllerArray[1]; + $upload = new Route( sprintf('/_uploader/%s/upload', $type), array('_controller' => $service . ':upload', '_format' => 'json'), array('_method' => 'POST') ); + if ($options['use_upload_progress'] === true) { + $progress = new Route( + sprintf('/_uploader/%s/progress', $type), + array('_controller' => $service . ':progress', '_format' => 'json'), + array('_method' => 'POST') + ); + } + $routes->add(sprintf('_uploader_%s', $type), $upload); }
0
89e84169a46cf48796fc2734866554f8d3554115
1up-lab/OneupUploaderBundle
Testing one third of the validations in the controller.
commit 89e84169a46cf48796fc2734866554f8d3554115 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 12:51:40 2013 +0200 Testing one third of the validations in the controller. diff --git a/Tests/Controller/ControllerValidationTest.php b/Tests/Controller/ControllerValidationTest.php new file mode 100644 index 0000000..944cc51 --- /dev/null +++ b/Tests/Controller/ControllerValidationTest.php @@ -0,0 +1,94 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Oneup\UploaderBundle\Controller\UploaderController; + +class ControllerValidationTest extends \PHPUnit_Framework_TestCase +{ + /** + * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException + */ + public function testMaxSizeValidationFails() + { + // create a config + $config = array(); + $config['max_size'] = 10; + $config['allowed_types'] = array(); + $config['disallowed_types'] = 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); + } + + public function testMaxSizeValidationPasses() + { + // create a config + $config = array(); + $config['max_size'] = 20; + $config['allowed_types'] = array(); + $config['disallowed_types'] = 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); + } + + protected function getUploadedFileMock() + { + $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + ->disableOriginalConstructor() + ->getMock() + ; + + $file + ->expects($this->any()) + ->method('getClientSize') + ->will($this->returnValue(15)) + ; + + $file + ->expects($this->any()) + ->method('getClientOriginalName') + ->will($this->returnValue('grumpycat.jpeg')) + ; + + return $file; + } + + protected function getContainerMock() + { + return $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); + } + + protected function getStorageMock() + { + return $this->getMock('Oneup\UploaderBundle\Uploader\Storage\StorageInterface'); + } + + protected function getValidationMethod() + { + // create a public version of the validate method + $class = new \ReflectionClass('Oneup\\UploaderBundle\\Controller\\UploaderController'); + $method = $class->getMethod('validate'); + $method->setAccessible(true); + + return $method; + } +} \ No newline at end of file
0
13dee605501659d1bdcd738f3a9c4e7be97094a0
1up-lab/OneupUploaderBundle
Only Gaufrette is used to test the bundle, not the GaufretteBundle.
commit 13dee605501659d1bdcd738f3a9c4e7be97094a0 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 12:29:54 2013 +0200 Only Gaufrette is used to test the bundle, not the GaufretteBundle. diff --git a/composer.json b/composer.json index 9b93984..d59371e 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ }, "require-dev": { - "knplabs/knp-gaufrette-bundle": "0.1.*" + "knplabs/gaufrette": "0.2.*@dev" }, "suggest": {
0
afc344f16e95c15f41a165cc16b76c4492565f12
1up-lab/OneupUploaderBundle
2018
commit afc344f16e95c15f41a165cc16b76c4492565f12 Author: David Greminger <[email protected]> Date: Tue Feb 6 19:09:57 2018 +0100 2018 diff --git a/Resources/meta/LICENSE b/LICENSE similarity index 100% rename from Resources/meta/LICENSE rename to LICENSE diff --git a/README.md b/README.md index c5c5b05..5cad81a 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ License This bundle is under the MIT license. See the complete license in the bundle: - Resources/meta/LICENSE + LICENSE Reporting an issue or a feature request ---------------------------------------
0
ab7bc7c9d5c2ce8e8cd8118372b6a27963d6d3e9
1up-lab/OneupUploaderBundle
Add example of using requestStack in a namer (#377) * Add example of using requestStack in a namer * Prevent path traversal attacks Co-authored-by: Malte Blättermann <[email protected]>
commit ab7bc7c9d5c2ce8e8cd8118372b6a27963d6d3e9 Author: David Greminger <[email protected]> Date: Sun Mar 29 12:12:49 2020 +0200 Add example of using requestStack in a namer (#377) * Add example of using requestStack in a namer * Prevent path traversal attacks Co-authored-by: Malte Blättermann <[email protected]> diff --git a/doc/custom_namer.md b/doc/custom_namer.md index 37be120..5e95a77 100644 --- a/doc/custom_namer.md +++ b/doc/custom_namer.md @@ -126,5 +126,45 @@ class CatNamer implements NamerInterface } } ``` - Every file uploaded through the `Controller` of this mapping will be named with your new directory structure. + +## How to use additional request params for naming? + +Inject the `RequestStack` into your custom `Namer` and call `getCurrentRequest()` on it: + +```php +<?php + +namespace Acme\DemoBundle; + +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; +use Symfony\Component\HttpFoundation\RequestStack; + +class CatNamer implements NamerInterface +{ + private $requestStack; + + public function __construct(RequestStack $requestStack){ + $this->requestStack = $requestStack; + } + + /** + * Creates a catId directory name for the file being uploaded. + * + * @param FileInterface $file + * @return string The directory name. + */ + public function name(FileInterface $file) + { + // Prevent path traversal attacks + $catId = basename($this->requestStack->getCurrentRequest()->get('catId')) + + return sprintf('cat_%s/%s.%s', + $catId, + uniqid(), + $file->getExtension() + ); + } +} +```
0
06f3d9906381bccadf8cc06081632eeb51788cf8
1up-lab/OneupUploaderBundle
Documentation updates
commit 06f3d9906381bccadf8cc06081632eeb51788cf8 Author: David Greminger <[email protected]> Date: Fri Dec 1 17:00:18 2017 +0100 Documentation updates diff --git a/README.md b/README.md index 377fb9d..c76f765 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 **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 **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). diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 2e5f82e..bc3858f 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -5,11 +5,14 @@ The OneupUploaderBundle is a Symfony2 bundle developed and tested for versions 2 ## Prerequisites -This bundle is tested using Symfony 2.4+. +This bundle is tested using Symfony 3.3+. **With Symfony 2.3** If you want to use the bundle with Symfony 2.3, head over to the documentation for [1.3.x](https://github.com/1up-lab/OneupUploaderBundle/blob/release-1.3.x/Resources/doc/index.md). +**With Symfony 2.4.x - 2.8.x** +If you want to use the bundle with Symfony 2.4.x - 2.8.x, head over to the documentation for [1.9.x](https://github.com/1up-lab/OneupUploaderBundle/blob/release/1.9.x/Resources/doc/index.md). + ### Translations If you wish to use the default texts provided with this bundle, you have to make sure that you have translator enabled in your configuration file.
0
da64cb49e81eab38a1226d7c574304429080388d
1up-lab/OneupUploaderBundle
Coding style fixes.
commit da64cb49e81eab38a1226d7c574304429080388d Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:05:07 2013 +0200 Coding style fixes. diff --git a/Uploader/Response/EmptyResponse.php b/Uploader/Response/EmptyResponse.php index 3fa6f6c..de61b42 100644 --- a/Uploader/Response/EmptyResponse.php +++ b/Uploader/Response/EmptyResponse.php @@ -10,5 +10,4 @@ class EmptyResponse extends AbstractResponse { return $this->data; } - } \ No newline at end of file
0
31eb7edacf1a9524d4eee69b8af86cc7dd954654
1up-lab/OneupUploaderBundle
Removed newline after routing configuration
commit 31eb7edacf1a9524d4eee69b8af86cc7dd954654 Author: Jim Schmid <[email protected]> Date: Mon Apr 8 11:40:37 2013 +0300 Removed newline after routing configuration diff --git a/Resources/doc/index.md b/Resources/doc/index.md index df1378e..29a4395 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -80,7 +80,6 @@ To enable the dynamic routes, add the following to your routing configuration fi oneup_uploader: resource: . type: uploader - ``` ### Step 4: Prepare your frontend
0
ff25449a5b050eeaecd43c231f34d4d94d940694
1up-lab/OneupUploaderBundle
Fixed tests
commit ff25449a5b050eeaecd43c231f34d4d94d940694 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:46:04 2013 +0200 Fixed tests diff --git a/Tests/Uploader/Response/UploaderResponseTest.php b/Tests/Uploader/Response/FineUploaderResponseTest.php similarity index 84% rename from Tests/Uploader/Response/UploaderResponseTest.php rename to Tests/Uploader/Response/FineUploaderResponseTest.php index 37728a0..05f3d0a 100644 --- a/Tests/Uploader/Response/UploaderResponseTest.php +++ b/Tests/Uploader/Response/FineUploaderResponseTest.php @@ -2,13 +2,13 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Response; -use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; +use Oneup\UploaderBundle\Uploader\Response\FineUploaderResponse; -class TestUploaderResponse extends \PHPUnit_Framework_TestCase +class TestFineUploaderResponse extends \PHPUnit_Framework_TestCase { public function testCreationOfResponse() { - $response = new UploaderResponse(); + $response = new FineUploaderResponse(); $this->assertTrue($response->getSuccess()); $this->assertNull($response->getError()); @@ -16,7 +16,7 @@ class TestUploaderResponse extends \PHPUnit_Framework_TestCase public function testFillOfResponse() { - $response = new UploaderResponse(); + $response = new FineUploaderResponse(); $cat = 'is grumpy'; $dog = 'has no idea'; @@ -46,7 +46,7 @@ class TestUploaderResponse extends \PHPUnit_Framework_TestCase public function testError() { - $response = new UploaderResponse(); + $response = new FineUploaderResponse(); $response->setError('This response is grumpy'); $this->assertEquals($response->getError(), 'This response is grumpy'); @@ -54,7 +54,7 @@ class TestUploaderResponse extends \PHPUnit_Framework_TestCase public function testOverwriteOfInternals() { - $response = new UploaderResponse(); + $response = new FineUploaderResponse(); $response['success'] = false; $response['error'] = 42;
0
55fc9c277c8e577514b37c816c1dab27a5fd193f
1up-lab/OneupUploaderBundle
Include mime type with file upload When reading the file mime type through php, the information is still in place. However, when using AWS S3, the uploaded object's metadata always defaults to "application/octet-stream" inside of AWS. Including the "mimetype" option with the "putstream" function seems to correct this problem; setting the AWS object to the correct content type.
commit 55fc9c277c8e577514b37c816c1dab27a5fd193f Author: Brandon Pearson <[email protected]> Date: Wed Dec 7 20:16:51 2016 -0600 Include mime type with file upload When reading the file mime type through php, the information is still in place. However, when using AWS S3, the uploaded object's metadata always defaults to "application/octet-stream" inside of AWS. Including the "mimetype" option with the "putstream" function seems to correct this problem; setting the AWS object to the correct content type. diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index 9a98720..aa2fa61 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -45,7 +45,9 @@ class FlysystemStorage implements StorageInterface } $stream = fopen($file->getPathname(), 'r+'); - $this->filesystem->putStream($name, $stream); + $this->filesystem->putStream($name, $stream, array( + 'mimetype' => $file->getMimeType() + )); if (is_resource($stream)) { fclose($stream); }
0
c97fd9837d1cf4496465efa9d171458df44e33a9
1up-lab/OneupUploaderBundle
Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle
commit c97fd9837d1cf4496465efa9d171458df44e33a9 (from c9c4c1946b430f1d1226958176eb2a26d71cc5e4) Merge: c9c4c19 e7b6326 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:26:16 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Resources/doc/frontend_fancyupload.md b/Resources/doc/frontend_fancyupload.md index bad221a..da918c2 100644 --- a/Resources/doc/frontend_fancyupload.md +++ b/Resources/doc/frontend_fancyupload.md @@ -3,6 +3,8 @@ Use FancyUpload Download [FancyUpload](http://digitarald.de/project/fancyupload/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}` and include the FlashUploader file (`path`). +> If you have any idea on how to make a minimal example about the usage of FancyUpload, consider creating a pull-request. + ```html <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.2/mootools.js"></script> @@ -103,4 +105,4 @@ oneup_uploader: frontend: fancyupload ``` -Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. commit c97fd9837d1cf4496465efa9d171458df44e33a9 (from e7b632698fead9ca6e15bf567aac82249bbd97c4) Merge: c9c4c19 e7b6326 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:26:16 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 311c4fa..981a4a4 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -14,9 +14,6 @@ class BlueimpController extends AbstractChunkedController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index ee69af0..c2e32bd 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -13,9 +13,6 @@ class FancyUploadController extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index 7c94966..ea18f52 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -13,9 +13,6 @@ class UploadifyController extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index 8ade2ec..b063e92 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -13,9 +13,6 @@ class YUI3Controller extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files;
0
9d8ebc416365c777fad846c1974be0e0af272e22
1up-lab/OneupUploaderBundle
min(\INF, somewhat below INF) was always returning INF.
commit 9d8ebc416365c777fad846c1974be0e0af272e22 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 16:05:36 2013 +0100 min(\INF, somewhat below INF) was always returning INF. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 04d1ca6..fc02a08 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->scalarNode('storage')->isRequired()->end() - ->scalarNode('max_size')->defaultNull()->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() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index e844c04..91e4520 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -44,7 +44,7 @@ class OneupUploaderExtension extends Extension $mapping['directory_prefix'] = $key; } - $mapping['max_size'] = min(min($mapping['max_size'], ini_get('upload_max_filesize')), ini_get('post_max_size')); + $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); $mapping['storage'] = $this->registerStorageService($container, $mapping); $this->registerServicesPerMap($container, $key, $mapping); @@ -128,4 +128,29 @@ class OneupUploaderExtension extends Extension ->setScope('request') ; } + + 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) + { + case 'g': $input *= 1024; + case 'm': $input *= 1024; + case 'k': $input *= 1024; + } + + return $input; + } } \ No newline at end of file diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php index 93b22e6..138d692 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Orphanage/Orphanage.php @@ -4,6 +4,7 @@ namespace Oneup\UploaderBundle\Uploader\Orphanage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; @@ -48,7 +49,7 @@ class Orphanage implements OrphanageInterface foreach($finder as $file) { - $uploaded[] = $this->storage->upload($file); + $uploaded[] = $this->storage->upload(new UploadedFile($file->getPathname(), $file->getBasename(), null, null, null, true)); if(!$keep) { diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 77464be..cfc5d35 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -2,7 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\Finder\SplFileInfo as File; +use Symfony\Component\HttpFoundation\File\File; use Gaufrette\Stream\Local as LocalStream; use Gaufrette\StreamMode; use Gaufrette\Filesystem; diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 0e9b830..1e4a287 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -2,10 +2,10 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\Finder\SplFileInfo as File; +use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { - public function upload(\SplFileInfo $file, $name); + public function upload(File $file, $name); public function remove(File $file); } \ No newline at end of file
0
f7c464f85eabd4b108f638a9daf9f3a17ac57103
1up-lab/OneupUploaderBundle
Basic uploading of a file, using the gaufrette LocalStream.
commit f7c464f85eabd4b108f638a9daf9f3a17ac57103 Author: Jim Schmid <[email protected]> Date: Tue Mar 12 18:18:57 2013 +0100 Basic uploading of a file, using the gaufrette LocalStream. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 3a5a4e9..e922323 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -2,6 +2,10 @@ namespace Oneup\UploaderBundle\Controller; +use Symfony\Component\HttpFoundation\JsonResponse; +use Gaufrette\Stream\Local as LocalStream; +use Gaufrette\StreamMode; + use Oneup\UploaderBundle\Controller\UploadControllerInterface; class UploaderController implements UploadControllerInterface @@ -29,13 +33,28 @@ class UploaderController implements UploadControllerInterface // get filebag from request $files = $this->request->files; - var_dump(get_class($this->storage)); die(); - foreach($files as $file) { + $name = $this->namer->name($file); + $path = $file->getPathname(); + + $src = new LocalStream($path); + $dst = $this->storage->createStream($name); + + $src->open(new StreamMode('rb+')); + $dst->open(new StreamMode('ab+')); + + while(!$src->eof()) + { + $data = $src->read(100000); + $written = $dst->write($data); + } + + $dst->close(); + $src->close(); } - die(); + return new JsonResponse(array('success' => true)); } protected function handleChunkedUpload()
0
9f1dd1249fc77ad24618c9816d8e936bdbadaa0b
1up-lab/OneupUploaderBundle
Fixed RouteLoader test according to the new controller loading mechanism.
commit 9f1dd1249fc77ad24618c9816d8e936bdbadaa0b Author: Jim Schmid <[email protected]> Date: Mon Apr 8 10:28:03 2013 +0200 Fixed RouteLoader test according to the new controller loading mechanism. diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 4bd7ca9..4145b86 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -8,19 +8,18 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase { public function testRouteLoader() { - $routeLoader = new RouteLoader(); - - // for code coverage - $this->assertTrue($routeLoader->supports('grumpy', 'uploader')); - $cat = 'GrumpyCatController'; $dog = 'HelloThisIsDogController'; + + $routeLoader = new RouteLoader(array( + 'cat' => $cat, + 'dog' => $dog + )); - // add a new controller and check if the route will be added - $routeLoader->addController('cat', $cat); - $routeLoader->addController('dog', $dog); $routes = $routeLoader->load(null); - + + // for code coverage + $this->assertTrue($routeLoader->supports('grumpy', 'uploader')); $this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $routes); $this->assertCount(2, $routes);
0
f420fff5bc3ec910e925ceae15bc513b419693f2
1up-lab/OneupUploaderBundle
Adding ability to pass HTTP status code to response in AbstractController. This allows to take advantage of HTTP codes for error handling. Added ErrorHandler for Dropzone
commit f420fff5bc3ec910e925ceae15bc513b419693f2 Author: Pereyaslov Konstantin <[email protected]> Date: Wed Nov 5 05:27:43 2014 +0300 Adding ability to pass HTTP status code to response in AbstractController. This allows to take advantage of HTTP codes for error handling. Added ErrorHandler for Dropzone diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index a551ba8..b150214 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -183,13 +183,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); + $response = new JsonResponse($data, $statusCode); $response->headers->set('Vary', 'Accept'); if (!in_array('application/json', $request->getAcceptableContentTypes())) { diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 0c8a5b0..f8cf580 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -14,15 +14,16 @@ class DropzoneController extends AbstractController $request = $this->container->get('request'); $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); } } - return $this->createSupportedJsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble(), $statusCode); } } 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/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; + } +}
0
148be73b118621588fb7a36967e7140d201ea3a9
1up-lab/OneupUploaderBundle
Refactored NamerInterface. Second parameter is now an optional prefix, instead of a mapping array. Loose cupling, yey.
commit 148be73b118621588fb7a36967e7140d201ea3a9 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 08:34:03 2013 +0100 Refactored NamerInterface. Second parameter is now an optional prefix, instead of a mapping array. Loose cupling, yey. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 631ce7e..7314147 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -32,10 +32,7 @@ class UploaderController implements UploadControllerInterface foreach($files as $file) { - // get name and directory and put them together - $name = $this->namer->name($file); - $name = sprintf('%s/%s', $this->config['directory_prefix'], $name); - + $name = $this->namer->name($file, $this->config['directory_prefix']); $this->storage->upload($file, $name); } diff --git a/Uploader/Naming/NamerInterface.php b/Uploader/Naming/NamerInterface.php index 4a7882c..7bbf4d0 100644 --- a/Uploader/Naming/NamerInterface.php +++ b/Uploader/Naming/NamerInterface.php @@ -6,5 +6,5 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; interface NamerInterface { - public function name(UploadedFile $file, array $mapping = array()); + public function name(UploadedFile $file, $prefix = null); } \ No newline at end of file diff --git a/Uploader/Naming/UniqidNamer.php b/Uploader/Naming/UniqidNamer.php index c9b918f..9d9c8b9 100644 --- a/Uploader/Naming/UniqidNamer.php +++ b/Uploader/Naming/UniqidNamer.php @@ -7,8 +7,10 @@ use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; class UniqidNamer implements NamerInterface { - public function name(UploadedFile $file, array $mapping = array()) + public function name(UploadedFile $file, $prefix = null) { - return sprintf('%s.%s', uniqid(), $file->guessExtension()); + $prefix = !is_null($prefix) ? $prefix . '/' : ''; + + return sprintf('%s%s.%s', $prefix, uniqid(), $file->guessExtension()); } } \ No newline at end of file
0
8a922f6a0ac6f38bffe22a3f2a0b10f3a674ed74
1up-lab/OneupUploaderBundle
Fix for FlysystemStorage ignoring path on upload Added a test that demonstrates the issue.
commit 8a922f6a0ac6f38bffe22a3f2a0b10f3a674ed74 Author: snarktooth <[email protected]> Date: Mon Sep 11 18:06:55 2017 -0500 Fix for FlysystemStorage ignoring path on upload Added a test that demonstrates the issue. diff --git a/Tests/Uploader/Storage/FlysystemStorageTest.php b/Tests/Uploader/Storage/FlysystemStorageTest.php index bdd43e9..121a7ec 100644 --- a/Tests/Uploader/Storage/FlysystemStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemStorageTest.php @@ -53,6 +53,22 @@ class FlysystemStorageTest extends \PHPUnit_Framework_TestCase } } + public function testUploadWithPath() + { + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); + $this->storage->upload($payload, 'notsogrumpyanymore.jpeg', 'cat'); + + $finder = new Finder(); + $finder->in($this->directory)->files(); + + $this->assertCount(1, $finder); + + foreach ($finder as $file) { + $this->assertEquals($file->getFilename(), 'notsogrumpyanymore.jpeg'); + $this->assertEquals($file->getSize(), 1024); + } + } + public function tearDown() { $filesystem = new Filesystem(); diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index aa2fa61..08e6206 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -45,7 +45,7 @@ class FlysystemStorage implements StorageInterface } $stream = fopen($file->getPathname(), 'r+'); - $this->filesystem->putStream($name, $stream, array( + $this->filesystem->putStream($path, $stream, array( 'mimetype' => $file->getMimeType() )); if (is_resource($stream)) {
0
bd400e893294d1f6fca31fb2de252c7eb94d7da4
1up-lab/OneupUploaderBundle
broke configuration up even more fro scrutinizer
commit bd400e893294d1f6fca31fb2de252c7eb94d7da4 Author: mitom <[email protected]> Date: Thu Oct 10 16:11:07 2013 +0200 broke configuration up even more fro scrutinizer diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index b5e2ab5..a86036f 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -42,7 +42,7 @@ class OneupUploaderExtension extends Extension // handle mappings foreach ($this->config['mappings'] as $key => $mapping) { - $this->processMapping($key, $mapping); + $controllers[$key] = $this->processMapping($key, $mapping); } $container->setParameter('oneup_uploader.controllers', $controllers); @@ -62,15 +62,26 @@ class OneupUploaderExtension extends Extension $this->getMaxUploadSize($mapping['max_size']) : $mapping['max_size'] ; + $controllerName = $this->createController($key, $mapping); + $this->verifyPhpVersion($mapping); + + return array($controllerName, array( + 'enable_progress' => $mapping['enable_progress'], + 'enable_cancelation' => $mapping['enable_cancelation'] + )); + } + + protected function createController($key, $config) + { // create the storage service according to the configuration - $storageService = $this->createStorageService($mapping['storage'], $key, isset($mapping['orphanage']) ? :null); + $storageService = $this->createStorageService($config['storage'], $key, isset($config['orphanage']) ? :null); - if ($mapping['frontend'] != 'custom') { + if ($config['frontend'] != 'custom') { $controllerName = sprintf('oneup_uploader.controller.%s', $key); - $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $mapping['frontend']); + $controllerType = sprintf('%%oneup_uploader.controller.%s.class%%', $config['frontend']); } else { - $customFrontend = $mapping['custom_frontend']; + $customFrontend = $config['custom_frontend']; $controllerName = sprintf('oneup_uploader.controller.%s', $customFrontend['name']); $controllerType = $customFrontend['class']; @@ -79,9 +90,7 @@ class OneupUploaderExtension extends Extension 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 = is_null($mapping['error_handler']) ? - new Reference('oneup_uploader.error_handler.'.$mapping['frontend']) : - new Reference($mapping['error_handler']); + $errorHandler = $this->createErrorHandler($config); // create controllers based on mapping $this->container @@ -90,23 +99,30 @@ class OneupUploaderExtension extends Extension ->addArgument(new Reference('service_container')) ->addArgument($storageService) ->addArgument($errorHandler) - ->addArgument($mapping) + ->addArgument($config) ->addArgument($key) ->addTag('oneup_uploader.routable', array('type' => $key)) ->setScope('request') ; - if ($mapping['enable_progress'] || $mapping['enable_cancelation']) { + 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']); + } + + 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.'); } } - - $controllers[$key] = array($controllerName, array( - 'enable_progress' => $mapping['enable_progress'], - 'enable_cancelation' => $mapping['enable_cancelation'] - )); } protected function createChunkStorageService()
0
b8d2c324d1a89fca7eb46dcf00a13bd0c3bbd17d
1up-lab/OneupUploaderBundle
Fetch an exception if the orphanage has never been used.
commit b8d2c324d1a89fca7eb46dcf00a13bd0c3bbd17d Author: Jim Schmid <[email protected]> Date: Sat Apr 6 21:23:41 2013 +0200 Fetch an exception if the orphanage has never been used. diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/OrphanageStorage.php index 6477358..1248f1c 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -39,15 +39,23 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte public function uploadFiles() { $filesystem = new Filesystem(); - $files = $this->getFiles(); - $return = array(); - foreach($files as $file) + try { - $return[] = $this->storage->upload(new File($file->getPathname()), str_replace($this->getFindPath(), '', $file)); - } + $files = $this->getFiles(); + $return = array(); - return $return; + foreach($files as $file) + { + $return[] = $this->storage->upload(new File($file->getPathname()), str_replace($this->getFindPath(), '', $file)); + } + + return $return; + } + catch(\Exception $e) + { + return array(); + } } protected function getFiles()
0
a2f48b71a5cd3c4e4b75bff364dfb588660ab8f9
1up-lab/OneupUploaderBundle
Update FineUploader official manual link (#319)
commit a2f48b71a5cd3c4e4b75bff364dfb588660ab8f9 Author: Léo <[email protected]> Date: Fri Feb 16 16:26:03 2018 +0100 Update FineUploader official manual link (#319) diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md index 22fbb16..8519f97 100644 --- a/Resources/doc/frontend_fineuploader.md +++ b/Resources/doc/frontend_fineuploader.md @@ -33,7 +33,7 @@ oneup_uploader: frontend: fineuploader ``` -Be sure to check out the [official manual](https://github.com/Widen/fine-uploader/blob/master/readme.md) for details on the configuration. +Be sure to check out the [official manual](https://github.com/FineUploader/fine-uploader/blob/master/README.md) for details on the configuration. Next steps ----------
0
515132a404c312ee0beb9dd86263c15ce0933788
1up-lab/OneupUploaderBundle
Added a switch to globally enable and disable chunks. This is necesseray to determine if a developer should provide a storage service.
commit 515132a404c312ee0beb9dd86263c15ce0933788 Author: Jim Schmid <[email protected]> Date: Fri Mar 15 16:36:45 2013 +0100 Added a switch to globally enable and disable chunks. This is necesseray to determine if a developer should provide a storage service. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c3f4575..9d98300 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -17,7 +17,8 @@ class Configuration implements ConfigurationInterface ->arrayNode('chunks') ->addDefaultsIfNotSet() ->children() - ->scalarNode('directory')->end() + ->booleanNode('enabled')->defaultFalse()->end() + ->scalarNode('storage')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->end() ->end()
0
c8d119534029226b874ae8ccaef5e265fa137d06
1up-lab/OneupUploaderBundle
Merge pull request #87 from FunkeMT/patch-1 Fixed typo in orphanage.md
commit c8d119534029226b874ae8ccaef5e265fa137d06 (from 2b98963842287be1f7e1c44befbb59148d66b2d9) Merge: 2b98963 b1543bd Author: Jim Schmid <[email protected]> Date: Mon Feb 17 17:06:45 2014 +0100 Merge pull request #87 from FunkeMT/patch-1 Fixed typo in orphanage.md diff --git a/Resources/doc/orphanage.md b/Resources/doc/orphanage.md index b4051a2..b489535 100644 --- a/Resources/doc/orphanage.md +++ b/Resources/doc/orphanage.md @@ -76,7 +76,7 @@ and default to ```orphanage```. ## Clean up The `OrphanageManager` can be forced to clean up orphans by using the command provided by the OneupUploaderBundle. - $> php app/console oneup:uploader:clean-orphans + $> php app/console oneup:uploader:clear-orphans This parameter will clean all orphaned files older than the `maxage` value in your configuration.
0
52303cf5d4387b7f320ffb6fd46a0687a51d98ee
1up-lab/OneupUploaderBundle
Fix unnamed directory when uploading to Amazon S3
commit 52303cf5d4387b7f320ffb6fd46a0687a51d98ee Author: Diego Lázaro <[email protected]> Date: Sat Apr 16 18:38:05 2016 +0200 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;
0
18a7f3194bfd8a451e194410bc24a0620bae3acd
1up-lab/OneupUploaderBundle
Merge pull request #220 from JHGitty/patch-5 Fix typo
commit 18a7f3194bfd8a451e194410bc24a0620bae3acd (from f5acda92ea3d6aa482408d1ef65a69f46efb3802) Merge: f5acda9 fbaf18e Author: David Greminger <[email protected]> Date: Mon Feb 8 08:26:50 2016 +0100 Merge pull request #220 from JHGitty/patch-5 Fix typo diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index fd6d87a..c577309 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -1,7 +1,7 @@ Using Chunked Uploads ===================== -Fine Uploader comes bundled with the possibility to use so called chunked uploads. If enabed, an uploaded file will be split into equal sized blobs which are sequentially uploaded afterwards. In order to use this feature, be sure to enable it in the frontend. +Fine Uploader comes bundled with the possibility to use so called chunked uploads. If enabled, an uploaded file will be split into equal sized blobs which are sequentially uploaded afterwards. In order to use this feature, be sure to enable it in the frontend. ```js $(document).ready(function()
0
9fa868f0f92759d421787dea82c53274e83063b1
1up-lab/OneupUploaderBundle
Merge pull request #225 from SrgSteak/patch-1 Upload large files with flysystem
commit 9fa868f0f92759d421787dea82c53274e83063b1 (from 0abd7065d1e36193147ba5cbaf53f3e5576389ae) Merge: 0abd706 394a7ab Author: Jim Schmid <[email protected]> Date: Thu Feb 11 10:03:43 2016 +0100 Merge pull request #225 from SrgSteak/patch-1 Upload large files with flysystem diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index 4d0212d..9a98720 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -44,7 +44,11 @@ class FlysystemStorage implements StorageInterface } } - $this->filesystem->put($name, file_get_contents($file)); + $stream = fopen($file->getPathname(), 'r+'); + $this->filesystem->putStream($name, $stream); + if (is_resource($stream)) { + fclose($stream); + } if ($file instanceof FlysystemFile) { $file->delete();
0
e36a629ed6584866ce8ddd22aa9f511056920af5
1up-lab/OneupUploaderBundle
Rename namer.md to custom_namer.md
commit e36a629ed6584866ce8ddd22aa9f511056920af5 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 09:40:25 2013 +0300 Rename namer.md to custom_namer.md 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.
0
bb824ccf4d051d19041ed393325ecb42335b0c33
1up-lab/OneupUploaderBundle
The main repository of fine-uploader has changed.
commit bb824ccf4d051d19041ed393325ecb42335b0c33 Author: Jim Schmid <[email protected]> Date: Thu Mar 28 17:41:20 2013 +0100 The main repository of fine-uploader has changed. diff --git a/composer.json b/composer.json index f9fa6d5..be9a578 100644 --- a/composer.json +++ b/composer.json @@ -13,13 +13,13 @@ ], "repositories": { - "file-uploader": { + "fine-uploader": { "type": "package", "package": { - "name": "valums/file-uploader", - "version": "3.3.0", + "name": "widen/fine-uploader", + "version": "3.3.1", "source": { - "url": "git://github.com/valums/file-uploader.git", + "url": "git://github.com/Widen/fine-uploader.git", "type": "git", "reference": "origin/master" } @@ -32,7 +32,7 @@ "symfony/filesystem": ">=2.0.16,<2.3-dev", "symfony/event-dispatcher": ">=2.0.16,<2.3-dev", "knplabs/knp-gaufrette-bundle": "0.1.*", - "valums/file-uploader": "3.3.*" + "widen/fine-uploader": "3.3.*" }, "autoload": {
0
9bc555951e5f882a1f6e7108202f4fff666ecd10
1up-lab/OneupUploaderBundle
Fixed tests (static container)
commit 9bc555951e5f882a1f6e7108202f4fff666ecd10 Author: David Greminger <[email protected]> Date: Tue Jun 5 10:57:00 2018 +0200 Fixed tests (static container) diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index d68d658..d092e58 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -15,8 +15,8 @@ abstract class AbstractControllerTest extends WebTestCase * @var Client */ protected $client; - protected $container; protected $requestHeaders; + protected static $container; /** * @var UploaderHelper @@ -26,14 +26,14 @@ abstract class AbstractControllerTest extends WebTestCase public function setUp() { $this->client = static::createClient(); - $this->container = $this->client->getContainer(); - $this->helper = $this->container->get('oneup_uploader.templating.uploader_helper'); + self::$container = $this->client->getContainer(); + $this->helper = self::$container->get('oneup_uploader.templating.uploader_helper'); $this->createdFiles = []; $this->requestHeaders = [ 'HTTP_ACCEPT' => 'application/json', ]; - $this->container->get('router')->getRouteCollection()->all(); + self::$container->get('router')->getRouteCollection()->all(); } public function tearDown() @@ -121,15 +121,14 @@ abstract class AbstractControllerTest extends WebTestCase protected function getUploadedFiles() { - $env = $this->container->getParameter('kernel.environment'); - $root = $this->container->getParameter('kernel.root_dir'); + $env = self::$container->getParameter('kernel.environment'); + $root = self::$container->getParameter('kernel.root_dir'); // assemble path $path = sprintf('%s/cache/%s/upload', $root, $env); $finder = new Finder(); - $files = $finder->in($path); - return $files; + return $finder->in($path); } }
0
59c1450d566708ae7907e6de486941db9f24d57c
1up-lab/OneupUploaderBundle
Merge pull request #10 from 1up-lab/moouploader Implemented Mooupload backend.
commit 59c1450d566708ae7907e6de486941db9f24d57c (from ea3774346b722a84aa48e8181751b23b255f837c) Merge: ea37743 6af40c4 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 05:33:52 2013 -0700 Merge pull request #10 from 1up-lab/moouploader Implemented Mooupload backend. diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php new file mode 100644 index 0000000..949663d --- /dev/null +++ b/Controller/MooUploadController.php @@ -0,0 +1,122 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; + +use Oneup\UploaderBundle\Controller\AbstractChunkedController; +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(); + $files = $request->files; + $headers = $request->headers; + + // we have to get access to this object in another method + $this->response = $response; + + // 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); + + // check if uploaded by chunks + $chunked = $headers->get('content-length') < $headers->get('x-file-size'); + + try + { + $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + + // 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')); + $response->setUploadedName($uploadFileName); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + 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 + { + // loop through every file that has been uploaded before + foreach($chunkManager->getChunks($uuid) as $file) + { + $size += $file->getSize(); + } + } + 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) + { + $ints += ord($char); + } + + return $ints; + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index b97806e..b00f847 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/README.md b/README.md index dea7969..558ff06 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ The OneupUploaderBundle adds support for handling file uploads using one of the * [YUI3 Uploader](http://yuilibrary.com/yui/docs/uploader/) * [Uploadify](http://www.uploadify.com/) * [FancyUpload](http://digitarald.de/project/fancyupload/) +* [MooUpload](https://github.com/juanparati/MooUpload) Features included: diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 1a1108d..8b1cc48 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -16,6 +16,7 @@ <parameter key="oneup_uploader.controller.uploadify.class">Oneup\UploaderBundle\Controller\UploadifyController</parameter> <parameter key="oneup_uploader.controller.yui3.class">Oneup\UploaderBundle\Controller\YUI3Controller</parameter> <parameter key="oneup_uploader.controller.fancyupload.class">Oneup\UploaderBundle\Controller\FancyUploadController</parameter> + <parameter key="oneup_uploader.controller.mooupload.class">Oneup\UploaderBundle\Controller\MooUploadController</parameter> </parameters> <services> diff --git a/Resources/doc/frontend_mooupload.md b/Resources/doc/frontend_mooupload.md new file mode 100644 index 0000000..5dfa4cb --- /dev/null +++ b/Resources/doc/frontend_mooupload.md @@ -0,0 +1,35 @@ +Use MooUpload in your Symfony2 application +========================================== + +Download [MooUpload](https://github.com/juanparati/MooUpload) and include it in your template. Connect the `action` property to the dynamic route `_uploader_{mapping_name}`. + +```html +<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.0/mootools-yui-compressed.js"></script> +<script type="text/javascript" src="http://www.livespanske.com/labs/MooUpload/MooUpload.js"></script> +<script type="text/javascript"> + +window.addEvent("domready", function() +{ + var myUpload = new MooUpload("fileupload", + { + action: "{{ path('_uploader_gallery') }}", + method: "auto" + }); +}); +</script> + +<div id="fileupload"></div> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + 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 diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 663f91e..357df8f 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -95,6 +95,7 @@ So if you take the mapping described before, the generated route name would be ` * [Use YUI3 Uploader](frontend_yui3.md) * [Use Uploadify](frontend_uploadify.md) * [Use FancyUpload](frontend_fancyupload.md) +* [Use MooUpload](frontend_mooupload.md) This is of course a very minimal setup. Be sure to include stylesheets for Fine Uploader if you want to use them. diff --git a/Uploader/Response/MooUploadResponse.php b/Uploader/Response/MooUploadResponse.php new file mode 100644 index 0000000..36e8572 --- /dev/null +++ b/Uploader/Response/MooUploadResponse.php @@ -0,0 +1,109 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class MooUploadResponse extends AbstractResponse +{ + protected $id; + protected $name; + protected $size; + protected $error; + protected $finish; + protected $uploadedName; + + public function __construct() + { + $this->finish = true; + $this->error = 0; + + parent::__construct(); + } + + public function assemble() + { + $data = $this->data; + + $data['id'] = $this->id; + $data['name'] = $this->name; + $data['size'] = $this->size; + $data['error'] = $this->error; + $data['finish'] = $this->finish; + $data['upload_name'] = $this->uploadedName; + + return $data; + } + + public function setId($id) + { + $this->id = $id; + + return $this; + } + + public function getId() + { + return $this->id; + } + + public function setName($name) + { + $this->name = $name; + + return $this; + } + + public function getName() + { + return $this->id; + } + + public function setSize($size) + { + $this->size = $size; + + return $this; + } + + public function getSize() + { + return $this->size; + } + + public function setError($error) + { + $this->error = $error; + + return $this; + } + + public function getError() + { + return $this->error; + } + + public function setFinish($finish) + { + $this->finish = $finish; + + return $this; + } + + public function getFinish() + { + return $this->finish; + } + + public function setUploadedName($name) + { + $this->uploadedName = $name; + + return $this; + } + + public function getUploadedName() + { + return $this->uploadedName; + } +} \ No newline at end of file commit 59c1450d566708ae7907e6de486941db9f24d57c (from 6af40c4fc610dd774417bf2326d76f3e79099ac2) Merge: ea37743 6af40c4 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 05:33:52 2013 -0700 Merge pull request #10 from 1up-lab/moouploader Implemented Mooupload backend. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 311c4fa..981a4a4 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -14,9 +14,6 @@ class BlueimpController extends AbstractChunkedController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index ee69af0..c2e32bd 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -13,9 +13,6 @@ class FancyUploadController extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index 7c94966..ea18f52 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -13,9 +13,6 @@ class UploadifyController extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index 8ade2ec..b063e92 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -13,9 +13,6 @@ class YUI3Controller extends AbstractController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files; diff --git a/Resources/doc/frontend_fancyupload.md b/Resources/doc/frontend_fancyupload.md index bad221a..da918c2 100644 --- a/Resources/doc/frontend_fancyupload.md +++ b/Resources/doc/frontend_fancyupload.md @@ -3,6 +3,8 @@ Use FancyUpload Download [FancyUpload](http://digitarald.de/project/fancyupload/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}` and include the FlashUploader file (`path`). +> If you have any idea on how to make a minimal example about the usage of FancyUpload, consider creating a pull-request. + ```html <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.2/mootools.js"></script> @@ -103,4 +105,4 @@ oneup_uploader: frontend: fancyupload ``` -Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](http://digitarald.de/project/fancyupload/) for details on the configuration. diff --git a/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index 2cd35ea..4d52bb9 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -20,7 +20,6 @@ class FilesystemStorage implements StorageInterface { $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); diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index fac7bbe..5823d50 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -6,6 +6,7 @@ use Symfony\Component\HttpFoundation\File\File; use Gaufrette\Stream\Local as LocalStream; use Gaufrette\StreamMode; use Gaufrette\Filesystem; +use Gaufrette\Adapter\MetadataSupporter; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; @@ -20,9 +21,13 @@ class GaufretteStorage implements StorageInterface public function upload(File $file, $name, $path = null) { - $name = is_null($name) ? $file->getRelativePathname() : $name; $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())); + } + $src = new LocalStream($file->getPathname()); $dst = $this->filesystem->createStream($path); diff --git a/composer.json b/composer.json index 9b93984..a8ae808 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,8 @@ { "name": "oneup/uploader-bundle", "type": "symfony-bundle", - "description": "widen/file-uploader integration", - "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans"], + "description": "Handle multi file uploads. Features included: Chunked upload, Orphans management, Gaufrette support...", + "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload"], "homepage": "http://1up.io", "license": "MIT", "authors": [ @@ -18,7 +18,7 @@ }, "require-dev": { - "knplabs/knp-gaufrette-bundle": "0.1.*" + "knplabs/gaufrette": "0.2.*@dev" }, "suggest": {
0
8af488c0f35a8e08da2a409bfc9be595e915531b
1up-lab/OneupUploaderBundle
Update README.md
commit 8af488c0f35a8e08da2a409bfc9be595e915531b Author: Thomas Landauer <[email protected]> Date: Fri Dec 23 14:52:44 2016 +0100 Update README.md diff --git a/README.md b/README.md index b6b3992..7f5b15e 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ 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). -* [jQuery File Upload](http://blueimp.github.io/jQuery-File-Upload/) * [Dropzone](http://www.dropzonejs.com/) +* [jQuery File Upload](http://blueimp.github.io/jQuery-File-Upload/) * [Plupload](http://www.plupload.com/) * [FineUploader](http://fineuploader.com/) * [FancyUpload](http://digitarald.de/project/fancyupload/) (based on MooTools)
0
829d3e48ae681619d011cb000e965dcf443f4293
1up-lab/OneupUploaderBundle
Merge pull request #152 from Schyzophrenic/patch-1 [DOC] How to move specific files out of the orphanage
commit 829d3e48ae681619d011cb000e965dcf443f4293 (from 36de4a72e1cbb4e29d11b2046becdea5664a9ea9) Merge: 36de4a7 56bc64a Author: Jim Schmid <[email protected]> Date: Wed Mar 11 08:03:46 2015 +0100 Merge pull request #152 from Schyzophrenic/patch-1 [DOC] How to move specific files out of the orphanage diff --git a/Resources/doc/orphanage.md b/Resources/doc/orphanage.md index 6848615..9e4db06 100644 --- a/Resources/doc/orphanage.md +++ b/Resources/doc/orphanage.md @@ -53,6 +53,18 @@ class AcmeController extends Controller You will get an array containing the moved files. +Note that you can move only one or a set of defined files out of the orphanage by passing an array to $manager->getFiles(). +For instance, you can use this to move a specific file: +```php + // get files + $files = $manager->getFiles(); + + // reduce the scope of the Finder object to what you want + $files->files()->name($filename); + $manager->uploadFiles(iterator_to_array($files)); +``` +In this example, $filename is the name of the file you want to move out of the orphanage. + > If you are using Gaufrette, these files are instances of `Gaufrette\File`, otherwise `SplFileInfo`. ## Configure the Orphanage commit 829d3e48ae681619d011cb000e965dcf443f4293 (from 56bc64a5db84379ef6cc42c471595a3e5d0182df) Merge: 36de4a7 56bc64a Author: Jim Schmid <[email protected]> Date: Wed Mar 11 08:03:46 2015 +0100 Merge pull request #152 from Schyzophrenic/patch-1 [DOC] How to move specific files out of the orphanage 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; } } diff --git a/Resources/meta/LICENSE b/Resources/meta/LICENSE index 44d421f..bebab95 100644 --- a/Resources/meta/LICENSE +++ b/Resources/meta/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2013 1up GmbH +Copyright (c) 2015 1up GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -16,4 +16,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file +THE SOFTWARE.
0
ffbdf2fd02a8e2957b719fd3ae82a3d9f2fa1daa
1up-lab/OneupUploaderBundle
Further documented the changed events.
commit ffbdf2fd02a8e2957b719fd3ae82a3d9f2fa1daa Author: Jim Schmid <[email protected]> Date: Thu Jun 20 19:59:21 2013 +0200 Further documented the changed events. diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index dcb0343..e3cda00 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -77,5 +77,17 @@ The Event object provides the following methods. * `getFile`: Get the uploaded file. Is either an instance of `Gaufrette\File` or `Symfony\Component\HttpFoundation\File\File`. * `getRequest`: Get the current request including custom variables. +* `getResponse`: Get the response object to add custom return data. * `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. \ No newline at end of file +* `getConfig`: Get the config of the mapping. + +## Using chunked uploads +If you are using chunked uploads and hook into the `oneup_uploader.post_chunk_upload` event, you will get `PostChunkUploadEvent` in your listeners. This Event type differs from the previously introduced ones. You'll have the following methods. + + +* `getChunk`: Get the chunk file. Is an instance of `Symfony\Component\HttpFoundation\File\File`. +* `getRequest`: Get the current request including custom variables. +* `getResponse`: Get the response object to add custom return data. +* `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. diff --git a/Resources/doc/events.md b/Resources/doc/events.md index a7a5ff5..a789691 100644 --- a/Resources/doc/events.md +++ b/Resources/doc/events.md @@ -8,7 +8,7 @@ For a list of general Events, you can always have a look at the `UploadEvents.ph In case you are using chunked uploads on your frontend, you can listen to: -* `oneup_uploader.post_chunk_upload` Will be dispatched after a chunk has been uploaded (including the last and assembled one) +* `oneup_uploader.post_chunk_upload` Will be dispatched after a chunk has been uploaded. The Event itself has a property `isLast` which shows if this is the last chunk for the uploaded file. Moreover this bundles also dispatches some special kind of generic events you can listen to.
0
156f67be4e81d80c5da18050b14bf91dfaa6c7cf
1up-lab/OneupUploaderBundle
CS fixes.
commit 156f67be4e81d80c5da18050b14bf91dfaa6c7cf Author: Jim Schmid <[email protected]> Date: Fri Aug 9 16:55:24 2013 +0200 CS fixes. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 020d315..7f930d4 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -25,7 +25,7 @@ abstract class AbstractChunkedController extends AbstractController * chunk. Must be higher that in the previous request. * - orig: The original file name. * - * @param Request $request - The request object + * @param Request $request - The request object * @return array */ abstract protected function parseChunkedRequest(Request $request); diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 9f6c7f0..0ab6eec 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -88,7 +88,7 @@ abstract class AbstractController $files[] = $file; } - + return $files; } diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index cd70c1e..8043d1c 100644 --- a/Tests/Controller/AbstractChunkedUploadTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -6,7 +6,6 @@ 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; @@ -53,7 +52,7 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $this->assertTrue($response->isSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); } - + $this->assertEquals(1, $validationCount); foreach ($this->getUploadedFiles() as $file) { diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 4e3e284..4f7733b 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -108,7 +108,7 @@ class ChunkManager implements ChunkManagerInterface return $finder; } - + public function getLoadDistribution() { return $this->configuration['load_distribution']; diff --git a/Uploader/Response/AbstractResponse.php b/Uploader/Response/AbstractResponse.php index e9b1c30..16ff74a 100644 --- a/Uploader/Response/AbstractResponse.php +++ b/Uploader/Response/AbstractResponse.php @@ -38,7 +38,7 @@ abstract class AbstractResponse implements \ArrayAccess, ResponseInterface * This function will take a path of arrays and add a new element to it, creating the path if needed. * * @param mixed $value - * @param array $offsets + * @param array $offsets * * @throws \InvalidArgumentException if the path contains non-array items. *
0
243f21631411b06669f57e90243d7154e798b4f9
1up-lab/OneupUploaderBundle
use the stream wrapper prefix when available
commit 243f21631411b06669f57e90243d7154e798b4f9 Author: mitom <[email protected]> Date: Fri Feb 21 17:11:20 2014 +0100 use the stream wrapper prefix when available diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index dec76ce..9d22fd6 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -169,4 +169,9 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface { return $this->filesystem; } + + public function getStreamWrapperPrefix() + { + return $this->streamWrapperPrefix; + } } diff --git a/Uploader/Storage/GaufretteOrphanageStorage.php b/Uploader/Storage/GaufretteOrphanageStorage.php index ea5379f..d5a9489 100644 --- a/Uploader/Storage/GaufretteOrphanageStorage.php +++ b/Uploader/Storage/GaufretteOrphanageStorage.php @@ -26,9 +26,11 @@ class GaufretteOrphanageStorage extends GaufretteStorage implements OrphanageSto */ public function __construct(StorageInterface $storage, SessionInterface $session, GaufretteChunkStorage $chunkStorage, $config, $type) { - // initiate the storage on the chunk storage's filesystem - // the prefix and stream wrapper are unnecessary. - parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, null, null); + /* + * initiate the storage on the chunk storage's filesystem + * the stream wrapper is useful for metadata. + */ + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, $chunkStorage->getStreamWrapperPrefix()); $this->storage = $storage; $this->chunkStorage = $chunkStorage;
0
e2b21d4245bf70ccd5aa7cf4f38ab7884f490c79
1up-lab/OneupUploaderBundle
Merge branch 'Lctrs-fix/flysystem-chunk-storage'
commit e2b21d4245bf70ccd5aa7cf4f38ab7884f490c79 (from d5a149b431311e19ca6c8fab276c58bce30c58a6) Merge: d5a149b 42e611f Author: David Greminger <[email protected]> Date: Tue Oct 10 10:09:38 2017 +0200 Merge branch 'Lctrs-fix/flysystem-chunk-storage' diff --git a/README.md b/README.md index 1daa930..377fb9d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ OneupUploaderBundle =================== -The OneupUploaderBundle for Symfony2 adds support for handling file uploads using one of the following JavaScript libraries, or [your own implementation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_uploader.md). +The OneupUploaderBundle for Symfony adds support for handling file uploads using one of the following JavaScript libraries, or [your own implementation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_uploader.md). * [Dropzone](http://www.dropzonejs.com/) * [jQuery File Upload](http://blueimp.github.io/jQuery-File-Upload/) diff --git a/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php index af1f32f..ca14e11 100644 --- a/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php +++ b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php @@ -2,18 +2,22 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\ChunkStorageInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase { protected $tmpDir; + /** + * @var ChunkStorageInterface + */ protected $storage; public function testExistanceOfTmpDir() { $this->assertTrue(is_dir($this->tmpDir)); - $this->assertTrue(is_writeable($this->tmpDir)); + $this->assertTrue(is_writable($this->tmpDir)); } public function testFillOfTmpDir() @@ -30,7 +34,7 @@ abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase public function testChunkCleanup() { // get a manager configured with a max-age of 5 minutes - $maxage = 5 * 60; + $maxage = 5 * 60; $numberOfFiles = 10; $finder = new Finder(); @@ -42,7 +46,7 @@ abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase $this->storage->clear($maxage); $this->assertTrue(is_dir($this->tmpDir)); - $this->assertTrue(is_writeable($this->tmpDir)); + $this->assertTrue(is_writable($this->tmpDir)); $this->assertCount(5, $finder); @@ -66,8 +70,8 @@ abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase { $system = new Filesystem(); - for ($i = 0; $i < $number; $i ++) { - $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid()), time() - $i * 60); + for ($i = 0; $i < $number; ++$i) { + $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid('', true)), time() - $i * 60); } } } diff --git a/Tests/Uploader/Chunk/Storage/FlysystemStorageTest.php b/Tests/Uploader/Chunk/Storage/FlysystemStorageTest.php new file mode 100644 index 0000000..8d553a1 --- /dev/null +++ b/Tests/Uploader/Chunk/Storage/FlysystemStorageTest.php @@ -0,0 +1,48 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; + +use League\Flysystem\Adapter\Local as Adapter; +use League\Flysystem\Filesystem as LeagueFilesystem; +use League\Flysystem\Plugin\ListFiles; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage; +use Symfony\Component\Filesystem\Filesystem; +use Twistor\FlysystemStreamWrapper; + +class FlysystemStorageTest extends ChunkStorageTest +{ + protected $parentDir; + protected $chunkKey = 'chunks'; + protected $chunkDir; + + public function setUp() + { + // create a cache dir + $parentDir = sprintf('/tmp/%s', uniqid('', true)); + + $system = new Filesystem(); + $system->mkdir($parentDir); + + $this->parentDir = $parentDir; + + $adapter = new Adapter($this->parentDir); + + $filesystem = new LeagueFilesystem($adapter); + $filesystem->addPlugin(new ListFiles()); + + FlysystemStreamWrapper::register('tests', $filesystem); + + $this->storage = new FlysystemStorage($filesystem, 100000, 'tests:/', $this->chunkKey); + $this->tmpDir = $this->parentDir.'/'.$this->chunkKey; + + $system->mkdir($this->tmpDir); + } + + public function tearDown() + { + $system = new Filesystem(); + $system->remove($this->parentDir); + + FlysystemStreamWrapper::unregister('tests'); + } +} diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index 102e954..af5a194 100644 --- a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -14,6 +14,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use League\Flysystem\Adapter\Local as Adapter; use League\Flysystem\Filesystem as FSAdapter; use Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage as Storage; +use Twistor\FlysystemStreamWrapper; class FlysystemOrphanageStorageTest extends OrphanageTest { @@ -34,16 +35,14 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $filesystem->mkdir($this->chunkDirectory); $filesystem->mkdir($this->tempDirectory); - if (!$this->checkIfTempnameMatchesAfterCreation()) { - $this->markTestSkipped('Temporary directories do not match'); - } - - $adapter = new Adapter($this->realDirectory, true); + $adapter = new Adapter($this->realDirectory); $filesystem = new FSAdapter($adapter); + FlysystemStreamWrapper::register('tests', $filesystem); + $this->storage = new Storage($filesystem, 100000); - $chunkStorage = new ChunkStorage($filesystem, 100000, null, 'chunks'); + $chunkStorage = new ChunkStorage($filesystem, 100000, 'tests:/', 'chunks'); // create orphanage $session = new Session(new MockArraySessionStorage()); @@ -68,6 +67,13 @@ class FlysystemOrphanageStorageTest extends OrphanageTest } } + public function tearDown() + { + (new Filesystem())->remove($this->realDirectory); + + FlysystemStreamWrapper::unregister('tests'); + } + public function testUpload() { for ($i = 0; $i < $this->numberOfPayloads; $i ++) { @@ -95,9 +101,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $this->assertCount($this->numberOfPayloads, $finder); $finder = new Finder(); - $finder->in($this->realDirectory) - ->exclude(array($this->orphanageKey, $this->chunksKey)) - ->files(); + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); $this->assertCount(0, $finder); $files = $this->orphanage->uploadFiles(); @@ -113,13 +117,4 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $finder->in($this->realDirectory)->files(); $this->assertCount($this->numberOfPayloads, $finder); } - - public function checkIfTempnameMatchesAfterCreation() - { - $testName = tempnam($this->chunkDirectory, 'uploader'); - $result = strpos($testName, $this->chunkDirectory) === 0; - unlink($testName); - - return $result; - } } diff --git a/Uploader/Chunk/Storage/FlysystemStorage.php b/Uploader/Chunk/Storage/FlysystemStorage.php index 19e7a44..77eabc6 100644 --- a/Uploader/Chunk/Storage/FlysystemStorage.php +++ b/Uploader/Chunk/Storage/FlysystemStorage.php @@ -1,13 +1,14 @@ <?php + namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; -use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use League\Flysystem\FileNotFoundException; use League\Flysystem\Filesystem; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; use Symfony\Component\HttpFoundation\File\UploadedFile; class FlysystemStorage implements ChunkStorageInterface { - protected $unhandledChunk; protected $prefix; protected $streamWrapperPrefix; @@ -21,12 +22,8 @@ class FlysystemStorage implements ChunkStorageInterface public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) { - if ( - ! method_exists($filesystem, 'readStream') - || - ! method_exists($filesystem, 'putStream') - ) { - throw new \InvalidArgumentException('The filesystem used as chunk storage must streamable'); + if (null === $streamWrapperPrefix) { + throw new \InvalidArgumentException('Stream wrapper must be configured.'); } $this->filesystem = $filesystem; @@ -37,8 +34,8 @@ class FlysystemStorage implements ChunkStorageInterface public function clear($maxAge, $prefix = null) { - $prefix = $prefix ? :$this->prefix; - $matches = $this->filesystem->listFiles($prefix); + $prefix = $prefix ?: $this->prefix; + $matches = $this->filesystem->listContents($prefix, true); $now = time(); $toDelete = array(); @@ -47,24 +44,20 @@ class FlysystemStorage implements ChunkStorageInterface // this also means the files inside are old // but after the files are deleted the dirs // would remain - foreach ($matches['dirs'] as $key) { - if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { - $toDelete[] = $key; - } - } - // The same directory is returned for every file it contains - array_unique($toDelete); - foreach ($matches['keys'] as $key) { - if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { - $this->filesystem->delete($key); + foreach ($matches as $key) { + $path = $key['path']; + $timestamp = isset($key['timestamp']) ? $key['timestamp'] : $this->filesystem->getTimestamp($path); + + if ($maxAge <= $now - $timestamp) { + $toDelete[] = $path; } } - foreach ($toDelete as $key) { + foreach ($toDelete as $path) { // The filesystem will throw exceptions if // a directory is not empty try { - $this->filesystem->delete($key); + $this->filesystem->delete($path); } catch (\Exception $e) { continue; } @@ -77,7 +70,7 @@ class FlysystemStorage implements ChunkStorageInterface 'uuid' => $uuid, 'index' => $index, 'chunk' => $chunk, - 'original' => $original + 'original' => $original, ); } @@ -91,21 +84,26 @@ class FlysystemStorage implements ChunkStorageInterface $target = $filename; } else { sort($chunks, SORT_STRING | SORT_FLAG_CASE); - $target = pathinfo($chunks[0], PATHINFO_BASENAME); + $target = pathinfo($chunks[0]['path'], PATHINFO_BASENAME); } - - if ($this->unhandledChunk['index'] === 0) { + $mode = 'ab'; + if (0 === $this->unhandledChunk['index']) { // if it's the first chunk overwrite the already existing part // to avoid appending to earlier failed uploads - $handle = fopen($path . '/' . $target, 'w'); - } else { - $handle = fopen($path . '/' . $target, 'a'); + $mode = 'wb'; } - $this->filesystem->putStream($path . $target, $handle); + $file = fopen($this->unhandledChunk['chunk']->getPathname(), 'rb'); + $dest = fopen($this->streamWrapperPrefix.'/'.$path.$target, $mode); + + stream_copy_to_stream($file, $dest); + + fclose($file); + fclose($dest); + if ($renameChunk) { - $name = preg_replace('/^(\d+)_/', '', $target); + $name = $this->unhandledChunk['original']; /* The name can only match if the same user in the same session is * trying to upload a file under the same name AND the previous upload failed, * somewhere between this function, and the cleanup call. If that happened @@ -130,13 +128,16 @@ class FlysystemStorage implements ChunkStorageInterface public function cleanup($path) { - $this->filesystem->delete($path); + try { + $this->filesystem->delete($path); + } catch (FileNotFoundException $e) { + // File already gone. + } } public function getChunks($uuid) { - $results = $this->filesystem->listFiles($this->prefix.'/'.$uuid); - return preg_grep('/^.+\/(\d+)_/', $results['keys']); + return $this->filesystem->listFiles($this->prefix.'/'.$uuid); } public function getFilesystem() @@ -148,5 +149,4 @@ class FlysystemStorage implements ChunkStorageInterface { return $this->streamWrapperPrefix; } - } diff --git a/Uploader/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
ed5ffc40ced979b0f6b19b59aec79a1173b92cfa
1up-lab/OneupUploaderBundle
Renamed use_upload_progress to enable_progress.
commit ed5ffc40ced979b0f6b19b59aec79a1173b92cfa Author: Jim Schmid <[email protected]> Date: Tue Jun 25 11:33:13 2013 +0200 Renamed use_upload_progress to enable_progress. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 13b8eb2..c72861e 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -49,7 +49,7 @@ abstract class AbstractController return new JsonResponse($value); } - + public function cancel() { $request = $this->container->get('request'); @@ -57,12 +57,12 @@ abstract class AbstractController $prefix = ini_get('session.upload_progress.prefix'); $name = ini_get('session.upload_progress.name'); - + $key = sprintf('%s.%s', $prefix, $request->get($name)); - + $progress = $session->get($key); $progress['cancel_upload'] = false; - + $session->set($key, $progress); return new JsonResponse(true); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index e51b8b0..9b4c457 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -72,7 +72,7 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->booleanNode('use_orphanage')->defaultFalse()->end() - ->booleanNode('use_upload_progress')->defaultValue(false)->end() + ->booleanNode('enable_progress')->defaultFalse()->end() ->booleanNode('enable_cancelation')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index ede54fb..ca6684a 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -130,7 +130,7 @@ class OneupUploaderExtension extends Extension ; $controllers[$key] = array($controllerName, array( - 'use_upload_progress' => $mapping['use_upload_progress'], + 'enable_progress' => $mapping['enable_progress'], 'enable_cancelation' => $mapping['enable_cancelation'] )); } diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 1e2f8ca..a464dc2 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -35,7 +35,7 @@ class RouteLoader extends Loader array('_method' => 'POST') ); - if ($options['use_upload_progress'] === true) { + if ($options['enable_progress'] === true) { $progress = new Route( sprintf('/_uploader/%s/progress', $type), array('_controller' => $service . ':progress', '_format' => 'json'), diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 2299750..77da381 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -26,7 +26,6 @@ oneup_uploader: fineuploader: frontend: fineuploader - use_upload_progress: true storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index db6b86d..08d433c 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -13,11 +13,11 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $routeLoader = new RouteLoader(array( 'cat' => array($cat, array( - 'use_upload_progress' => false, + 'enable_progress' => false, 'enable_cancelation' => false )), 'dog' => array($dog, array( - 'use_upload_progress' => true, + 'enable_progress' => true, 'enable_cancelation' => true )), ));
0
95740749e0550dc63f7b4f28b2e0129ef5fc33be
1up-lab/OneupUploaderBundle
Merge pull request #258 from mediafigaro/patch-2 Update custom_namer.md
commit 95740749e0550dc63f7b4f28b2e0129ef5fc33be (from 2a6daa73e00801ecc0e065d2dee52592147208ee) Merge: 2a6daa7 e5b8427 Author: David Greminger <[email protected]> Date: Tue Jun 28 09:50:14 2016 +0200 Merge pull request #258 from mediafigaro/patch-2 Update custom_namer.md diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index 257451d..fea6ee0 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -65,6 +65,13 @@ You need to inject the `security.token_storage` service to your namer. </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 @@ -92,7 +99,7 @@ class CatNamer implements NamerInterface */ public function name(FileInterface $file) { - $userId = $tokenStorage->getToken()->getUser()->getId(); + $userId = $this->tokenStorage->getToken()->getUser()->getId(); return sprintf('%s/%s.%s', $userId, @@ -103,4 +110,4 @@ class CatNamer implements NamerInterface } ``` -Every file uploaded through the `Controller` of this mapping will be named with your new directory structure. \ No newline at end of file +Every file uploaded through the `Controller` of this mapping will be named with your new directory structure.
0
f9fb64baadbfbad5d0a533b279251a4947507de7
1up-lab/OneupUploaderBundle
Let blueimp return a text/plain response to old browsers
commit f9fb64baadbfbad5d0a533b279251a4947507de7 Author: Erik Ammerlaan <[email protected]> Date: Wed Oct 2 12:36:50 2013 +0200 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
c32aae428a153a2b878319062505d5ca4ad1fbd0
1up-lab/OneupUploaderBundle
Test validation of allowed_extensions.
commit c32aae428a153a2b878319062505d5ca4ad1fbd0 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 14:45:41 2013 +0200 Test validation of allowed_extensions. diff --git a/Tests/Controller/ControllerValidationTest.php b/Tests/Controller/ControllerValidationTest.php index 944cc51..20dd449 100644 --- a/Tests/Controller/ControllerValidationTest.php +++ b/Tests/Controller/ControllerValidationTest.php @@ -14,8 +14,8 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase // create a config $config = array(); $config['max_size'] = 10; - $config['allowed_types'] = array(); - $config['disallowed_types'] = array(); + $config['allowed_extensions'] = array(); + $config['disallowed_extensions'] = array(); // prepare mock $file = $this->getUploadedFileMock(); @@ -33,8 +33,55 @@ class ControllerValidationTest extends \PHPUnit_Framework_TestCase // create a config $config = array(); $config['max_size'] = 20; - $config['allowed_types'] = array(); - $config['disallowed_types'] = array(); + $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); + } + + /** + * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException + */ + public function testAllowedExtensionValidationFails() + { + // create a config + $config = array(); + $config['max_size'] = 20; + $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); + } + + public function testAllowedExtensionValidationPasses() + { + // create a config + $config = array(); + $config['max_size'] = 20; + $config['allowed_extensions'] = array('png', 'jpg', 'jpeg', 'gif'); + $config['disallowed_extensions'] = array(); // prepare mock $file = $this->getUploadedFileMock();
0
222e93cd91d3407120e9eaf9c790671d42031d60
1up-lab/OneupUploaderBundle
A bunch of stuff related to a new feature: Delete uploads.
commit 222e93cd91d3407120e9eaf9c790671d42031d60 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 20:01:17 2013 +0100 A bunch of stuff related to a new feature: Delete uploads. diff --git a/Controller/UploadControllerInterface.php b/Controller/UploadControllerInterface.php index 977375e..c2631a7 100644 --- a/Controller/UploadControllerInterface.php +++ b/Controller/UploadControllerInterface.php @@ -5,4 +5,5 @@ namespace Oneup\UploaderBundle\Controller; interface UploadControllerInterface { public function upload(); + public function delete($uuid = null); } \ No newline at end of file diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 0047a7d..a59fe54 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -5,6 +5,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\HttpKernel\Exception\HttpException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Finder\Finder; @@ -61,6 +62,16 @@ class UploaderController implements UploadControllerInterface new JsonResponse(array('error' => 'An unknown error occured.')) ; } + + public function delete($uuid = null) + { + if(is_null($uuid)) + return new HttpException(400, 'You must provide a file uuid.'); + + return $this->storage->remove($this->type, $uuid) ? + new JsonResponse(array('success' => true)): + new JsonResponse(array('error' => 'An unknown error occured.')); + } protected function handleUpload(UploadedFile $file) { @@ -85,6 +96,7 @@ class UploaderController implements UploadControllerInterface $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( 'use_orphanage' => $this->config['use_orphanage'], 'file_name' => $name, + 'deletable' => $this->config['deletable'], )); $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 658f48f..c3f4575 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -44,6 +44,7 @@ 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 91e4520..3a0d2f2 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -71,6 +71,8 @@ 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/Event/PostDeleteEvent.php b/Event/PostDeleteEvent.php new file mode 100644 index 0000000..00f9a93 --- /dev/null +++ b/Event/PostDeleteEvent.php @@ -0,0 +1,44 @@ +<?php + +namespace Oneup\UploaderBundle\Event; + +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\HttpFoundation\Request; + +use Symfony\Component\HttpFoundation\File\File; + +class PostDeleteEvent extends Event +{ + protected $file; + protected $request; + protected $type; + protected $options; + + public function __construct(File $file, Request $request, $type, array $options = array()) + { + $this->file = $file; + $this->request = $request; + $this->type = $type; + $this->options = $options; + } + + public function getFile() + { + return $this->file; + } + + public function getRequest() + { + return $this->request; + } + + public function getType() + { + return $this->type; + } + + public function getOptions() + { + return $this->options; + } +} \ No newline at end of file diff --git a/EventListener/DeletableListener.php b/EventListener/DeletableListener.php new file mode 100644 index 0000000..38c752b --- /dev/null +++ b/EventListener/DeletableListener.php @@ -0,0 +1,45 @@ +<?php + +namespace Oneup\UploaderBundle\EventListener; + +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +use Oneup\UploaderBundle\Event\PostUploadEvent; +use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Uploader\Deletable\DeletableManagerInterface; + +class DeletableListener implements EventSubscriberInterface +{ + protected $manager; + + public function __construct(DeletableManagerInterface $manager) + { + $this->manager = $manager; + } + + public function register(PostUploadEvent $event) + { + $options = $event->getOptions(); + $request = $event->getRequest(); + $file = $event->getFile(); + $type = $event->getType(); + + if(!array_key_exists('deletable', $options) || !$options['deletable']) + return; + + if(!array_key_exists('file_name', $options)) + return; + + $uuid = $request->get('qquuid'); + + $this->manager->addFile($type, $uuid, $options['file_name']); + } + + public static function getSubscribedEvents() + { + return array( + UploadEvents::POST_UPLOAD => 'register', + ); + } +} diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 83369bf..fad0080 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -4,6 +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.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> @@ -11,7 +12,8 @@ <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> <parameter key="oneup_uploader.storage.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> - <parameter key="oneup_uploader.listener.session.class">Oneup\UploaderBundle\EventListener\OrphanageListener</parameter> + <parameter key="oneup_uploader.listener.orphanage.class">Oneup\UploaderBundle\EventListener\OrphanageListener</parameter> + <parameter key="oneup_uploader.listener.deletable.class">Oneup\UploaderBundle\EventListener\DeletableListener</parameter> </parameters> <services> @@ -28,18 +30,29 @@ <!-- 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" /> </service> <!-- events --> - <service id="oneup_uploader.listener.orphanage" class="%oneup_uploader.listener.session.class%"> + <service id="oneup_uploader.listener.orphanage" class="%oneup_uploader.listener.orphanage.class%"> <argument type="service" id="oneup_uploader.orphanage_manager" /> <tag name="kernel.event_subscriber" /> </service> + <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/Routing/RouteLoader.php b/Routing/RouteLoader.php index 572f522..726e84d 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -32,13 +32,27 @@ class RouteLoader extends Loader foreach($this->controllers as $type => $service) { - $route = new Route( - sprintf('/_uploader/%s', $type), + $upload = new Route( + sprintf('/_uploader/%s/upload', $type), array('_controller' => $service . ':upload', '_format' => 'json'), array('_method' => 'POST') ); - $routes->add(sprintf('_uploader_%s', $type), $route); + $delete = new Route( + sprintf('/_uploader/%s/delete/{uuid}', $type), + array('_controller' => $service . ':delete', '_format' => 'json'), + array('_method' => 'DELETE', 'uuid' => '[A-z0-9-]*') + ); + + $base = new Route( + sprintf('/_uploader/%s/delete', $type), + array('_controller' => $service . ':delete', '_format' => 'json'), + array('_method' => 'DELETE') + ); + + $routes->add(sprintf('_uploader_%s_upload', $type), $upload); + $routes->add(sprintf('_uploader_%s_delete', $type), $delete); + $routes->add(sprintf('_uploader_%s_delete_base', $type), $base); } return $routes; diff --git a/Uploader/Deletable/DeletableManager.php b/Uploader/Deletable/DeletableManager.php new file mode 100644 index 0000000..69ba85c --- /dev/null +++ b/Uploader/Deletable/DeletableManager.php @@ -0,0 +1,67 @@ +<?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 new file mode 100644 index 0000000..02afdf1 --- /dev/null +++ b/Uploader/Deletable/DeletableManagerInterface.php @@ -0,0 +1,7 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Deletable; + +interface DeletableManagerInterface +{ +} \ No newline at end of file diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index cfc5d35..f0a7430 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -6,15 +6,19 @@ use Symfony\Component\HttpFoundation\File\File; use Gaufrette\Stream\Local as LocalStream; use Gaufrette\StreamMode; use Gaufrette\Filesystem; + use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; +use Oneup\UploaderBundle\Uploader\Deletable\DeletableManagerInterface; class GaufretteStorage implements StorageInterface { protected $filesystem; + protected $deletableManager; - public function __construct(Filesystem $filesystem) + public function __construct(Filesystem $filesystem, DeletableManagerInterface $deletableManager) { $this->filesystem = $filesystem; + $this->deletableManager = $deletableManager; } public function upload(File $file, $name = null) @@ -46,8 +50,28 @@ class GaufretteStorage implements StorageInterface return $this->filesystem->get($name); } - public function remove(File $file) + public function remove($type, $uuid) { + try + { + // get associated file path + $name = $this->deletableManager->getFile($type, $uuid); + + if($this->filesystem->has($name)) + { + $this->filesystem->delete($name); + } + + // delete this reference anyway + $this->deletableManager->removeFile($type, $uuid); + } + catch(\Exception $e) + { + // whoopsi, something went terribly wrong + // better leave this method now and never look back + return false; + } + return true; } } \ No newline at end of file diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 1e4a287..38eb9c8 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -7,5 +7,5 @@ use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { public function upload(File $file, $name); - public function remove(File $file); + public function remove($type, $uuid); } \ No newline at end of file
0
2d8f07a3c9847132c1ead0d0bf7efc9b71e313e7
1up-lab/OneupUploaderBundle
Fixed RouteLoaderTest, we're now working with arrays.
commit 2d8f07a3c9847132c1ead0d0bf7efc9b71e313e7 Author: Jim Schmid <[email protected]> Date: Tue Jun 25 11:16:21 2013 +0200 Fixed RouteLoaderTest, we're now working with arrays. diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 017a94e..9a362f5 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -12,8 +12,8 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $dog = 'HelloThisIsDogController'; $routeLoader = new RouteLoader(array( - 'cat' => $cat, - 'dog' => $dog + 'cat' => array($cat, array('use_upload_progress' => false)), + 'dog' => array($dog, array('use_upload_progress' => true)), )); $routes = $routeLoader->load(null); @@ -21,7 +21,7 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase // for code coverage $this->assertTrue($routeLoader->supports('grumpy', 'uploader')); $this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $routes); - $this->assertCount(2, $routes); + $this->assertCount(3, $routes); foreach ($routes as $route) { $this->assertInstanceOf('Symfony\Component\Routing\Route', $route);
0
e0e018e330ac37f029f6536df7dd687b559897d7
1up-lab/OneupUploaderBundle
Switched to correct frontend and added some basic upload stuff.
commit e0e018e330ac37f029f6536df7dd687b559897d7 Author: Jim Schmid <[email protected]> Date: Mon May 6 22:13:35 2013 +0200 Switched to correct frontend and added some basic upload stuff. diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 7c7d4c8..564f071 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -29,5 +29,6 @@ monolog: oneup_uploader: mappings: blueimp: + frontend: blueimp storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload \ No newline at end of file diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index be2176d..14c966f 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Controller; +use Symfony\Component\Finder\Finder; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; abstract class AbstractControllerTest extends WebTestCase @@ -21,8 +22,8 @@ abstract class AbstractControllerTest extends WebTestCase } abstract protected function getConfigKey(); - abstract protected function getSingleRequestParameters(); - abstract protected function getSingleRequestFile(); + abstract protected function getRequestParameters(); + abstract protected function getRequestFile(); public function testSingleUpload() { @@ -30,11 +31,18 @@ abstract class AbstractControllerTest extends WebTestCase $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, $this->getSingleRequestParameters(), $this->getSingleRequestFile()); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile())); $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 testRoute() @@ -94,10 +102,28 @@ abstract class AbstractControllerTest extends WebTestCase return $file; } + protected function getUploadedFiles() + { + $env = $this->container->getParameter('kernel.environment'); + $root = $this->container->getParameter('kernel.root_dir'); + + // assemble path + $path = sprintf('%s/cache/%s/upload', $root, $env); + + $finder = new Finder(); + $files = $finder->in($path); + + return $files; + } + public function tearDown() { foreach($this->createdFiles as $file) { @unlink($file); } + + foreach($this->getUploadedFiles() as $file) { + @unlink($file); + } } } diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index f60d785..51c9918 100644 --- a/Tests/Controller/BlueimpTest.php +++ b/Tests/Controller/BlueimpTest.php @@ -12,20 +12,18 @@ class BlueimpTest extends AbstractControllerTest return 'blueimp'; } - protected function getSingleRequestParameters() + protected function getRequestParameters() { return array(); } - protected function getSingleRequestFile() + protected function getRequestFile() { - $file = new UploadedFile( + return array(new UploadedFile( $this->createTempFile(128), 'cat.txt', 'text/plain', 128 - ); - - return array($file); + )); } }
0
7727ba12af35030d1ac8c54caa6d0264829c0da1
1up-lab/OneupUploaderBundle
Changed tests according to new class names.
commit 7727ba12af35030d1ac8c54caa6d0264829c0da1 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:01:59 2013 +0200 Changed tests according to new class names. diff --git a/Tests/Controller/UploaderControllerChunkedTest.php b/Tests/Controller/FineUploaderControllerChunkedTest.php similarity index 95% rename from Tests/Controller/UploaderControllerChunkedTest.php rename to Tests/Controller/FineUploaderControllerChunkedTest.php index 1291823..f82f41b 100644 --- a/Tests/Controller/UploaderControllerChunkedTest.php +++ b/Tests/Controller/FineUploaderControllerChunkedTest.php @@ -9,9 +9,9 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; -use Oneup\UploaderBundle\Controller\UploaderController; +use Oneup\UploaderBundle\Controller\FineUploaderController; -class UploaderControllerChunkedTest extends \PHPUnit_Framework_TestCase +class FineUploaderControllerChunkedTest extends \PHPUnit_Framework_TestCase { protected $tempChunks; protected $currentChunk; @@ -52,7 +52,7 @@ class UploaderControllerChunkedTest extends \PHPUnit_Framework_TestCase ); $responses = array(); - $controller = new UploaderController($container, $storage, $config, 'cat'); + $controller = new FineUploaderController($container, $storage, $config, 'cat'); // mock as much requests as there are parts to assemble for($i = 0; $i < $this->numberOfChunks; $i ++) diff --git a/Tests/Controller/UploaderControllerTest.php b/Tests/Controller/FineUploaderControllerTest.php similarity index 93% rename from Tests/Controller/UploaderControllerTest.php rename to Tests/Controller/FineUploaderControllerTest.php index e9bd236..84f0db4 100644 --- a/Tests/Controller/UploaderControllerTest.php +++ b/Tests/Controller/FineUploaderControllerTest.php @@ -8,9 +8,9 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; -use Oneup\UploaderBundle\Controller\UploaderController; +use Oneup\UploaderBundle\Controller\FineUploaderController; -class UploaderControllerTest extends \PHPUnit_Framework_TestCase +class FineUploaderControllerTest extends \PHPUnit_Framework_TestCase { protected $tempFile; @@ -36,7 +36,7 @@ class UploaderControllerTest extends \PHPUnit_Framework_TestCase 'disallowed_extensions' => array() ); - $controller = new UploaderController($container, $storage, $config, 'cat'); + $controller = new FineUploaderController($container, $storage, $config, 'cat'); $response = $controller->upload(); // check if original file has been moved @@ -65,7 +65,7 @@ class UploaderControllerTest extends \PHPUnit_Framework_TestCase 'disallowed_extensions' => array() ); - $controller = new UploaderController($container, $storage, $config, 'cat'); + $controller = new FineUploaderController($container, $storage, $config, 'cat'); $response = $controller->upload(); $json = json_decode($response->getContent()); diff --git a/Tests/Controller/UploaderControllerValidationTest.php b/Tests/Controller/FineUploaderControllerValidationTest.php similarity index 93% rename from Tests/Controller/UploaderControllerValidationTest.php rename to Tests/Controller/FineUploaderControllerValidationTest.php index 2e06720..f38e951 100644 --- a/Tests/Controller/UploaderControllerValidationTest.php +++ b/Tests/Controller/FineUploaderControllerValidationTest.php @@ -2,9 +2,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; -use Oneup\UploaderBundle\Controller\UploaderController; +use Oneup\UploaderBundle\Controller\FineUploaderController; -class UploaderControllerValidationTest extends \PHPUnit_Framework_TestCase +class FineUploaderControllerValidationTest extends \PHPUnit_Framework_TestCase { /** * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException @@ -90,7 +90,7 @@ class UploaderControllerValidationTest extends \PHPUnit_Framework_TestCase $container = $this->getContainerMock(); $storage = $this->getStorageMock(); - $controller = new UploaderController($container, $storage, $config, 'cat'); + $controller = new FineUploaderController($container, $storage, $config, 'cat'); $method->invoke($controller, $file); // yey, no exception thrown @@ -132,7 +132,7 @@ class UploaderControllerValidationTest extends \PHPUnit_Framework_TestCase protected function getValidationMethod() { // create a public version of the validate method - $class = new \ReflectionClass('Oneup\\UploaderBundle\\Controller\\UploaderController'); + $class = new \ReflectionClass('Oneup\\UploaderBundle\\Controller\\FineUploaderController'); $method = $class->getMethod('validate'); $method->setAccessible(true);
0
8263926a658f9f50add73c1278871e68ee6d8357
1up-lab/OneupUploaderBundle
version compare
commit 8263926a658f9f50add73c1278871e68ee6d8357 Author: Martin Aarhof <[email protected]> Date: Wed Dec 9 16:59:23 2015 +0100 version compare diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index d20bf8f..5374a8c 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -207,7 +207,7 @@ abstract class AbstractController */ protected function getRequest() { - if (version_compare(Kernel::VERSION, '2.4') === -1) { + if (version_compare(Kernel::VERSION, '2.4', '<=')) { return $this->container->get('request'); }
0
6206abffaba14dfc473f812904dc4395222f12d8
1up-lab/OneupUploaderBundle
Tested chunked uploads for FineUploaderController.
commit 6206abffaba14dfc473f812904dc4395222f12d8 Author: Jim Schmid <[email protected]> Date: Mon May 6 23:25:27 2013 +0200 Tested chunked uploads for FineUploaderController. diff --git a/Tests/Controller/FineUploaderTest.php b/Tests/Controller/FineUploaderTest.php index 7c6ec11..d2737ef 100644 --- a/Tests/Controller/FineUploaderTest.php +++ b/Tests/Controller/FineUploaderTest.php @@ -5,7 +5,7 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; -class FineUploaderTest extends AbstractControllerTest +class FineUploaderTest extends AbstractChunkedControllerTest { protected function getConfigKey() { @@ -26,4 +26,24 @@ class FineUploaderTest extends AbstractControllerTest 128 ); } + + protected function getNextRequestParameters($i) + { + return array( + 'qqtotalparts' => $this->total, + 'qqpartindex' => $i, + 'qquuid' => 'veryuuid', + 'qqfilename' => 'cat.txt' + ); + } + + protected function getNextFile($i) + { + return new UploadedFile( + $this->createTempFile(20), + 'cat.txt', + 'text/plain', + 20 + ); + } }
0
0a0bb1e9cb0d44cd6ea4dd9dfc6fe619e226adfe
1up-lab/OneupUploaderBundle
Merge pull request #70 from USvER/patch-1 Fixed ErrorHandlerInterface implementation documentation (issue #68)
commit 0a0bb1e9cb0d44cd6ea4dd9dfc6fe619e226adfe (from 3b8ee6a453e57d6ce8fbd9635bcfcae517bea237) Merge: 3b8ee6a c1e9a14 Author: Jim Schmid <[email protected]> Date: Wed Nov 6 10:09:25 2013 -0800 Merge pull request #70 from USvER/patch-1 Fixed ErrorHandlerInterface implementation documentation (issue #68) diff --git a/Resources/doc/custom_error_handler.md b/Resources/doc/custom_error_handler.md index b6cd21c..4110836 100644 --- a/Resources/doc/custom_error_handler.md +++ b/Resources/doc/custom_error_handler.md @@ -10,13 +10,13 @@ To create your own error handler, implement the `ErrorHandlerInterface` and add namespace Acme\DemoBundle\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 CustomErrorHandler implements ErrorHandlerInterface { - public function addException(ResponseInterface $response, UploadException $exception) + public function addException(AbstractResponse $response, Exception $exception) { $message = $exception->getMessage(); $response['error'] = $message;
0
ccae98164529c319ba345d82803ebf24fab39d70
1up-lab/OneupUploaderBundle
Removed unused variables on BlueimpController.
commit ccae98164529c319ba345d82803ebf24fab39d70 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:23:51 2013 +0200 Removed unused variables on BlueimpController. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 311c4fa..981a4a4 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -14,9 +14,6 @@ class BlueimpController extends AbstractChunkedController public function upload() { $request = $this->container->get('request'); - $dispatcher = $this->container->get('event_dispatcher'); - $translator = $this->container->get('translator'); - $response = new EmptyResponse(); $files = $request->files;
0
da09f881c78b58a869ade9ecfa00b730f02bb9aa
1up-lab/OneupUploaderBundle
Merge pull request #11 from 1up-lab/plupload Implemented Plupload
commit da09f881c78b58a869ade9ecfa00b730f02bb9aa (from 59659bda1dbd944cf18d140417ff5f29c8622644) Merge: 59659bd 5f8d051 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 07:03:37 2013 -0700 Merge pull request #11 from 1up-lab/plupload Implemented Plupload diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php new file mode 100644 index 0000000..c445174 --- /dev/null +++ b/Controller/PluploadController.php @@ -0,0 +1,56 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; + +use Oneup\UploaderBundle\Controller\AbstractChunkedController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class PluploadController extends AbstractChunkedController +{ + public function upload() + { + $request = $this->container->get('request'); + $response = new EmptyResponse(); + $files = $request->files; + + $chunked = !is_null($request->get('chunks')); + + foreach($files as $file) + { + try + { + $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + } + + return new JsonResponse($response->assemble()); + } + + 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/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index b00f847..e33d623 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload', 'plupload')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/README.md b/README.md index 48eb51b..292b3cb 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ The OneupUploaderBundle adds support for handling file uploads using one of the * [Uploadify](http://www.uploadify.com/) * [FancyUpload](http://digitarald.de/project/fancyupload/) * [MooUpload](https://github.com/juanparati/MooUpload) +* [Plupload](http://www.plupload.com/) Features included: diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 8b1cc48..49de680 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -17,6 +17,7 @@ <parameter key="oneup_uploader.controller.yui3.class">Oneup\UploaderBundle\Controller\YUI3Controller</parameter> <parameter key="oneup_uploader.controller.fancyupload.class">Oneup\UploaderBundle\Controller\FancyUploadController</parameter> <parameter key="oneup_uploader.controller.mooupload.class">Oneup\UploaderBundle\Controller\MooUploadController</parameter> + <parameter key="oneup_uploader.controller.plupload.class">Oneup\UploaderBundle\Controller\PluploadController</parameter> </parameters> <services> diff --git a/Resources/doc/frontend_blueimp.md b/Resources/doc/frontend_blueimp.md index 1b4e63a..453dd54 100644 --- a/Resources/doc/frontend_blueimp.md +++ b/Resources/doc/frontend_blueimp.md @@ -29,4 +29,16 @@ oneup_uploader: frontend: blueimp ``` -Be sure to check out the [official manual](https://github.com/blueimp/jQuery-File-Upload#jquery-file-upload-plugin) for details on the configuration. \ No newline at end of file +Be sure to check out the [official manual](https://github.com/blueimp/jQuery-File-Upload#jquery-file-upload-plugin) for details on the configuration. + +The jQuery File Upload library does not send a unique id along the file upload request. Because of that, we only have the filename as an information to distinguish uploads. It is possible though that two users upload a file with the same name at the same time. To further tell these files apart, the SessionId is used. If you provide anonymous uploads on your application, be sure to configure the firewall accordingly. + +```yml +# app/config/security.yml + +security: + firewalls: + main: + pattern: ^/ + anonymous: true +``` \ No newline at end of file diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md new file mode 100644 index 0000000..b27657c --- /dev/null +++ b/Resources/doc/frontend_plupload.md @@ -0,0 +1,50 @@ +Use Plupload in your Symfony2 application +========================================= + +Download [Plupload](http://http://www.plupload.com/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}`. + +```html +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> +<script type="text/javascript" src="http://bp.yahooapis.com/2.4.21/browserplus-min.js"></script> +<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script> +<script type="text/javascript" src="http://www.plupload.com/plupload/js/plupload.full.js"></script> +<script type="text/javascript" src="http://www.plupload.com/plupload/js/jquery.ui.plupload/jquery.ui.plupload.js"></script> + +<script type="text/javascript"> +$(document).ready(function() +{ + $("#fileupload").plupload( + { + runtimes: "html5", + url: "{{ path('_uploader_gallery') }}" + }); +}); +</script> + +<div id="fileupload"></div> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: plupload +``` + +Be sure to check out the [official manual](http://www.plupload.com/documentation.php) for details on the configuration. + +The Plupload library does not send a unique id along the file upload request. Because of that, we only have the filename as an information to distinguish uploads. It is possible though that two users upload a file with the same name at the same time. To further tell these files apart, the SessionId is used. If you provide anonymous uploads on your application, be sure to configure the firewall accordingly. + +```yml +# app/config/security.yml + +security: + firewalls: + main: + pattern: ^/ + anonymous: true +``` \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 9b6afe0..2a49f75 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -98,6 +98,7 @@ So if you take the mapping described before, the generated route name would be ` * [Use Uploadify](frontend_uploadify.md) * [Use FancyUpload](frontend_fancyupload.md) * [Use MooUpload](frontend_mooupload.md) +* [Use Plupload](frontend_plupload.md) ## Next steps diff --git a/composer.json b/composer.json index 36f6e82..8124134 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "oneup/uploader-bundle", "type": "symfony-bundle", "description": "Handle multi file uploads. Features included: Chunked upload, Orphans management, Gaufrette support.", - "keywords": ["fileupload", "upload", "multifileupload", "chunked upload", "orphans", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload"], + "keywords": ["fileupload", "upload", "FineUploader", "blueimp", "jQuery File Uploader", "YUI3 Uploader", "Uploadify", "FancyUpload", "MooUpload", "Plupload"], "homepage": "http://1up.io", "license": "MIT", "authors": [
0
1f5962b83781ea1c256c39c61f4f7c91e84e16b9
1up-lab/OneupUploaderBundle
Documented custom validators.
commit 1f5962b83781ea1c256c39c61f4f7c91e84e16b9 Author: Jim Schmid <[email protected]> Date: Mon Apr 22 20:12:51 2013 +0200 Documented custom validators. diff --git a/Resources/doc/custom_validator.md b/Resources/doc/custom_validator.md new file mode 100644 index 0000000..3b63823 --- /dev/null +++ b/Resources/doc/custom_validator.md @@ -0,0 +1,45 @@ +Writing custom Validators +========================= + +File validations in the OneupUploaderBundle were made using the [EventDispatcher](http://symfony.com/doc/current/components/event_dispatcher/introduction.html) component. +If you want to enhance file validations in your application, you can register your own `EventListener` like in the example below. + +```php +namespace Acme\DemoBundle\EventListener; + +use Oneup\UploaderBundle\Event\ValidationEvent; +use Oneup\UploaderBundle\Uploader\Exception\ValidationException; + +class AlwaysFalseValidationListener +{ + public function onValidate(ValidationEvent $event) + { + $config = $event->getConfig(); + $file = $event->getFile(); + + // do some validations + throw new ValidationException('Sorry! Always false.'); + } +} +``` + +If you want your validation to fail, throw a `ValidationException`. This will be catched up by the `Controller`. +After that register your new `EventListener` in the `services.xml` of your application. + +```xml +<?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="acme_demo.always_false_listener" + class="Acme\DemoBundle\EventListener\AlwaysFalseValidationListener" + > + <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> + </service> + </services> +</container> +``` diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 00bc4ae..2b6be7a 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -120,6 +120,7 @@ some more advanced features. * [Include your own Namer](custom_namer.md) * [Testing this bundle](testing.md) * [Support a custom uploader](custom_uploader.md) +* [Validate your uploads](custom_validator.md) * [General/Generic Events](events.md) * [Configuration Reference](configuration_reference.md)
0
5f4d333aecdd888c165a02b288c4cbafb35f0b70
1up-lab/OneupUploaderBundle
Merge pull request #7 from 1up-lab/uniformity Uniformity
commit 5f4d333aecdd888c165a02b288c4cbafb35f0b70 (from 2a9913169e17de226a41ecc5ef3ed3cc7f4a04e1) Merge: 2a99131 e5de39a Author: Jim Schmid <[email protected]> Date: Thu Mar 28 04:47:44 2013 -0700 Merge pull request #7 from 1up-lab/uniformity Uniformity diff --git a/Controller/UploadControllerInterface.php b/Controller/UploadControllerInterface.php index c2631a7..977375e 100644 --- a/Controller/UploadControllerInterface.php +++ b/Controller/UploadControllerInterface.php @@ -5,5 +5,4 @@ namespace Oneup\UploaderBundle\Controller; interface UploadControllerInterface { public function upload(); - public function delete($uuid = null); } \ No newline at end of file diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 48aef6e..7ca7320 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -13,7 +13,6 @@ use Symfony\Component\Finder\Finder; use Oneup\UploaderBundle\UploadEvents; use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; -use Oneup\UploaderBundle\Event\PostDeleteEvent; use Oneup\UploaderBundle\Controller\UploadControllerInterface; use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; @@ -60,24 +59,6 @@ class UploaderController implements UploadControllerInterface return new JsonResponse(array('success' => true, 'name' => $name)); } - - public function delete($uuid = null) - { - if(is_null($uuid)) - return new HttpException(400, 'You must provide a file uuid.'); - - $result = $this->storage->remove($this->type, $uuid); - - if($result) - { - $postUploadEvent = new PostDeleteEvent($this->request, $uuid, $this->type); - $this->dispatcher->dispatch(UploadEvents::POST_DELETE, $postUploadEvent); - - return new JsonResponse(array('success' => true)); - } - - return new JsonResponse(array('error' => 'An unknown error occured.')); - } protected function handleUpload(UploadedFile $file) { @@ -98,18 +79,16 @@ class UploaderController implements UploadControllerInterface throw new UploadException('This extension is not allowed.'); $name = $this->namer->name($file, $this->config['directory_prefix']); + $uploaded = $this->storage->upload($file, $name); $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( 'use_orphanage' => $this->config['use_orphanage'], - 'file_name' => $name, - 'deletable' => $this->config['deletable'], + 'file_name' => $name )); $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); if(!$this->config['use_orphanage']) { - $uploaded = $this->storage->upload($file, $name); - // dispatch post upload event $postPersistEvent = new PostPersistEvent($uploaded, $this->request, $this->type); $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c3f4575..9987fb7 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -17,14 +17,16 @@ class Configuration implements ConfigurationInterface ->arrayNode('chunks') ->addDefaultsIfNotSet() ->children() - ->scalarNode('directory')->end() + ->booleanNode('enabled')->defaultFalse()->end() + ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->end() ->end() ->arrayNode('orphanage') ->addDefaultsIfNotSet() ->children() - ->scalarNode('directory')->end() + ->booleanNode('enabled')->defaultFalse()->end() + ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->end() ->end() @@ -34,7 +36,7 @@ class Configuration implements ConfigurationInterface ->requiresAtLeastOneElement() ->prototype('array') ->children() - ->scalarNode('storage')->isRequired()->end() + ->scalarNode('filesystem')->isRequired()->end() ->arrayNode('allowed_types') ->prototype('scalar')->end() ->end() @@ -44,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..1ca00ec 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -10,7 +10,7 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { - protected static $storageServices = array(); + protected $storageServices = array(); public function load(array $configs, ContainerBuilder $container) { @@ -35,6 +35,7 @@ class OneupUploaderExtension extends Extension } $container->setParameter('oneup_uploader.orphanage', $config['orphanage']); + //$config['orphanage']['storage'] = $this->registerStorageService($container, $config['orphanage']); // handle mappings foreach($config['mappings'] as $key => $mapping) @@ -46,22 +47,20 @@ class OneupUploaderExtension extends Extension $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); - $mapping['storage'] = $this->registerStorageService($container, $mapping); - $this->registerServicesPerMap($container, $key, $mapping); + $mapping['storage'] = $this->registerStorageService($container, $mapping['filesystem']); + $this->registerServicesPerMap($container, $key, $mapping, $config); } } - protected function registerStorageService(ContainerBuilder $container, $mapping) + protected function registerStorageService(ContainerBuilder $container, $filesystem) { - $storage = $mapping['storage']; - - // if service has already been declared, return - if(in_array($storage, self::$storageServices)) - return; - // get base name of gaufrette storage - $name = explode('.', $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); @@ -70,39 +69,34 @@ class OneupUploaderExtension extends Extension ->register($service, $container->getParameter('oneup_uploader.storage.class')) // inject the actual gaufrette filesystem - ->addArgument(new Reference($storage)) - - ->addArgument(new Reference('oneup_uploader.deletable_manager')) + ->addArgument(new Reference($filesystem)) ; - self::$storageServices[] = $name; + $this->storageServices[] = $name; return $service; } - protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping) + protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping, $config) { if($mapping['use_orphanage']) { - // this mapping want to use the orphanage, so create a typed one + $orphanage = sprintf('oneup_uploader.orphanage.%s', $type); + + // this mapping wants to use the orphanage, so create + // a masked filesystem for the controller $container - ->register(sprintf('oneup_uploader.orphanage.%s', $type), $container->getParameter('oneup_uploader.orphanage.class')) + ->register($orphanage, $container->getParameter('oneup_uploader.orphanage.class')) + ->addArgument(new Reference($config['orphanage']['filesystem'])) + ->addArgument(new Reference($mapping['filesystem'])) ->addArgument(new Reference('session')) - ->addArgument(new Reference($mapping['storage'])) - ->addArgument($container->getParameter('oneup_uploader.orphanage')) + ->addArgument($config['orphanage']) ->addArgument($type) ; - $container - ->getDefinition('oneup_uploader.orphanage_manager') - - // add this service to the orphanage manager - ->addMethodCall('addImplementation', array( - $type, - new Reference(sprintf('oneup_uploader.orphanage.%s', $type)) - )) - ; + // switch storage of mapping to orphanage + $mapping['storage'] = $orphanage; } // create controllers based on mapping diff --git a/Event/PostDeleteEvent.php b/Event/PostDeleteEvent.php deleted file mode 100644 index 0528225..0000000 --- a/Event/PostDeleteEvent.php +++ /dev/null @@ -1,35 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Event; - -use Symfony\Component\EventDispatcher\Event; -use Symfony\Component\HttpFoundation\Request; - -class PostDeleteEvent extends Event -{ - protected $requets; - protected $uuid; - protected $type; - - public function __construct(Request $request, $uuid, $type) - { - $this->request = $request; - $this->uuid = $uuid; - $this->type = $type; - } - - public function getRequest() - { - return $this->request; - } - - public function getUuid() - { - return $this->uuid; - } - - public function getType() - { - return $this->type; - } -} \ No newline at end of file diff --git a/EventListener/DeletableListener.php b/EventListener/DeletableListener.php deleted file mode 100644 index 38c752b..0000000 --- a/EventListener/DeletableListener.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; - -use Oneup\UploaderBundle\Event\PostUploadEvent; -use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Uploader\Deletable\DeletableManagerInterface; - -class DeletableListener implements EventSubscriberInterface -{ - protected $manager; - - public function __construct(DeletableManagerInterface $manager) - { - $this->manager = $manager; - } - - public function register(PostUploadEvent $event) - { - $options = $event->getOptions(); - $request = $event->getRequest(); - $file = $event->getFile(); - $type = $event->getType(); - - if(!array_key_exists('deletable', $options) || !$options['deletable']) - return; - - if(!array_key_exists('file_name', $options)) - return; - - $uuid = $request->get('qquuid'); - - $this->manager->addFile($type, $uuid, $options['file_name']); - } - - public static function getSubscribedEvents() - { - return array( - UploadEvents::POST_UPLOAD => 'register', - ); - } -} diff --git a/EventListener/OrphanageListener.php b/EventListener/OrphanageListener.php deleted file mode 100644 index f830b39..0000000 --- a/EventListener/OrphanageListener.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\EventListener; - -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; - -use Oneup\UploaderBundle\Event\PostUploadEvent; -use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; - -class OrphanageListener implements EventSubscriberInterface -{ - protected $manager; - - public function __construct(OrphanageManagerInterface $manager) - { - $this->manager = $manager; - } - - public function add(PostUploadEvent $event) - { - $options = $event->getOptions(); - $request = $event->getRequest(); - $file = $event->getFile(); - $type = $event->getType(); - - if(!array_key_exists('use_orphanage', $options) || !$options['use_orphanage']) - return; - - $this->manager->get($type)->addFile($file, $options['file_name']); - } - - public static function getSubscribedEvents() - { - return array( - UploadEvents::POST_UPLOAD => 'add', - ); - } -} \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index fad0080..b74071a 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -4,16 +4,12 @@ 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> <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> <parameter key="oneup_uploader.storage.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> - <parameter key="oneup_uploader.listener.orphanage.class">Oneup\UploaderBundle\EventListener\OrphanageListener</parameter> - <parameter key="oneup_uploader.listener.deletable.class">Oneup\UploaderBundle\EventListener\DeletableListener</parameter> + <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\OrphanageStorage</parameter> </parameters> <services> @@ -21,38 +17,14 @@ <argument>%oneup_uploader.chunks%</argument> </service> - <!-- orphanage --> - <service id="oneup_uploader.orphanage_manager" class="%oneup_uploader.orphanage.manager.class%"> - <argument type="service" id="service_container" /> - <argument>%oneup_uploader.orphanage%</argument> - </service> - <!-- namer --> <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" /> - <!-- 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" /> </service> - <!-- events --> - <service id="oneup_uploader.listener.orphanage" class="%oneup_uploader.listener.orphanage.class%"> - <argument type="service" id="oneup_uploader.orphanage_manager" /> - - <tag name="kernel.event_subscriber" /> - </service> - - <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/Routing/RouteLoader.php b/Routing/RouteLoader.php index 726e84d..3ccc0a0 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -38,21 +38,7 @@ class RouteLoader extends Loader array('_method' => 'POST') ); - $delete = new Route( - sprintf('/_uploader/%s/delete/{uuid}', $type), - array('_controller' => $service . ':delete', '_format' => 'json'), - array('_method' => 'DELETE', 'uuid' => '[A-z0-9-]*') - ); - - $base = new Route( - sprintf('/_uploader/%s/delete', $type), - array('_controller' => $service . ':delete', '_format' => 'json'), - array('_method' => 'DELETE') - ); - $routes->add(sprintf('_uploader_%s_upload', $type), $upload); - $routes->add(sprintf('_uploader_%s_delete', $type), $delete); - $routes->add(sprintf('_uploader_%s_delete_base', $type), $base); } return $routes; diff --git a/UploadEvents.php b/UploadEvents.php index f272c9d..6a9967b 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -6,5 +6,4 @@ final class UploadEvents { const POST_PERSIST = 'oneup.uploader.post.persist'; const POST_UPLOAD = 'oneup.uploader.post.upload'; - const POST_DELETE = 'oneup.uploader.post.delete'; } \ 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 diff --git a/Uploader/Orphanage/OrphanageInterface.php b/Uploader/Orphanage/OrphanageInterface.php deleted file mode 100644 index 00b584a..0000000 --- a/Uploader/Orphanage/OrphanageInterface.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Symfony\Component\HttpFoundation\File\File; - -interface OrphanageInterface -{ - public function addFile(File $file, $name); - public function uploadFiles($keep = false); -} diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php deleted file mode 100644 index 13d0d4b..0000000 --- a/Uploader/Orphanage/OrphanageManager.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Symfony\Component\Finder\Finder; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\DependencyInjection\ContainerInterface; - -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; - -class OrphanageManager implements OrphanageManagerInterface -{ - protected $container; - protected $configuration; - protected $orphanages; - - public function __construct(ContainerInterface $container, array $configuration) - { - $this->container = $container; - $this->configuration = $configuration; - $this->orphanages = array(); - } - - public function warmup() - { - $fileSystem = new FileSystem(); - $fileSystem->mkdir($this->configuration['directory']); - } - - public function clear() - { - $system = new Filesystem(); - $finder = new Finder(); - - try - { - $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds')->files(); - } - catch(\InvalidArgumentException $e) - { - // the finder will throw an exception of type InvalidArgumentException - // if the directory he should search in does not exist - // in that case we don't have anything to clean - return; - } - - foreach($finder as $file) - { - $system->remove($file); - } - } - - public function get($type) - { - return $this->getImplementation($type); - } - - public function getImplementation($type) - { - if(!array_key_exists($type, $this->orphanages)) - throw new \InvalidArgumentException(sprintf('No Orphanage implementation of type "%s" found.', $type)); - - return $this->orphanages[$type]; - } - - public function addImplementation($type, OrphanageInterface $orphanage) - { - $this->orphanages[$type] = $orphanage; - } -} \ No newline at end of file diff --git a/Uploader/Orphanage/OrphanageManagerInterface.php b/Uploader/Orphanage/OrphanageManagerInterface.php deleted file mode 100644 index 01bf0dc..0000000 --- a/Uploader/Orphanage/OrphanageManagerInterface.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Orphanage; - -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; - -interface OrphanageManagerInterface -{ - public function warmup(); - public function clear(); - public function getImplementation($type); - public function addImplementation($type, OrphanageInterface $orphanage); -} \ No newline at end of file diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index f0a7430..66b074f 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -8,17 +8,14 @@ use Gaufrette\StreamMode; use Gaufrette\Filesystem; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Deletable\DeletableManagerInterface; class GaufretteStorage implements StorageInterface { protected $filesystem; - protected $deletableManager; - public function __construct(Filesystem $filesystem, DeletableManagerInterface $deletableManager) + public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; - $this->deletableManager = $deletableManager; } public function upload(File $file, $name = null) @@ -49,29 +46,4 @@ class GaufretteStorage implements StorageInterface return $this->filesystem->get($name); } - - public function remove($type, $uuid) - { - try - { - // get associated file path - $name = $this->deletableManager->getFile($type, $uuid); - - if($this->filesystem->has($name)) - { - $this->filesystem->delete($name); - } - - // delete this reference anyway - $this->deletableManager->removeFile($type, $uuid); - } - catch(\Exception $e) - { - // whoopsi, something went terribly wrong - // better leave this method now and never look back - return false; - } - - return true; - } } \ No newline at end of file diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Storage/OrphanageStorage.php similarity index 60% rename from Uploader/Orphanage/Orphanage.php rename to Uploader/Storage/OrphanageStorage.php index 138d692..f7f7aad 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -1,38 +1,39 @@ <?php -namespace Oneup\UploaderBundle\Uploader\Orphanage; +namespace Oneup\UploaderBundle\Uploader\Storage; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpFoundation\File\UploadedFile; -use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; +use Gaufrette\Filesystem as GaufretteFilesystem; -class Orphanage implements OrphanageInterface +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; +use Oneup\UploaderBundle\Uploader\Storage\OrphanageStorageInterface; + +class OrphanageStorage extends GaufretteStorage implements OrphanageStorageInterface { + protected $masked; protected $session; - protected $storage; - protected $namer; protected $config; protected $type; - public function __construct(SessionInterface $session, StorageInterface $storage, $config, $type) + public function __construct(GaufretteFilesystem $orphanage, GaufretteFilesystem $filesystem, SessionInterface $session, $config, $type) { + parent::__construct($orphanage); + + $this->masked = $filesystem; $this->session = $session; - $this->storage = $storage; - $this->config = $config; - $this->type = $type; + $this->config = $config; + $this->type = $type; } - public function addFile(File $file, $name) + public function upload(File $file, $name = null) { if(!$this->session->isStarted()) throw new \RuntimeException('You need a running session in order to run the Orphanage.'); - // move file to orphanage - return $file->move($this->getPath(), $name); + parent::upload($file, $name); } public function uploadFiles($keep = false) @@ -40,16 +41,18 @@ class Orphanage implements OrphanageInterface $system = new Filesystem(); $finder = new Finder(); + // switch orphanage with masked filesystem + $this->filesystem = $this->masked; + if(!$system->exists($this->getPath())) return array(); $finder->in($this->getPathRelativeToSession())->files(); $uploaded = array(); - foreach($finder as $file) { - $uploaded[] = $this->storage->upload(new UploadedFile($file->getPathname(), $file->getBasename(), null, null, null, true)); + $uploaded[] = $this->upload(new UploadedFile($file->getPathname(), $file->getBasename(), null, null, null, true)); if(!$keep) { diff --git a/Uploader/Storage/OrphanageStorageInterface.php b/Uploader/Storage/OrphanageStorageInterface.php new file mode 100644 index 0000000..de0eb47 --- /dev/null +++ b/Uploader/Storage/OrphanageStorageInterface.php @@ -0,0 +1,11 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use Symfony\Component\HttpFoundation\File\File; +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; + +interface OrphanageStorageInterface extends StorageInterface +{ + public function uploadFiles($keep = false); +} diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 38eb9c8..74a63df 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -7,5 +7,4 @@ use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { public function upload(File $file, $name); - public function remove($type, $uuid); } \ No newline at end of file
0
5d35826c408e0a48e01b081be90fcf7665348971
1up-lab/OneupUploaderBundle
Update README.md
commit 5d35826c408e0a48e01b081be90fcf7665348971 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 18:32:17 2013 +0300 Update README.md diff --git a/README.md b/README.md index 292b3cb..821a85c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ OneupUploaderBundle =================== -The OneupUploaderBundle adds support for handling file uploads using one of the following Javascript libraries to your Symfony2 application: +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/index.md). * [FineUploader](http://fineuploader.com/) * [jQuery File Uploader](http://blueimp.github.io/jQuery-File-Upload/)
0
fc4750b9163033d009ed806fa82ec975af9fef76
1up-lab/OneupUploaderBundle
Fix single colon deprecation (#341) * Fix single colon deprecation * Drop PHP 7.0.x support, remove unused package
commit fc4750b9163033d009ed806fa82ec975af9fef76 Author: KDederichs <[email protected]> Date: Mon Jul 16 12:19:46 2018 +0200 Fix single colon deprecation (#341) * Fix single colon deprecation * Drop PHP 7.0.x support, remove unused package diff --git a/.travis.yml b/.travis.yml index 6c5d8bd..0cc8236 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 7.0 - 7.1 - 7.2 diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index b26289f..dda6d65 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -30,7 +30,7 @@ class RouteLoader extends Loader $upload = new Route( $options['endpoints']['upload'] ?: sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), - ['_controller' => $service.':upload', '_format' => 'json'], + ['_controller' => $service.'::upload', '_format' => 'json'], [], [], '', @@ -41,7 +41,7 @@ class RouteLoader extends Loader if (true === $options['enable_progress']) { $progress = new Route( $options['endpoints']['progress'] ?: sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), - ['_controller' => $service.':progress', '_format' => 'json'], + ['_controller' => $service.'::progress', '_format' => 'json'], [], [], '', @@ -55,7 +55,7 @@ class RouteLoader extends Loader if (true === $options['enable_cancelation']) { $progress = new Route( $options['endpoints']['cancel'] ?: sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), - ['_controller' => $service.':cancel', '_format' => 'json'], + ['_controller' => $service.'::cancel', '_format' => 'json'], [], [], '', diff --git a/composer.json b/composer.json index 6a96aa0..9405e60 100644 --- a/composer.json +++ b/composer.json @@ -21,8 +21,7 @@ ], "require": { - "php": "^7.0", - "paragonie/random_compat": "^1.1|^2.0", + "php": "^7.1", "symfony/asset": "^3.0|^4.0", "symfony/finder": "^3.0|^4.0", "symfony/framework-bundle": "^3.0|^4.0",
0
e82d70365b044d95b033944595e452a300bbae20
1up-lab/OneupUploaderBundle
Added a Gaufrette storage test.
commit e82d70365b044d95b033944595e452a300bbae20 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 22:15:08 2013 +0200 Added a Gaufrette storage test. diff --git a/Tests/Uploader/Storage/GaufretteStorageTest.php b/Tests/Uploader/Storage/GaufretteStorageTest.php new file mode 100644 index 0000000..054d71c --- /dev/null +++ b/Tests/Uploader/Storage/GaufretteStorageTest.php @@ -0,0 +1,56 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; + +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Gaufrette\Filesystem as GaufretteFilesystem; +use Gaufrette\Adapter\Local as Adapter; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; + +class GaufretteStorageTest extends \PHPUnit_Framework_TestCase +{ + protected $directory; + protected $storage; + + public function setUp() + { + $this->directory = sys_get_temp_dir() . '/storage'; + + // create temporary file + $this->file = tempnam(sys_get_temp_dir(), 'uploader'); + + $pointer = fopen($this->file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + $adapter = new Adapter($this->directory, true); + $filesystem = new GaufretteFilesystem($adapter); + + $this->storage = new GaufretteStorage($filesystem); + } + + public function testUpload() + { + $payload = new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true); + $this->storage->upload($payload, 'notsogrumpyanymore.jpeg'); + + $finder = new Finder(); + $finder->in($this->directory)->files(); + + $this->assertCount(1, $finder); + + foreach($finder as $file) + { + $this->assertEquals($file->getFilename(), 'notsogrumpyanymore.jpeg'); + $this->assertEquals($file->getSize(), 1024); + } + } + + public function tearDown() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->directory); + } +} \ No newline at end of file
0
3cee34e31747db8f6d4f541c9d422d2fbf6fc3a5
1up-lab/OneupUploaderBundle
Fixed "unused code" labels in Scrutinizer report.
commit 3cee34e31747db8f6d4f541c9d422d2fbf6fc3a5 Author: Jim Schmid <[email protected]> Date: Tue Oct 8 21:30:36 2013 +0200 Fixed "unused code" labels in Scrutinizer report. 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/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/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index ed7931e..d6915e0 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -2,7 +2,6 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; @@ -18,8 +17,6 @@ class FilesystemStorage implements StorageInterface public function upload(File $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/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 2fbd349..f2229d0 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -43,7 +43,7 @@ class GaufretteStorage implements StorageInterface while (!$src->eof()) { $data = $src->read($this->bufferSize); - $written = $dst->write($data); + $dst->write($data); } $dst->close(); diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/OrphanageStorage.php index d0787d0..fcbbaf0 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -5,7 +5,6 @@ namespace Oneup\UploaderBundle\Uploader\Storage; 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; @@ -38,8 +37,6 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte public function uploadFiles() { - $filesystem = new Filesystem(); - try { $files = $this->getFiles(); $return = array();
0
bff5b86c5477d0dd05b488aa5498324b376d9673
1up-lab/OneupUploaderBundle
Removed confusing function call. This addresses #26 and #15.
commit bff5b86c5477d0dd05b488aa5498324b376d9673 Author: Jim Schmid <[email protected]> Date: Sun Jul 14 11:19:37 2013 +0200 Removed confusing function call. This addresses #26 and #15. diff --git a/Resources/doc/response.md b/Resources/doc/response.md index ed7e449..d55192c 100644 --- a/Resources/doc/response.md +++ b/Resources/doc/response.md @@ -20,8 +20,8 @@ class UploadListener The `UploaderResponse` class implements the `ArrayAccess` interface, so you can just add data using it like an array: ```php -$response['id'] = $uploadedImage->getId(); -$response['url'] = $uploadedImage->getUrl(); +$response['id'] = $id; +$response['url'] = $url; ``` If you like to indicate an error, be sure to set the `success` property to `false` and provide an error message: @@ -31,4 +31,4 @@ $response->setSuccess(false); $response->setError($msg); ``` -> Do not use the keys `success` and `error` if you provide custom data, they will be overwritten by the internal properties of `UploaderResponse`. \ No newline at end of file +> Do not use the keys `success` and `error` if you provide custom data, they will be overwritten by the internal properties of `UploaderResponse`.
0
1fe30e7afcb0cd9965701c34f61902011a895aec
1up-lab/OneupUploaderBundle
Merge pull request #177 from foaly-nr1/patch-container-has Wrapper for container method has
commit 1fe30e7afcb0cd9965701c34f61902011a895aec (from 6594095e71e484f4afcdac55639fe614a7c7bebc) Merge: 6594095 a017c39 Author: Jim Schmid <[email protected]> Date: Tue Jun 2 15:42:29 2015 +0200 Merge pull request #177 from foaly-nr1/patch-container-has 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
790a534de46dba1db1ed331c2416cac450267774
1up-lab/OneupUploaderBundle
Merge branch 'error-handling-doc' of https://github.com/lsv/OneupUploaderBundle into lsv-error-handling-doc
commit 790a534de46dba1db1ed331c2416cac450267774 (from 210707fefc9f9fe9d14e5aefe361ad7e6c346ef7) Merge: 210707f 68af022 Author: David Greminger <[email protected]> Date: Mon Jan 4 10:09:46 2016 +0100 Merge branch 'error-handling-doc' of https://github.com/lsv/OneupUploaderBundle into lsv-error-handling-doc 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'); +} +``` commit 790a534de46dba1db1ed331c2416cac450267774 (from 68af0229f159a7d62225c5d503cbf4fa8ca7b1ca) Merge: 210707f 68af022 Author: David Greminger <[email protected]> Date: Mon Jan 4 10:09:46 2016 +0100 Merge branch 'error-handling-doc' of https://github.com/lsv/OneupUploaderBundle into lsv-error-handling-doc diff --git a/.travis.yml b/.travis.yml index 5a3affa..f81a416 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,24 +5,42 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 - hhvm env: - - SYMFONY_VERSION=2.3.* + - SYMFONY_VERSION=2.4.* + - SYMFONY_VERSION=2.7.* + - SYMFONY_VERSION=2.8.* + +cache: + directories: + - $COMPOSER_CACHE_DIR matrix: allow_failures: - - env: SYMFONY_VERSION=dev-master - php: hhvm + - php: 7.0 + - env: SYMFONY_VERSION=dev-master + include: - - php: 5.5 + - 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/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index aec580d..7f35224 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -115,7 +115,6 @@ class OneupUploaderExtension extends Extension ->addArgument($key) ->addTag('oneup_uploader.routable', array('type' => $key)) - ->setScope('request') ; return $controllerName; 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_error_handler.md b/Resources/doc/custom_error_handler.md index 9fefa4c..8c1e248 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 0a1b39a..ccb915e 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_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/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 } +``` 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..b2f32a3 100644 --- a/composer.json +++ b/composer.json @@ -15,18 +15,18 @@ ], "require": { - "symfony/framework-bundle": ">=2.2", - "symfony/finder": ">=2.2.0" + "symfony/framework-bundle": "^2.4.0|~3.0", + "symfony/finder": "^2.4.0|~3.0" }, "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", "knplabs/gaufrette": "0.2.*@dev", - "symfony/class-loader": "2.*", - "symfony/security-bundle": "2.*", - "sensio/framework-extra-bundle": "2.*", - "symfony/browser-kit": "2.*", - "phpunit/phpunit": "~4.1" + "symfony/class-loader": "2.*|~3.0", + "symfony/security-bundle": "2.*|~3.0", + "sensio/framework-extra-bundle": "2.*|~3.0", + "symfony/browser-kit": "2.*|~3.0", + "phpunit/phpunit": "~4.4" }, "suggest": {
0
6b5a2b6aa5d833ed6460e67daa5615504c74b0f4
1up-lab/OneupUploaderBundle
Added a dispatched POST_UPLOAD event. Will be used for session storage or custom logic (for example orm-bindings..)
commit 6b5a2b6aa5d833ed6460e67daa5615504c74b0f4 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 09:29:02 2013 +0100 Added a dispatched POST_UPLOAD event. Will be used for session storage or custom logic (for example orm-bindings..) diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 7314147..6d29961 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -3,6 +3,8 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\StoreEvents; use Oneup\UploaderBundle\Controller\UploadControllerInterface; class UploaderController implements UploadControllerInterface @@ -10,12 +12,13 @@ class UploaderController implements UploadControllerInterface protected $namer; protected $storage; - public function __construct($request, $namer, $storage, $config) + public function __construct($request, $namer, $storage, $config, $dispatcher) { $this->request = $request; $this->namer = $namer; $this->storage = $storage; $this->config = $config; + $this->dispatcher = $dispatcher; } public function upload() @@ -33,7 +36,11 @@ class UploaderController implements UploadControllerInterface foreach($files as $file) { $name = $this->namer->name($file, $this->config['directory_prefix']); - $this->storage->upload($file, $name); + $uploaded = $this->storage->upload($file, $name); + + // dispatch POST_UPLOAD event + $event = new PostUploadEvent($uploaded, $request); + $this->dispatcher->dispatch(StoreEvents::POST_UPLOAD, $event); } return new JsonResponse(array('success' => true)); diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 2640c61..8d26404 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -93,6 +93,9 @@ class OneupUploaderExtension extends Extension // after all, add the config as argument ->addArgument($mapping) + // we need the EventDispatcher for post upload events + ->addArgument(new Reference('event.dispatcher')) + ->addTag('oneup_uploader.routable', array('type' => $type)) ->setScope('request') ; diff --git a/Event/PostUploadEvent.php b/Event/PostUploadEvent.php new file mode 100644 index 0000000..a24af56 --- /dev/null +++ b/Event/PostUploadEvent.php @@ -0,0 +1,31 @@ +<?php + +namespace Oneup\UploaderBundle\Event; + +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\HttpFoundation\Request; + +use Gaufrette\File; + +class PostUploadEvent extends Event +{ + protected $file; + protected $request; + + public function __construct(File $file, Request $request) + { + $this->file = $file; + $this->request = $request; + } + + public function getFile() + { + return $this->file; + } + + public function getRequest() + { + return $this->request; + } +} \ No newline at end of file diff --git a/UploadEvents.php b/UploadEvents.php new file mode 100644 index 0000000..39adf0b --- /dev/null +++ b/UploadEvents.php @@ -0,0 +1,8 @@ +<?php + +namespace Oneup\UploaderBundle; + +final class UploadEvents +{ + const POST_UPLOAD = 'oneup.uploader.post.upload'; +} \ No newline at end of file diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index b6918c6..4268814 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -42,7 +42,7 @@ class GaufretteStorage implements StorageInterface $dst->close(); $src->close(); - return true; + return $this->filesystem->get($name); } public function remove(File $file)
0
6de0e1fb347514cf85565a0ec373df979fcf6365
1up-lab/OneupUploaderBundle
Cleanup after upload.
commit 6de0e1fb347514cf85565a0ec373df979fcf6365 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 15:23:34 2013 +0100 Cleanup after upload. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 97d7550..6feeed0 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -84,8 +84,11 @@ class UploaderController implements UploadControllerInterface // assemble parts $assembled = $this->chunkManager->assembleChunks($chunks); + $path = $assembled->getPath(); - return $this->handleUpload(new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, null, null, true)); + $ret = $this->handleUpload(new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, null, null, true)); + + $this->chunkManager->cleanup($path); } return new JsonResponse(array('success' => true)); diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 1da9eb3..3e58f00 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -84,6 +84,15 @@ class ChunkManager implements ChunkManagerInterface return $base; } + public function cleanup($path) + { + // cleanup + $filesystem = new Filesystem(); + $filesystem->remove($path); + + return true; + } + public function getChunks($uuid) { $finder = new Finder();
0
f9d820ab679f7c4942f90ea0e13847a23ef0a0d4
1up-lab/OneupUploaderBundle
BlueimpController: cast chunk index to integer (#379)
commit f9d820ab679f7c4942f90ea0e13847a23ef0a0d4 Author: mjedlick2 <[email protected]> Date: Mon Jul 6 16:54:07 2020 +0200 BlueimpController: cast chunk index to integer (#379) diff --git a/src/Controller/BlueimpController.php b/src/Controller/BlueimpController.php index a288759..126584a 100644 --- a/src/Controller/BlueimpController.php +++ b/src/Controller/BlueimpController.php @@ -76,7 +76,7 @@ class BlueimpController extends AbstractChunkedController // previously saved files, let me know. $size = ((int) $endByte + 1 - (int) $startByte); $last = ((int) $endByte + 1) === (int) $totalBytes; - $index = $last ? \PHP_INT_MAX : floor($startByte / $size); + $index = $last ? \PHP_INT_MAX : (int) floor($startByte / $size); // it is possible, that two clients send a file with the // exact same filename, therefore we have to add the session
0
e5de39a8cf22dbc4a00faadaafb60824afd80ffe
1up-lab/OneupUploaderBundle
Rearranged configuration, so it will use the correct storage and filesystem layer.
commit e5de39a8cf22dbc4a00faadaafb60824afd80ffe Author: Jim Schmid <[email protected]> Date: Thu Mar 28 12:36:23 2013 +0100 Rearranged configuration, so it will use the correct storage and filesystem layer. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 10ffce6..7ca7320 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -79,6 +79,7 @@ class UploaderController implements UploadControllerInterface throw new UploadException('This extension is not allowed.'); $name = $this->namer->name($file, $this->config['directory_prefix']); + $uploaded = $this->storage->upload($file, $name); $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( 'use_orphanage' => $this->config['use_orphanage'], @@ -88,8 +89,6 @@ class UploaderController implements UploadControllerInterface if(!$this->config['use_orphanage']) { - $uploaded = $this->storage->upload($file, $name); - // dispatch post upload event $postPersistEvent = new PostPersistEvent($uploaded, $this->request, $this->type); $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index a90043b..9987fb7 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -18,7 +18,7 @@ class Configuration implements ConfigurationInterface ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled')->defaultFalse()->end() - ->scalarNode('storage')->defaultNull()->end() + ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->end() ->end() @@ -26,7 +26,7 @@ class Configuration implements ConfigurationInterface ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled')->defaultFalse()->end() - ->scalarNode('storage')->defaultNull()->end() + ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('maxage')->defaultValue(604800)->end() ->end() ->end() @@ -36,7 +36,7 @@ class Configuration implements ConfigurationInterface ->requiresAtLeastOneElement() ->prototype('array') ->children() - ->scalarNode('storage')->isRequired()->end() + ->scalarNode('filesystem')->isRequired()->end() ->arrayNode('allowed_types') ->prototype('scalar')->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 91e4520..1ca00ec 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -10,7 +10,7 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { - protected static $storageServices = array(); + protected $storageServices = array(); public function load(array $configs, ContainerBuilder $container) { @@ -35,6 +35,7 @@ class OneupUploaderExtension extends Extension } $container->setParameter('oneup_uploader.orphanage', $config['orphanage']); + //$config['orphanage']['storage'] = $this->registerStorageService($container, $config['orphanage']); // handle mappings foreach($config['mappings'] as $key => $mapping) @@ -46,22 +47,20 @@ class OneupUploaderExtension extends Extension $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); - $mapping['storage'] = $this->registerStorageService($container, $mapping); - $this->registerServicesPerMap($container, $key, $mapping); + $mapping['storage'] = $this->registerStorageService($container, $mapping['filesystem']); + $this->registerServicesPerMap($container, $key, $mapping, $config); } } - protected function registerStorageService(ContainerBuilder $container, $mapping) + protected function registerStorageService(ContainerBuilder $container, $filesystem) { - $storage = $mapping['storage']; - - // if service has already been declared, return - if(in_array($storage, self::$storageServices)) - return; - // get base name of gaufrette storage - $name = explode('.', $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); @@ -70,37 +69,34 @@ class OneupUploaderExtension extends Extension ->register($service, $container->getParameter('oneup_uploader.storage.class')) // inject the actual gaufrette filesystem - ->addArgument(new Reference($storage)) + ->addArgument(new Reference($filesystem)) ; - self::$storageServices[] = $name; + $this->storageServices[] = $name; return $service; } - protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping) + protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping, $config) { if($mapping['use_orphanage']) { - // this mapping want to use the orphanage, so create a typed one + $orphanage = sprintf('oneup_uploader.orphanage.%s', $type); + + // this mapping wants to use the orphanage, so create + // a masked filesystem for the controller $container - ->register(sprintf('oneup_uploader.orphanage.%s', $type), $container->getParameter('oneup_uploader.orphanage.class')) + ->register($orphanage, $container->getParameter('oneup_uploader.orphanage.class')) + ->addArgument(new Reference($config['orphanage']['filesystem'])) + ->addArgument(new Reference($mapping['filesystem'])) ->addArgument(new Reference('session')) - ->addArgument(new Reference($mapping['storage'])) - ->addArgument($container->getParameter('oneup_uploader.orphanage')) + ->addArgument($config['orphanage']) ->addArgument($type) ; - $container - ->getDefinition('oneup_uploader.orphanage_manager') - - // add this service to the orphanage manager - ->addMethodCall('addImplementation', array( - $type, - new Reference(sprintf('oneup_uploader.orphanage.%s', $type)) - )) - ; + // switch storage of mapping to orphanage + $mapping['storage'] = $orphanage; } // create controllers based on mapping diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/OrphanageStorage.php index a463039..f7f7aad 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -1,12 +1,15 @@ <?php -namespace Oneup\UploaderBundle\Storage; +namespace Oneup\UploaderBundle\Uploader\Storage; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -use Gaufrette\Filesystem; +use Gaufrette\Filesystem as GaufretteFilesystem; -use Oneup\UploaderBundle\Storage\GaufretteStorage; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; +use Oneup\UploaderBundle\Uploader\Storage\OrphanageStorageInterface; class OrphanageStorage extends GaufretteStorage implements OrphanageStorageInterface { @@ -15,7 +18,7 @@ class OrphanageStorage extends GaufretteStorage implements OrphanageStorageInter protected $config; protected $type; - public function __construct(Gaufrette $orphanage, Gaufrette $filesystem, SessionInterface $session, $config, $type) + public function __construct(GaufretteFilesystem $orphanage, GaufretteFilesystem $filesystem, SessionInterface $session, $config, $type) { parent::__construct($orphanage);
0
dfc20db7f208af02bb98f97eedb786c26b2a2117
1up-lab/OneupUploaderBundle
Initial directory structure and bundle initialization files.
commit dfc20db7f208af02bb98f97eedb786c26b2a2117 Author: Jim Schmid <[email protected]> Date: Fri Mar 8 17:48:52 2013 +0100 Initial directory structure and bundle initialization files. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php new file mode 100644 index 0000000..2c20ba1 --- /dev/null +++ b/DependencyInjection/Configuration.php @@ -0,0 +1,17 @@ +<?php + +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'); + + return $treeBuilder; + } +} \ No newline at end of file diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php new file mode 100644 index 0000000..3a77172 --- /dev/null +++ b/DependencyInjection/OneupUploaderExtension.php @@ -0,0 +1,20 @@ +<?php + +namespace Oneup\UploaderBundle\DependencyInjection; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\Config\FileLocator; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\Loader; + +class OneupUploaderExtension extends Extension +{ + 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'); + } +} \ No newline at end of file diff --git a/OneupUploaderBundle.php b/OneupUploaderBundle.php new file mode 100644 index 0000000..22c1af9 --- /dev/null +++ b/OneupUploaderBundle.php @@ -0,0 +1,9 @@ +<?php + +namespace Oneup\UploaderBundle; + +use Symfony\Component\HttpKernel\Bundle\Bundle; + +class OneupUploaderBundle extends Bundle +{ +} \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml new file mode 100644 index 0000000..f32be1c --- /dev/null +++ b/Resources/config/uploader.xml @@ -0,0 +1,6 @@ +<?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"> + +</container> \ No newline at end of file
0
240cab6337adea2f3bc9061ce3c3ee20bca4cbea
1up-lab/OneupUploaderBundle
Used BlueimpResponse in corresponding Controller.
commit 240cab6337adea2f3bc9061ce3c3ee20bca4cbea Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:57:40 2013 +0200 Used BlueimpResponse in corresponding Controller. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index cc02d77..9181860 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -12,7 +12,7 @@ use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Controller\UploadControllerInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; +use Oneup\UploaderBundle\Uploader\Response\BlueimpResponse; class BlueimpController implements UploadControllerInterface { @@ -35,7 +35,7 @@ class BlueimpController implements UploadControllerInterface $dispatcher = $this->container->get('event_dispatcher'); $translator = $this->container->get('translator'); - $response = new UploaderResponse(); + $response = new BlueimpResponse(); $files = $request->files; foreach($files as $file) @@ -66,7 +66,7 @@ class BlueimpController implements UploadControllerInterface } } - return new JsonResponse(array('files' => array())); + return new JsonResponse($response->assemble()); } protected function handleUpload(UploadedFile $file) diff --git a/Uploader/Response/BlueimpResponse.php b/Uploader/Response/BlueimpResponse.php index 60be67b..e5fd1a3 100644 --- a/Uploader/Response/BlueimpResponse.php +++ b/Uploader/Response/BlueimpResponse.php @@ -14,7 +14,7 @@ class BlueimpResponse extends AbstractResponse public function __construct() { - $this->success = array(); + $this->files = array(); parent::__construct(); }
0
c5a87ee373d09696d40afacb9cf5b81e8b6b4702
1up-lab/OneupUploaderBundle
don't test for sf2.1
commit c5a87ee373d09696d40afacb9cf5b81e8b6b4702 Author: mitom <[email protected]> Date: Thu Oct 10 20:22:09 2013 +0200 don't test for sf2.1 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.*
0
cab0860a44d257dcc6a4a2b1f94d1237fe1765b6
1up-lab/OneupUploaderBundle
Refactored the way Chunks are reassembled. Removed a rather hacky way of determine which of the chunks to use as a base, and replaced it with an Iterator as mentioned in #21.
commit cab0860a44d257dcc6a4a2b1f94d1237fe1765b6 Author: Jim Schmid <[email protected]> Date: Mon Jun 24 14:08:30 2013 +0200 Refactored the way Chunks are reassembled. Removed a rather hacky way of determine which of the chunks to use as a base, and replaced it with an Iterator as mentioned in #21. diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index b1dcf23..f5bc733 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -49,23 +49,20 @@ class ChunkManager implements ChunkManagerInterface public function assembleChunks(\Traversable $chunks) { - // I don't really get it why getIterator()->current() always - // gives me a null-value, due to that I've to implement this - // in a rather unorthodox way. - $i = 0; - $base = null; - - foreach ($chunks as $file) { - if ($i++ == 0) { - $base = $file; - - // proceed with next files, as we have our - // base data-container - continue; - } + $iterator = $chunks->getIterator()->getInnerIterator(); + + $base = $iterator->current(); + $iterator->next(); + + while ($iterator->valid()) { - if(false === file_put_contents($base->getPathname(), file_get_contents($file->getPathname()), \FILE_APPEND | \LOCK_EX)) + $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.'); + } + + $iterator->next(); } return $base;
0
dc7a0e41b92a256a61627385ac7e621f819a383c
1up-lab/OneupUploaderBundle
Merge branch 'mhlavac-patch-1'
commit dc7a0e41b92a256a61627385ac7e621f819a383c (from 5ec3508c5a8ddcbd9a4d96b77e5b415a15599806) Merge: 5ec3508 fc9d5c1 Author: David Greminger <[email protected]> Date: Thu Dec 15 09:28:57 2016 +0100 Merge branch 'mhlavac-patch-1' diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 0d472ff..86fd9f6 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -292,7 +292,7 @@ class OneupUploaderExtension extends Extension protected function getValueInBytes($input) { // see: http://www.php.net/manual/en/function.ini-get.php - $input = trim($input); + $input = (float) trim($input); $last = strtolower($input[strlen($input) - 1]); $numericInput = substr($input, 0, -1);
0