diff --git a/.styleci.yml b/.styleci.yml
index de6be917..f349be62 100644
--- a/.styleci.yml
+++ b/.styleci.yml
@@ -1,16 +1,30 @@
preset: symfony
+enabled:
+ - short_array_syntax
+
disabled:
- - multiline_array_trailing_comma
+ - cast_spaces
+ - concat_without_spaces
+ - function_declaration
+ - no_blank_lines_after_phpdoc
+ - no_blank_lines_after_throw
+ - php_unit_fqcn_annotation
+ - phpdoc_align
+ - phpdoc_no_empty_return
+ - phpdoc_scalar
+ - phpdoc_separation
+ - phpdoc_summary
+ - phpdoc_to_comment
+ - phpdoc_type_to_var
- pre_increment
+ - self_accessor
- single_quote
- - concat_without_spaces
- - empty_return
- - spaces_cast
- - unalign_equals
+ - trailing_comma_in_multiline_array
- unalign_double_arrow
- - phpdoc_to_comment
- - phpdoc_annotation_without_dot
-
-enabled:
- - short_array_syntax
+ - unalign_equals
+ - blank_line_before_break
+ - blank_line_before_continue
+ - blank_line_before_declare
+ - blank_line_before_throw
+ - blank_line_before_try
diff --git a/.travis.yml b/.travis.yml
index 0718186d..c3d83e18 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -3,22 +3,31 @@ language: php
sudo: false
php:
- - 5.4
- 5.5
- 5.6
+ - 7.0
+ - 7.1
+ - 7.2
+ - nightly
matrix:
fast_finish: true
+ allow_failures:
+ - php: 7.2
+ - php: nightly
services:
- mysql
before_install:
- - if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]] && [[ "$TRAVIS_PHP_VERSION" != "hhvm" ]] && [ $(php -r "echo PHP_MINOR_VERSION;") -le 4 ]; then echo "extension = apc.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi;
- - if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]] && [[ "$TRAVIS_PHP_VERSION" != "hhvm" ]]; then (pecl install -f memcached-2.1.0 && echo "extension = memcache.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini) || echo "Let's continue without memcache extension"; fi;
- # - if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]] && [[ "$TRAVIS_PHP_VERSION" != "hhvm" ]]; then php -i; fi;
+ - if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]]; then phpenv config-rm xdebug.ini; fi;
+ # load memcache.so for php 5
+ - if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]] && [ $(php -r "echo PHP_MAJOR_VERSION;") == 5 ]; then (pecl install -f memcached-2.1.0 && echo "extension = memcache.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini) || echo "Continuing without memcache extension"; fi;
+ # load memcache.so for php >= 7.1
+ - if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]] && [ $(php -r "echo PHP_MAJOR_VERSION;") == 7 ] && [ $(php -r "echo PHP_MINOR_VERSION;") >= 1 ]; then (pecl install -f memcached-2.1.0 && echo "extension = memcache.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini) || echo "Continuing without memcache extension"; fi;
# Set the COMPOSER_ROOT_VERSION to the right version according to the branch being built
- if [ "$TRAVIS_BRANCH" = "master" ]; then export COMPOSER_ROOT_VERSION=dev-master; else export COMPOSER_ROOT_VERSION="$TRAVIS_BRANCH".x-dev; fi;
+
- composer self-update
- if [ -n "$GH_TOKEN" ]; then composer config --global github-oauth.github.com ${GH_TOKEN}; fi;
- mysql -e 'create database zk_test;'
@@ -26,12 +35,12 @@ before_install:
install:
- composer install
- zip -qr MediaModule.zip .
- - wget https://github.com/zikula/core/releases/download/1.4.3/Zikula_Core-1.4.3.build183.tar.gz
- - tar -xpzf Zikula_Core-1.4.3.build183.tar.gz
- - rm Zikula_Core-1.4.3.build183.tar.gz
- - cd Zikula_Core-1.4.3
- - php app/console zikula:install:start -n --database_user=root --database_name=zk_test --password=12345678 --email=admin@example.com --router:request_context:host=localhost
- - php app/console zikula:install:finish
+ - wget https://github.com/zikula/core/releases/download/2.0.11/2.0.tar.gz
+ - tar -xpzf 2.0.tar.gz
+ - rm 2.0.tar.gz
+ - cd 2.0
+ - php bin/console zikula:install:start -n --database_user=root --database_name=zk_test --password=12345678 --email=admin@example.com --router:request_context:host=localhost
+ - php bin/console zikula:install:finish
- cd modules
- mkdir cmfcmf
- cd cmfcmf
@@ -39,12 +48,12 @@ install:
- cd media-module
- unzip -q ../../../../MediaModule
- cd ../../..
- - php app/console bootstrap:bundles
- - mysql -e "INSERT INTO zk_test.modules (id, name, type, displayname, url, description, directory, version, capabilities, state, securityschema, core_min, core_max) VALUES (NULL, 'CmfcmfMediaModule', '3', 'Media Module', 'media', '...', 'cmfcmf/media-module', '1.2.2', 'N;', '3', 'N;', '1.4.3', '1.4.99');"
+ - php bin/console bootstrap:bundles
+ - mysql -e "INSERT INTO zk_test.modules (id, name, type, displayname, url, description, version, capabilities, state, securityschema, core_min, core_max) VALUES (NULL, 'CmfcmfMediaModule', '3', 'Media Module', 'media', '...', '1.3.0', 'N;', '3', 'N;', '2.0.11', '3.0.0');"
script:
- - php app/console lint:yaml modules/cmfcmf/media-module/Resources
- - php app/console lint:twig @CmfcmfMediaModule
+ - php bin/console lint:yaml modules/cmfcmf/media-module/Resources
+ - php bin/console lint:twig @CmfcmfMediaModule
- phpunit --configuration modules/cmfcmf/media-module/phpunit.xml.dist --coverage-text --coverage-clover=coverage.clover -v
after_success:
diff --git a/Block/CollectionBlock.php b/Block/CollectionBlock.php
index 7be13f1e..ce64e626 100644
--- a/Block/CollectionBlock.php
+++ b/Block/CollectionBlock.php
@@ -12,17 +12,24 @@
namespace Cmfcmf\Module\MediaModule\Block;
use Cmfcmf\Module\MediaModule\Entity\Collection\Repository\CollectionRepository;
+use Cmfcmf\Module\MediaModule\Form\Collection\CollectionBlockType;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Translation\TranslatorInterface;
use Zikula\BlocksModule\AbstractBlockHandler;
/**
- * Class PageBlock.
+ * Collection block handler.
*/
class CollectionBlock extends AbstractBlockHandler
{
+ /**
+ * @var TranslatorInterface
+ */
+ private $translator;
+
/**
* @var CollectionRepository
*/
@@ -38,20 +45,15 @@ class CollectionBlock extends AbstractBlockHandler
*/
private $twig;
- /**
- * @var TranslatorInterface
- */
- private $translator;
-
public function setContainer(ContainerInterface $container = null)
{
parent::setContainer($container);
+ $this->translator = $container->get('translator');
$this->collectionRepository = $container->get('doctrine.orm.entity_manager')
->getRepository('CmfcmfMediaModule:Collection\CollectionEntity');
$this->securityManager = $container->get('cmfcmf_media_module.security_manager');
$this->twig = $container->get('twig');
- $this->translator = $container->get('translator');
}
/**
@@ -78,11 +80,18 @@ public function display(array $properties)
return false;
}
- $content = $this->get('cmfcmf_media_module.collection_template_collection')->getCollectionTemplate($properties['template'])->render(
+ $selectedTemplateFactory = $this->get('cmfcmf_media_module.collection_template.selected_factory');
+ try {
+ $selectedTemplate = $selectedTemplateFactory->fromDB($properties['template']);
+ } catch (\DomainException $e) {
+ throw new NotFoundHttpException();
+ }
+
+ $content = $selectedTemplate->getTemplate()->render(
$collection,
$this->get('cmfcmf_media_module.media_type_collection'),
isset($properties['showChildCollections']) ? $properties['showChildCollections'] : false,
- [] // @todo pass template options
+ $selectedTemplate->getOptions()
);
$hook = '';
@@ -109,20 +118,7 @@ public function display(array $properties)
*/
public function getFormClassName()
{
- return 'Cmfcmf\Module\MediaModule\Form\Collection\CollectionBlockType';
- }
-
- /**
- * {@inheritdoc}
- */
- public function getFormOptions()
- {
- return [
- 'translator' => $this->translator,
- 'securityManager' => $this->securityManager,
- 'templateCollection' => $this->get('cmfcmf_media_module.collection_template_collection'),
- 'collectionRepository' => $this->collectionRepository
- ];
+ return CollectionBlockType::class;
}
/**
diff --git a/CmfcmfMediaModule.php b/CmfcmfMediaModule.php
index bed5bdde..769cbe6b 100644
--- a/CmfcmfMediaModule.php
+++ b/CmfcmfMediaModule.php
@@ -11,11 +11,11 @@
namespace Cmfcmf\Module\MediaModule;
-use Cmfcmf\Module\MediaModule\DependencyInjection\CollectionPermissionCompilerPass;
-use Cmfcmf\Module\MediaModule\DependencyInjection\CollectionTemplateCompilerPass;
-use Cmfcmf\Module\MediaModule\DependencyInjection\FontCompilerPass;
-use Cmfcmf\Module\MediaModule\DependencyInjection\ImporterCompilerPass;
-use Cmfcmf\Module\MediaModule\DependencyInjection\MediaTypeCompilerPass;
+use Cmfcmf\Module\MediaModule\DependencyInjection\Compiler\CollectionPermissionCompilerPass;
+use Cmfcmf\Module\MediaModule\DependencyInjection\Compiler\CollectionTemplateCompilerPass;
+use Cmfcmf\Module\MediaModule\DependencyInjection\Compiler\FontCompilerPass;
+use Cmfcmf\Module\MediaModule\DependencyInjection\Compiler\ImporterCompilerPass;
+use Cmfcmf\Module\MediaModule\DependencyInjection\Compiler\MediaTypeCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Zikula\Core\AbstractModule;
diff --git a/CollectionTemplate/GalleriaTemplate.php b/CollectionTemplate/GalleriaTemplate.php
index 7048a37d..f3a2a9fe 100644
--- a/CollectionTemplate/GalleriaTemplate.php
+++ b/CollectionTemplate/GalleriaTemplate.php
@@ -11,6 +11,8 @@
namespace Cmfcmf\Module\MediaModule\CollectionTemplate;
+use Cmfcmf\Module\MediaModule\Form\CollectionTemplate\GalleriaType;
+
/**
* Displays a Galleria image slider https://galleria.io/.
*/
@@ -26,7 +28,7 @@ public function getTitle()
public function getSettingsForm()
{
- return 'Cmfcmf\Module\MediaModule\Form\CollectionTemplate\GalleriaType';
+ return GalleriaType::class;
}
public function getDefaultOptions()
diff --git a/CollectionTemplate/LightGalleryTemplate.php b/CollectionTemplate/LightGalleryTemplate.php
index 5dbec8dd..88e7ce0b 100644
--- a/CollectionTemplate/LightGalleryTemplate.php
+++ b/CollectionTemplate/LightGalleryTemplate.php
@@ -11,6 +11,8 @@
namespace Cmfcmf\Module\MediaModule\CollectionTemplate;
+use Cmfcmf\Module\MediaModule\Form\CollectionTemplate\LightGalleryType;
+
/**
* Displays a light gallery http://sachinchoolur.github.io/lightGallery/.
*/
@@ -26,7 +28,7 @@ public function getTitle()
public function getSettingsForm()
{
- return 'Cmfcmf\Module\MediaModule\Form\CollectionTemplate\LightGalleryType';
+ return LightGalleryType::class;
}
public function getDefaultOptions()
diff --git a/CollectionTemplate/SelectedTemplateFactory.php b/CollectionTemplate/SelectedTemplateFactory.php
index 568af571..c3d78e72 100644
--- a/CollectionTemplate/SelectedTemplateFactory.php
+++ b/CollectionTemplate/SelectedTemplateFactory.php
@@ -18,13 +18,29 @@ class SelectedTemplateFactory
*/
private $templateCollection;
- public function __construct(TemplateCollection $templateCollection)
- {
+ /**
+ * @var string
+ */
+ private $defaultTemplate;
+
+ /**
+ * @param TemplateCollection $templateCollection
+ * @param string $defaultTemplate
+ */
+ public function __construct(
+ TemplateCollection $templateCollection,
+ $defaultTemplate
+ ) {
$this->templateCollection = $templateCollection;
+ $this->defaultTemplate = $defaultTemplate;
}
public function fromDB($jsonOrString)
{
+ if (!$jsonOrString) {
+ $jsonOrString = $this->defaultTemplate;
+ }
+
if ($this->isJSON($jsonOrString)) {
$json = json_decode($jsonOrString, true);
$template = $json['template'];
@@ -40,7 +56,7 @@ public function fromDB($jsonOrString)
public function fromTemplateName($template, array $options)
{
$template = $this->templateCollection->getCollectionTemplate($template);
- if (count($options) == 0) {
+ if (0 == count($options)) {
$options = $template->getDefaultOptions();
}
@@ -49,6 +65,6 @@ public function fromTemplateName($template, array $options)
private function isJSON($string)
{
- return strpos($string, '{') !== false;
+ return false !== strpos($string, '{');
}
}
diff --git a/CollectionTemplate/TemplateCollection.php b/CollectionTemplate/TemplateCollection.php
index 023eb9b4..88b4401e 100644
--- a/CollectionTemplate/TemplateCollection.php
+++ b/CollectionTemplate/TemplateCollection.php
@@ -53,15 +53,18 @@ public function getCollectionTemplates()
*/
public function getCollectionTemplateTitles()
{
- return array_map(function (TemplateInterface $template) {
- return $template->getTitle();
- }, $this->templates);
+ $choices = [];
+ foreach ($this->templates as $template) {
+ $choices[$template->getTitle()] = $template->getName();
+ }
+
+ return $choices;
}
/**
* Returns the specified collection template.
*
- * @param string $template The template name.
+ * @param string $template the template name
*
* @return TemplateInterface
*/
@@ -77,7 +80,7 @@ public function getCollectionTemplate($template)
/**
* Checks whether or not the specified collection template exists.
*
- * @param string $template The template name.
+ * @param string $template the template name
*
* @return bool
*/
diff --git a/Container/HookContainer.php b/Container/HookContainer.php
deleted file mode 100644
index fc67c8f4..00000000
--- a/Container/HookContainer.php
+++ /dev/null
@@ -1,96 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Cmfcmf\Module\MediaModule\Container;
-
-use Zikula\Bundle\HookBundle\AbstractHookContainer;
-use Zikula\Bundle\HookBundle\Bundle\SubscriberBundle;
-use Zikula\Bundle\HookBundle\Bundle\ProviderBundle;
-
-class HookContainer extends AbstractHookContainer
-{
- /**
- * {@inheritdoc}
- */
- protected function setupHookBundles()
- {
- $entities = [
- "collection" => $this->__("Collections"),
- "media" => $this->__("Media"),
- "license" => $this->__("Licenses"),
- ];
- foreach ($entities as $name => $title) {
- if ($name != 'license') {
- $this->createSubscriberUIHook($name, $title);
- $this->createSubscriberFilterHook($name, $title);
- }
- $this->createProviderUIHook($name, $title);
- }
- }
-
- /**
- * Creates a subscriber UI hook using the given name and title.
- *
- * @param string $name
- * @param string $title
- */
- private function createSubscriberUIHook($name, $title)
- {
- $bundle = new SubscriberBundle("CmfcmfMediaModule", "subscriber.cmfcmfmediamodule.ui_hooks.$name", "ui_hooks", $this->__f("%s hooks", ['%s' => $title]));
-
- $bundle->addEvent("display_view", "cmfcmfmediamodule.ui_hooks.$name.display_view");
- $bundle->addEvent("form_edit", "cmfcmfmediamodule.ui_hooks.$name.form_edit");
- $bundle->addEvent("form_delete", "cmfcmfmediamodule.ui_hooks.$name.form_delete");
- //$bundle->addEvent("filter", "cmfcmfmediamodule.filter_hooks.$name.filter");
- $bundle->addEvent("validate_edit", "cmfcmfmediamodule.ui_hooks.$name.validate_edit");
- $bundle->addEvent("validate_delete", "cmfcmfmediamodule.ui_hooks.$name.validate_delete");
- $bundle->addEvent("process_edit", "cmfcmfmediamodule.ui_hooks.$name.process_edit");
- $bundle->addEvent("process_delete", "cmfcmfmediamodule.ui_hooks.$name.process_delete");
-
- $this->registerHookSubscriberBundle($bundle);
- }
-
- /**
- * Creates a subscriber filter hook using the given name and title.
- *
- * @param string $name
- * @param string $title
- */
- private function createSubscriberFilterHook($name, $title)
- {
- $bundle = new SubscriberBundle("CmfcmfMediaModule", "subscriber.cmfcmfmediamodule.filter_hooks.$name", "filter_hooks", $this->__f("%s display hooks", ['%s' => $title]));
- $bundle->addEvent('filter', "cmfcmfmediamodule.filter_hooks.$name.filter");
-
- $this->registerHookSubscriberBundle($bundle);
- }
-
- /**
- * Creates a provider UI hook using the given name and title.
- *
- * @param string $name
- * @param string $title
- */
- private function createProviderUIHook($name, $title)
- {
- $bundle = new ProviderBundle("CmfcmfMediaModule", "provider.cmfcmfmediamodule.ui_hooks.$name", "ui_hooks", $this->__f("Media Module - %s", ['%s' => $title]));
-
- $class = "Cmfcmf\\Module\\MediaModule\\HookHandler\\" . ucfirst($name) . "HookHandler";
- $service = "cmfcmf_media_module.hook_handler.$name";
-
- $bundle->addServiceHandler("display_view", $class, "uiView", $service);
- $bundle->addServiceHandler("form_edit", $class, "uiEdit", $service);
- $bundle->addServiceHandler("validate_edit", $class, "validateEdit", $service);
- $bundle->addServiceHandler("process_edit", $class, "processEdit", $service);
- $bundle->addServiceHandler("process_delete", $class, "processDelete", $service);
-
- $this->registerHookProviderBundle($bundle);
- }
-}
diff --git a/Container/LinkContainer.php b/Container/LinkContainer.php
index 8d1f797a..205100be 100644
--- a/Container/LinkContainer.php
+++ b/Container/LinkContainer.php
@@ -78,9 +78,13 @@ public function getBundleName()
*/
public function getLinks($type = self::TYPE_ADMIN)
{
- if ($type == self::TYPE_ADMIN) {
+ if (!class_exists('\\Fhaculty\\Graph\\Graph')) {
+ include_once __DIR__ . '/../bootstrap.php';
+ }
+ if (self::TYPE_ADMIN == $type) {
return $this->adminLinks();
- } elseif ($type == self::TYPE_USER) {
+ }
+ if (self::TYPE_USER == $type) {
return $this->userLinks();
}
diff --git a/ContentType/CollectionType.php b/ContentType/CollectionType.php
new file mode 100644
index 00000000..ce09df87
--- /dev/null
+++ b/ContentType/CollectionType.php
@@ -0,0 +1,199 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\ContentType;
+
+use Cmfcmf\Module\MediaModule\CollectionTemplate\SelectedTemplateFactory;
+use Cmfcmf\Module\MediaModule\ContentType\Form\Type\CollectionType as FormType;
+use Cmfcmf\Module\MediaModule\Entity\Collection\Repository\CollectionRepository;
+use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
+use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Doctrine\ORM\EntityManagerInterface;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+use Zikula\Common\Content\AbstractContentType;
+use Zikula\Common\Content\ContentTypeInterface;
+
+/**
+ * Collection content type.
+ */
+class CollectionType extends AbstractContentType
+{
+ /**
+ * @var CollectionRepository
+ */
+ private $collectionRepository;
+
+ /**
+ * @var SecurityManager
+ */
+ private $securityManager;
+
+ /**
+ * @var SelectedTemplateFactory
+ */
+ private $selectedTemplateFactory;
+
+ /**
+ * @var MediaTypeCollection
+ */
+ private $mediaTypeCollection;
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return ContentTypeInterface::CATEGORY_BASIC;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIcon()
+ {
+ return 'folder-o';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Media collection', 'cmfcmfmediamodule');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getDescription()
+ {
+ return $this->translator->__('Display a media collection.', 'cmfcmfmediamodule');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getDefaultData()
+ {
+ return [
+ 'id' => null,
+ 'template' => ''
+ ];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function displayView()
+ {
+ $this->customInit();
+
+ $this->data = $this->getData();
+ if (null === $this->data['id'] || empty($this->data['id'])) {
+ return '';
+ }
+
+ $collection = $this->collectionRepository->findOneBy(['id' => $this->data['id']]);
+ if (!$collection) {
+ return '';
+ }
+ if (!$this->securityManager->hasPermission($collection, CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW)) {
+ return '';
+ }
+
+ try {
+ $selectedTemplate = $this->selectedTemplateFactory->fromDB($this->data['template']);
+ } catch (\DomainException $e) {
+ throw new NotFoundHttpException();
+ }
+
+ $content = $selectedTemplate->getTemplate()->render(
+ $collection,
+ $this->mediaTypeCollection,
+ isset($this->data['showChildCollections']) ? $this->data['showChildCollections'] : false,
+ $selectedTemplate->getOptions()
+ );
+
+ if (isset($this->data['showEditAndDownloadLinks']) && $this->data['showEditAndDownloadLinks']) {
+ $content = $this->twig->render('@CmfcmfMediaModule/Collection/display.html.twig', [
+ 'collection' => $collection,
+ 'renderRaw' => true,
+ 'content' => $content,
+ 'hook' => ''
+ ]);
+ }
+
+ return $content;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function displayEditing()
+ {
+ if (null === $this->data['id'] || empty($this->data['id'])) {
+ return $this->translator->__('No collection selected.', 'cmfcmfmediamodule');
+ }
+
+ return parent::displayEditing();
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEditFormClass()
+ {
+ $this->customInit();
+
+ return FormType::class;
+ }
+
+ /**
+ * @param EntityManagerInterface $em
+ */
+ public function setEntityManager(EntityManagerInterface $em)
+ {
+ $this->collectionRepository = $em->getRepository('CmfcmfMediaModule:Collection\CollectionEntity');
+ }
+
+ /**
+ * @param SecurityManager $securityManager
+ */
+ public function setSecurityManager(SecurityManager $securityManager)
+ {
+ $this->securityManager = $securityManager;
+ }
+
+ /**
+ * @param SelectedTemplateFactory $selectedTemplateFactory
+ */
+ public function setSelectedTemplateFactory(SelectedTemplateFactory $selectedTemplateFactory)
+ {
+ $this->selectedTemplateFactory = $selectedTemplateFactory;
+ }
+
+ /**
+ * @param MediaTypeCollection $mediaTypeCollection
+ */
+ public function setMediaTypeCollection(MediaTypeCollection $mediaTypeCollection)
+ {
+ $this->mediaTypeCollection = $mediaTypeCollection;
+ }
+
+ private function customInit()
+ {
+ $this->bundleName = 'CmfcmfMediaModule';
+ $this->domain = strtolower($this->bundleName);
+
+ include_once __DIR__ . '/../bootstrap.php';
+ }
+}
diff --git a/ContentType/Form/Type/CollectionType.php b/ContentType/Form/Type/CollectionType.php
new file mode 100644
index 00000000..8ebfbbba
--- /dev/null
+++ b/ContentType/Form/Type/CollectionType.php
@@ -0,0 +1,116 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\ContentType\Form\Type;
+
+use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
+use Cmfcmf\Module\MediaModule\Entity\Collection\Repository\CollectionRepository;
+use Cmfcmf\Module\MediaModule\Form\CollectionTemplate\TemplateType;
+use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Doctrine\ORM\EntityManagerInterface;
+use Doctrine\ORM\EntityRepository;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
+use Symfony\Component\Form\CallbackTransformer;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\Translation\TranslatorInterface;
+use Zikula\Common\Content\AbstractContentFormType;
+
+/**
+ * Collection content type form type.
+ */
+class CollectionType extends AbstractContentFormType
+{
+ /**
+ * @var CollectionRepository
+ */
+ private $collectionRepository;
+
+ /**
+ * @var SecurityManager
+ */
+ private $securityManager;
+
+ /**
+ * @param TranslatorInterface $translator
+ * @param SecurityManager $securityManager
+ * @param EntityManagerInterface $em
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ SecurityManager $securityManager,
+ EntityManagerInterface $em
+ ) {
+ $this->setTranslator($translator);
+ $this->securityManager = $securityManager;
+ $this->collectionRepository = $em->getRepository('CmfcmfMediaModule:Collection\CollectionEntity');
+ }
+
+ public function buildForm(FormBuilderInterface $builder, array $options)
+ {
+ $securityManager = $this->securityManager;
+ $collectionRepository = $this->collectionRepository;
+
+ $collectionOptions = [
+ 'required' => true,
+ 'label' => $this->__('Collection', 'cmfcmfmediamodule'),
+ 'class' => CollectionEntity::class,
+ 'query_builder' => function (EntityRepository $er) use ($securityManager) {
+ /** @var CollectionRepository $er */
+ $qb = $securityManager->getCollectionsWithAccessQueryBuilder(
+ CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW
+ );
+ $qb->orderBy('c.root', 'ASC')
+ ->addOrderBy('c.lft', 'ASC');
+
+ return $qb;
+ },
+ 'placeholder' => $this->__('Select collection', 'cmfcmfmediamodule'),
+ 'choice_label' => 'indentedTitle',
+ 'multiple' => false
+ ];
+ $builder
+ ->add('id', EntityType::class, $collectionOptions)
+ ->add('template', TemplateType::class, [
+ 'label' => $this->__('Display', 'cmfcmfmediamodule'),
+ ])
+ ->add('showChildCollections', CheckboxType::class, [
+ 'label' => $this->__('Show child collections', 'cmfcmfmediamodule'),
+ 'required' => false
+ ])
+ ->add('showEditAndDownloadLinks', CheckboxType::class, [
+ 'label' => $this->__('Show edit and download links', 'cmfcmfmediamodule'),
+ 'required' => false
+ ])
+ ->addModelTransformer(new CallbackTransformer(
+ function ($data) use ($collectionRepository) {
+ $data['id'] = isset($data['id']) ? $collectionRepository->findOneBy(['id' => $data['id']]) : null;
+
+ return $data;
+ },
+ function ($data) {
+ $data['id'] = isset($data['id']) ? $data['id']->getId() : null;
+
+ return $data;
+ }
+ ))
+ ;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getBlockPrefix()
+ {
+ return 'cmfcmfmediamodule_contenttype_collection';
+ }
+}
diff --git a/ContentType/Form/Type/MediaType.php b/ContentType/Form/Type/MediaType.php
new file mode 100644
index 00000000..b4117502
--- /dev/null
+++ b/ContentType/Form/Type/MediaType.php
@@ -0,0 +1,102 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\ContentType\Form\Type;
+
+use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
+use Cmfcmf\Module\MediaModule\Entity\Media\Repository\MediaRepository;
+use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Doctrine\ORM\EntityManagerInterface;
+use Doctrine\ORM\EntityRepository;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
+use Symfony\Component\Form\CallbackTransformer;
+use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\Translation\TranslatorInterface;
+use Zikula\Common\Content\AbstractContentFormType;
+
+/**
+ * Media content type form type.
+ */
+class MediaType extends AbstractContentFormType
+{
+ /**
+ * @var MediaRepository
+ */
+ private $mediaRepository;
+
+ /**
+ * @var SecurityManager
+ */
+ private $securityManager;
+
+ /**
+ * @param TranslatorInterface $translator
+ * @param SecurityManager $securityManager
+ * @param EntityManagerInterface $em
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ SecurityManager $securityManager,
+ EntityManagerInterface $em
+ ) {
+ $this->setTranslator($translator);
+ $this->securityManager = $securityManager;
+ $this->mediaRepository = $em->getRepository('CmfcmfMediaModule:Media\AbstractMediaEntity');
+ }
+
+ public function buildForm(FormBuilderInterface $builder, array $options)
+ {
+ $securityManager = $this->securityManager;
+ $mediaRepository = $this->mediaRepository;
+
+ $mediumOptions = [
+ 'required' => true,
+ 'label' => $this->__('Medium', 'cmfcmfmediamodule'),
+ 'class' => AbstractMediaEntity::class,
+ 'query_builder' => function (EntityRepository $er) use ($securityManager) {
+ /** @var MediaRepository $er */
+ $qb = $securityManager->getMediaWithAccessQueryBuilder(
+ CollectionPermissionSecurityTree::PERM_LEVEL_MEDIA_DETAILS
+ );
+ $qb->orderBy('m.title');
+
+ return $qb;
+ },
+ 'placeholder' => $this->__('Select medium', 'cmfcmfmediamodule'),
+ 'choice_label' => 'title',
+ 'multiple' => false
+ ];
+ $builder
+ ->add('id', EntityType::class, $mediumOptions)
+ ->addModelTransformer(new CallbackTransformer(
+ function ($data) use ($mediaRepository) {
+ $data['id'] = isset($data['id']) ? $mediaRepository->findOneBy(['id' => $data['id']]) : null;
+
+ return $data;
+ },
+ function ($data) {
+ $data['id'] = isset($data['id']) ? $data['id']->getId() : null;
+
+ return $data;
+ }
+ ))
+ ;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getBlockPrefix()
+ {
+ return 'cmfcmfmediamodule_contenttype_media';
+ }
+}
diff --git a/ContentType/MediaType.php b/ContentType/MediaType.php
new file mode 100644
index 00000000..4fce382f
--- /dev/null
+++ b/ContentType/MediaType.php
@@ -0,0 +1,213 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\ContentType;
+
+use Cmfcmf\Module\MediaModule\ContentType\Form\Type\MediaType as FormType;
+use Cmfcmf\Module\MediaModule\Entity\Media\Repository\MediaRepository;
+use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
+use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Doctrine\ORM\EntityManagerInterface;
+use Zikula\Common\Content\AbstractContentType;
+use Zikula\Common\Content\ContentTypeInterface;
+
+/**
+ * Media content type.
+ */
+class MediaType extends AbstractContentType
+{
+ /**
+ * @var MediaRepository
+ */
+ private $mediaRepository;
+
+ /**
+ * @var SecurityManager
+ */
+ private $securityManager;
+
+ /**
+ * @var MediaTypeCollection
+ */
+ private $mediaTypeCollection;
+
+ /**
+ * @var boolean
+ */
+ private $enableMediaViewCounter;
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return ContentTypeInterface::CATEGORY_BASIC;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIcon()
+ {
+ return 'picture-o';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Media detail', 'cmfcmfmediamodule');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getDescription()
+ {
+ return $this->translator->__('Display a single medium.', 'cmfcmfmediamodule');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getDefaultData()
+ {
+ return [
+ 'id' => null
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getTranslatableDataFields()
+ {
+ return ['id'];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function displayView()
+ {
+ $this->customInit();
+
+ $this->data = $this->getData();
+ if (null === $this->data['id'] || empty($this->data['id'])) {
+ return '';
+ }
+
+ $medium = $this->mediaRepository->findOneBy(['id' => $this->data['id']]);
+ if (!$medium) {
+ return '';
+ }
+ if (!$this->securityManager->hasPermission($medium, CollectionPermissionSecurityTree::PERM_LEVEL_MEDIA_DETAILS)) {
+ return '';
+ }
+
+ return $this->twig->render('@CmfcmfMediaModule/Media/displayRaw.html.twig', [
+ 'mediaType' => $this->mediaTypeCollection->getMediaTypeFromEntity($medium),
+ 'entity' => $medium
+ ]);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function displayEditing()
+ {
+ if (null === $this->data['id'] || empty($this->data['id'])) {
+ return $this->translator->__('No medium selected.', 'cmfcmfmediamodule');
+ }
+
+ return parent::displayEditing();
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEditFormClass()
+ {
+ $this->customInit();
+
+ return FormType::class;
+ }
+
+ /**
+ * @param EntityManagerInterface $em
+ */
+ public function setEntityManager(EntityManagerInterface $em)
+ {
+ $this->mediaRepository = $em->getRepository('CmfcmfMediaModule:Media\AbstractMediaEntity');
+ }
+
+ /**
+ * @param SecurityManager $securityManager
+ */
+ public function setSecurityManager(SecurityManager $securityManager)
+ {
+ $this->securityManager = $securityManager;
+ }
+
+ /**
+ * @param MediaTypeCollection $mediaTypeCollection
+ */
+ public function setMediaTypeCollection(MediaTypeCollection $mediaTypeCollection)
+ {
+ $this->mediaTypeCollection = $mediaTypeCollection;
+ }
+
+ /**
+ * @param boolean $enableMediaViewCounter
+ */
+ public function setEnableMediaViewCounter($enableMediaViewCounter)
+ {
+ $this->enableMediaViewCounter = $enableMediaViewCounter;
+ }
+
+ private function customInit()
+ {
+ $this->bundleName = 'CmfcmfMediaModule';
+ $this->domain = strtolower($this->bundleName);
+
+ include_once __DIR__ . '/../bootstrap.php';
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getAssets($context)
+ {
+ $assets = parent::getAssets($context);
+ if (in_array($context, [ContentTypeInterface::CONTEXT_EDIT, ContentTypeInterface::CONTEXT_TRANSLATION])) {
+ $assets['js'][] = $this->assetHelper->resolve('@CmfcmfMediaModule:js/CmfcmfMediaModule.ContentType.Media.js');
+ }
+
+ return $assets;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getJsEntrypoint($context)
+ {
+ if (ContentTypeInterface::CONTEXT_EDIT == $context) {
+ return 'contentInitMediaEdit';
+ }
+ if (ContentTypeInterface::CONTEXT_TRANSLATION == $context) {
+ return 'contentInitMediaTranslation';
+ }
+
+ return null;
+ }
+}
diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php
index 5aac365b..3314df42 100644
--- a/Controller/AbstractController.php
+++ b/Controller/AbstractController.php
@@ -13,8 +13,14 @@
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
+use Zikula\Bundle\HookBundle\Hook\DisplayHook;
use Zikula\Bundle\HookBundle\Hook\DisplayHookResponse;
+use Zikula\Bundle\HookBundle\FormAwareHook\FormAwareHook;
+use Zikula\Bundle\HookBundle\FormAwareHook\FormAwareResponse;
use Zikula\Bundle\HookBundle\Hook\Hook;
+use Zikula\Bundle\HookBundle\Hook\ProcessHook;
+use Zikula\Bundle\HookBundle\Hook\ValidationHook;
+use Zikula\Bundle\HookBundle\Hook\ValidationProviders;
use Zikula\Core\Controller\AbstractController as BaseAbstractController;
use Zikula\Core\UrlInterface;
@@ -26,35 +32,35 @@ abstract class AbstractController extends BaseAbstractController
/**
* Notifies subscribers of the given hook.
*
- * @param Hook $hook
+ * @param string $name Hook event name
+ * @param Hook $hook Hook interface
*
* @return Hook
*/
- protected function notifyHooks(Hook $hook)
+ protected function dispatchHooks($name, Hook $hook)
{
- return $this->get('hook_dispatcher')->dispatch($hook->getName(), $hook);
+ return $this->get('hook_dispatcher')->dispatch($name, $hook);
}
/**
* Get the display hook content for the given hook.
*
* @param string $name
- * @param string $event
+ * @param string $hookType
* @param string|null $id
* @param UrlInterface|null $url
*
* @return string
*/
- protected function getDisplayHookContent($name, $event, $id = null, UrlInterface $url = null)
+ protected function getDisplayHookContent($name, $hookType, $id = null, UrlInterface $url = null)
{
- $eventName = "cmfcmfmediamodule.ui_hooks.$name.$event";
- $hook = new \Zikula_DisplayHook($eventName, $id, $url);
+ $eventName = 'cmfcmfmediamodule.ui_hooks.' . $name . '.' . $hookType;
+ $hook = new DisplayHook($id, $url);
$this->get('hook_dispatcher')->dispatch($eventName, $hook);
/** @var DisplayHookResponse[] $responses */
$responses = $hook->getResponses();
- $content = "";
-
+ $content = '';
foreach ($responses as $result) {
$result = $result->__toString();
if (strlen(trim($result)) > 0) {
@@ -62,44 +68,72 @@ protected function getDisplayHookContent($name, $event, $id = null, UrlInterface
}
}
- return strlen($content) == 0 ? "" : "
\n$content
";
+ return 0 == strlen($content) ? '' : "\n$content
";
}
/**
* Applies process hooks.
*
* @param string $name
- * @param string $event
+ * @param string $hookType
* @param string $id
* @param UrlInterface|null $url
*/
- protected function applyProcessHook($name, $event, $id, UrlInterface $url = null)
+ protected function applyProcessHook($name, $hookType, $id, UrlInterface $url = null)
+ {
+ $eventName = 'cmfcmfmediamodule.ui_hooks.' . $name . '.' . $hookType;
+ $hook = new ProcessHook($id, $url);
+ $this->dispatchHooks($eventName, $hook);
+ }
+
+ /**
+ * Applies form aware display hooks.
+ *
+ * @param Form $form
+ * @param string $name
+ * @param string $hookType
+ * @param UrlInterface|null $url
+ */
+ protected function applyFormAwareDisplayHook(Form $form, $name, $hookType, UrlInterface $url = null)
{
- /* @noinspection PhpParamsInspection */
- $this->notifyHooks(new \Zikula_ProcessHook(
- "cmfcmfmediamodule.ui_hooks.$name.$event",
- $id,
- $url
- ));
+ $eventName = 'cmfcmfmediamodule.form_aware_hook.' . $name . '.' . $hookType;
+ $hook = new FormAwareHook($form);
+ $this->dispatchHooks($eventName, $hook);
+
+ return $hook;
+ }
+
+ /**
+ * Applies form aware process hooks.
+ *
+ * @param Form $form
+ * @param string $name
+ * @param string $hookType
+ * @param object|array|string $formSubject
+ * @param UrlInterface|null $url
+ */
+ protected function applyFormAwareProcessHook(Form $form, $name, $hookType, $formSubject, UrlInterface $url = null)
+ {
+ $formResponse = new FormAwareResponse($form, $formSubject, $url);
+ $eventName = 'cmfcmfmediamodule.form_aware_hook.' . $name . '.' . $hookType;
+
+ $this->dispatchHooks($eventName, $formResponse);
}
/**
* Checks whether or not the hook validates.
*
* @param string $name
- * @param string $event
+ * @param string $hookType
*
* @return bool
*/
- protected function hookValidates($name, $event)
+ protected function hookValidates($name, $hookType)
{
- /* @noinspection PhpParamsInspection */
- $validationHook = new \Zikula_ValidationHook(
- "cmfcmfmediamodule.ui_hooks.$name.$event",
- new \Zikula_Hook_ValidationProviders()
- );
- /** @var \Zikula\Bundle\HookBundle\Hook\ValidationProviders $hookvalidators */
- $hookvalidators = $this->notifyHooks($validationHook)->getValidators();
+ $eventName = 'cmfcmfmediamodule.ui_hooks.' . $name . '.' . $hookType;
+ $validationHook = new ValidationHook();
+ /** @var ValidationProviders $hookvalidators */
+ $hookvalidators = $this->dispatchHooks($eventName, $validationHook)->getValidators();
return !$hookvalidators->hasErrors();
}
@@ -109,7 +143,7 @@ protected function hookValidates($name, $event)
*
* @param Form $form
*/
- protected function hookValidationError($form)
+ protected function hookValidationError(Form $form)
{
$form->addError(new FormError($this->__('Hook validation failed!')));
}
diff --git a/Controller/AdminController.php b/Controller/AdminController.php
deleted file mode 100644
index 9865e43b..00000000
--- a/Controller/AdminController.php
+++ /dev/null
@@ -1,25 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Cmfcmf\Module\MediaModule\Controller;
-
-/**
- * @todo Remove this. This is just here for legacy reasons so that a link from the extensions
- * list is provided.
- */
-class AdminController extends \Zikula_AbstractController
-{
- public function indexAction()
- {
- $url = $this->get('router')->generate('cmfcmfmediamodule_settings_index');
- $this->redirect($url);
- }
-}
diff --git a/Controller/CollectionController.php b/Controller/CollectionController.php
index 2d664df3..bcfb9f44 100644
--- a/Controller/CollectionController.php
+++ b/Controller/CollectionController.php
@@ -18,9 +18,6 @@
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\OptimisticLockException;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -28,7 +25,10 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
+use Zikula\Bundle\HookBundle\Category\FormAwareCategory;
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Core\Response\PlainResponse;
use Zikula\Core\RouteUrl;
@@ -37,7 +37,6 @@ class CollectionController extends AbstractController
/**
* @Route("/new/{slug}", requirements={"slug" = ".+"})
* @Template(template="CmfcmfMediaModule:Collection:edit.html.twig")
- * @ParamConverter("parent", class="Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity", options={"slug" = "slug"})
*
* @param Request $request
* @param CollectionEntity $parent
@@ -46,7 +45,7 @@ class CollectionController extends AbstractController
*/
public function newAction(Request $request, CollectionEntity $parent)
{
- if ($parent == null) {
+ if (null == $parent) {
throw new NotFoundHttpException();
}
$securityManager = $this->get('cmfcmf_media_module.security_manager');
@@ -54,15 +53,14 @@ public function newAction(Request $request, CollectionEntity $parent)
throw new AccessDeniedException();
}
- $templateCollection = $this->get('cmfcmf_media_module.collection_template_collection');
$entity = new CollectionEntity();
- $form = new CollectionType($templateCollection, $parent, $securityManager);
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm(CollectionType::class, $entity, [
+ 'parent' => $parent
+ ]);
$form->handleRequest($request);
if ($form->isValid()) {
- if ($this->hookValidates('collection', 'validate_edit')) {
+ if ($this->hookValidates('collection', UiHooksCategory::TYPE_VALIDATE_EDIT)) {
if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission($entity->getParent(), CollectionPermissionSecurityTree::PERM_LEVEL_ADD_SUB_COLLECTIONS)) {
throw new AccessDeniedException($this->__('You don\'t have permission to add a sub-collection to the selected parent collection.'));
}
@@ -70,29 +68,27 @@ public function newAction(Request $request, CollectionEntity $parent)
$em->persist($entity);
$em->flush();
- $this->applyProcessHook('collection', 'process_edit', $entity->getId(), new RouteUrl(
- 'cmfcmfmediamodule_collection_display',
- ['slug' => $entity->getSlug()]
- ));
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()]);
+ $this->applyFormAwareProcessHook($form, 'collection', FormAwareCategory::TYPE_PROCESS_EDIT, $entity, $hookUrl);
+ $this->applyProcessHook('collection', UiHooksCategory::TYPE_PROCESS_EDIT, $entity->getId(), $hookUrl);
return $this->redirectToRoute('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()]);
}
$this->hookValidationError($form);
}
+ $formHook = $this->applyFormAwareDisplayHook($form, 'collections', FormAwareCategory::TYPE_EDIT);
+
return [
'form' => $form->createView(),
- 'hook' => $this->getDisplayHookContent(
- 'collection',
- 'form_edit'
- ),
+ 'hook' => $this->getDisplayHookContent('collections', UiHooksCategory::TYPE_FORM_EDIT),
+ 'formHookTemplates' => $formHook->getTemplates()
];
}
/**
* @Route("/edit/{slug}", requirements={"slug" = ".+"})
- * @ParamConverter("entity", class="Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity", options={"slug" = "slug"})
- * @Template()
+ * @Template(template="CmfcmfMediaModule:Collection:edit.html.twig")
*
* @param Request $request
* @param CollectionEntity $entity
@@ -106,17 +102,16 @@ public function editAction(Request $request, CollectionEntity $entity)
throw new AccessDeniedException();
}
- $templateCollection = $this->get('cmfcmf_media_module.collection_template_collection');
- $form = new CollectionType($templateCollection, $entity->getParent(), $securityManager);
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm(CollectionType::class, $entity, [
+ 'parent' => $entity->getParent()
+ ]);
$form->handleRequest($request);
if (!$form->isValid()) {
goto edit_error;
}
- if (!$this->hookValidates('collection', 'validate_edit')) {
+ if (!$this->hookValidates('collection', UiHooksCategory::TYPE_VALIDATE_EDIT)) {
$this->hookValidationError($form);
goto edit_error;
}
@@ -130,29 +125,26 @@ public function editAction(Request $request, CollectionEntity $entity)
goto edit_error;
}
- $this->applyProcessHook('collection', 'process_edit', $entity->getId(), new RouteUrl(
- 'cmfcmfmediamodule_collection_display',
- ['slug' => $entity->getSlug()]
- ));
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()]);
+ $this->applyFormAwareProcessHook($form, 'collection', FormAwareCategory::TYPE_PROCESS_EDIT, $entity, $hookUrl);
+ $this->applyProcessHook('collection', UiHooksCategory::TYPE_PROCESS_EDIT, $entity->getId(), $hookUrl);
return $this->redirectToRoute('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()]);
edit_error:
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()]);
+ $formHook = $this->applyFormAwareDisplayHook($form, 'collections', FormAwareCategory::TYPE_EDIT, $hookUrl);
+
return [
'form' => $form->createView(),
- 'hook' => $this->getDisplayHookContent(
- 'collection',
- 'form_edit',
- $entity->getId(),
- new RouteUrl('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()])
- ),
+ 'hook' => $this->getDisplayHookContent('collections', UiHooksCategory::TYPE_FORM_EDIT, $entity->getId(), $hookUrl),
+ 'formHookTemplates' => $formHook->getTemplates()
];
}
/**
* @Route("/download/{slug}.zip", requirements={"slug"=".+"})
- * @ParamConverter("entity", class="Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity", options={"slug" = "slug"})
*
* @param CollectionEntity $entity
*
@@ -165,12 +157,19 @@ public function downloadAction(CollectionEntity $entity)
}
$em = $this->getDoctrine()->getManager();
- \CacheUtil::createLocalDir('CmfcmfMediaModule');
- $dir = \CacheUtil::getLocalDir('CmfcmfMediaModule');
- $path = $dir . '/' . uniqid(time(), true) . '.zip';
+ $cacheDirectory = $this->get('service_container')->getParameter('kernel.cache_dir') . '/CmfCmfMediaModule/';
+ $filesystem = $this->get('filesystem');
+ if (!$filesystem->exists($cacheDirectory)) {
+ $filesystem->mkdir($cacheDirectory, 0777);
+ }
+ if (!$filesystem->exists($cacheDirectory)) {
+ $cacheDirectory = sys_get_temp_dir();
+ }
+
+ $path = $cacheDirectory . '/' . uniqid(time(), true) . '.zip';
$zip = new \ZipArchive();
- if ($zip->open($path, \ZipArchive::CREATE) !== true) {
+ if (true !== $zip->open($path, \ZipArchive::CREATE)) {
throw new ServiceUnavailableHttpException('Could not create zip archive!');
}
$mediaTypeCollection = $this->get('cmfcmf_media_module.media_type_collection');
@@ -245,8 +244,7 @@ public function reorderAction(Request $request)
}
/**
- * @Route("")
- * @Method("GET")
+ * @Route("", methods={"GET"})
*
* @return RedirectResponse
*/
@@ -263,10 +261,27 @@ public function displayRootAction()
}
/**
- * @Route("/{slug}", requirements={"slug"=".*[^/]"}, options={"expose" = true})
- * @ParamConverter("entity", class="Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity", options={"slug" = "slug"})
- * @Method("GET")
- * @Template()
+ * @Route("/show-by-id/{id}", options={"expose" = true})
+ *
+ * @param CollectionEntity $entity
+ *
+ * @return RedirectResponse
+ */
+ public function displayByIdAction(CollectionEntity $entity)
+ {
+ if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission($entity, CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW)) {
+ throw new AccessDeniedException();
+ }
+
+ return $this->redirectToRoute(
+ 'cmfcmfmediamodule_collection_display',
+ ['slug' => $entity->getSlug()]
+ );
+ }
+
+ /**
+ * @Route("/{slug}", methods={"GET"}, requirements={"slug"=".*[^/]"}, options={"expose" = true})
+ * @Template(template="CmfcmfMediaModule:Collection:display.html.twig")
*
* @param Request $request
* @param CollectionEntity $entity
@@ -279,10 +294,10 @@ public function displayAction(Request $request, CollectionEntity $entity)
throw new AccessDeniedException();
}
- if ($entity->getDefaultTemplate() != null) {
+ if (null !== $entity->getDefaultTemplate()) {
$defaultTemplate = $entity->getDefaultTemplate();
} else {
- $defaultTemplate = \ModUtil::getVar('CmfcmfMediaModule', 'defaultCollectionTemplate');
+ $defaultTemplate = $this->getVar('defaultCollectionTemplate');
}
$template = $request->query->get('template', $defaultTemplate);
@@ -311,12 +326,7 @@ public function displayAction(Request $request, CollectionEntity $entity)
];
$hookUrl = new RouteUrl('cmfcmfmediamodule_collection_display', ['slug' => $entity->getSlug()]);
- $templateVars['hook'] = $this->getDisplayHookContent(
- 'collection',
- 'display_view',
- $entity->getId(),
- $hookUrl
- );
+ $templateVars['hook'] = $this->getDisplayHookContent('collections', UiHooksCategory::TYPE_DISPLAY_VIEW, $entity->getId(), $hookUrl);
$templateVars['renderRaw'] = $isHook = $request->query->get('isHook', false);
$templateVars['content'] = $selectedTemplate->getTemplate()->render(
@@ -328,23 +338,4 @@ public function displayAction(Request $request, CollectionEntity $entity)
return $this->render('CmfcmfMediaModule:Collection:display.html.twig', $templateVars);
}
-
- /**
- * @Route("/show-by-id/{id}", options={"expose" = true})
- *
- * @param CollectionEntity $entity
- *
- * @return RedirectResponse
- */
- public function displayByIdAction(CollectionEntity $entity)
- {
- if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission($entity, CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW)) {
- throw new AccessDeniedException();
- }
-
- return $this->redirectToRoute(
- 'cmfcmfmediamodule_collection_display',
- ['slug' => $entity->getSlug()]
- );
- }
}
diff --git a/Controller/FinderController.php b/Controller/FinderController.php
index ae237253..c3b548b5 100644
--- a/Controller/FinderController.php
+++ b/Controller/FinderController.php
@@ -14,10 +14,10 @@
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/finder")
@@ -26,7 +26,7 @@ class FinderController extends AbstractController
{
/**
* @Route("/choose", options={"expose" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Finder:chooseMethod.html.twig")
*/
public function chooseMethodAction()
{
@@ -35,7 +35,7 @@ public function chooseMethodAction()
/**
* @Route("/popup/choose/collection", options={"expose" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Finder:popupChooseCollections.html.twig")
*/
public function popupChooseCollectionsAction()
{
@@ -44,7 +44,7 @@ public function popupChooseCollectionsAction()
/**
* @Route("/popup/choose/media", options={"expose" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Finder:popupChooseMedia.html.twig")
*/
public function popupChooseMediaAction()
{
@@ -91,7 +91,7 @@ public function ajaxFindAction(Request $request)
return $entity->toArrayForFinder($mediaTypeCollection);
}, $collectionResults);
- return new JsonResponse([
+ return $this->json([
'media' => $mediaResults,
'collections' => $collectionResults
]);
@@ -110,7 +110,7 @@ public function getCollectionsAction($parentId, $hookedObjectId = null)
$securityManager = $this->get('cmfcmf_media_module.security_manager');
$mediaTypeCollection = $this->get('cmfcmf_media_module.media_type_collection');
- if ($hookedObjectId != null) {
+ if (null != $hookedObjectId) {
$em = $this->getDoctrine()->getManager();
$hookedObjectEntity = $em
->find('CmfcmfMediaModule:HookedObject\HookedObjectEntity', $hookedObjectId);
@@ -120,7 +120,7 @@ public function getCollectionsAction($parentId, $hookedObjectId = null)
$qb = $securityManager
->getCollectionsWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW);
- if ($parentId == '#') {
+ if ('#' == $parentId) {
$qb->andWhere($qb->expr()->isNull('c.parent'));
} else {
$qb->andWhere($qb->expr()->eq('c.parent', ':parentId'))
@@ -132,6 +132,6 @@ public function getCollectionsAction($parentId, $hookedObjectId = null)
return $collection->toArrayForJsTree($mediaTypeCollection, $hookedObjectEntity);
}, $collections);
- return new JsonResponse($collections);
+ return $this->json($collections);
}
}
diff --git a/Controller/ImportController.php b/Controller/ImportController.php
index 3ec079d9..9d504adc 100644
--- a/Controller/ImportController.php
+++ b/Controller/ImportController.php
@@ -13,9 +13,9 @@
use Cmfcmf\Module\MediaModule\Form\ImportType;
use Symfony\Component\HttpFoundation\Request;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Zikula\ThemeModule\Engine\Annotation\Theme;
@@ -23,7 +23,7 @@ class ImportController extends AbstractController
{
/**
* @Route("/import")
- * @Template()
+ * @Template("CmfcmfMediaModule:Import:select.html.twig")
* @Theme("admin")
*
* @return array
@@ -43,7 +43,7 @@ public function selectAction()
/**
* @Route("/import/{importer}")
- * @Template()
+ * @Template("CmfcmfMediaModule:Import:execute.html.twig")
* @Theme("admin")
*
* @param Request $request
@@ -62,18 +62,17 @@ public function executeAction(Request $request, $importer)
throw new NotFoundHttpException();
}
$importer = $importerCollection->getImporter($importer);
- if ($importer->checkRequirements() !== true) {
+ if (true !== $importer->checkRequirements()) {
throw new NotFoundHttpException();
}
- $importType = new ImportType($importer->getSettingsForm(), $this->get('translator'), $this->get('cmfcmf_media_module.security_manager'));
- $form = $this->createForm($importType);
+ $form = $this->createForm(ImportType::class, null, ['importerForm' => $importer->getSettingsForm()]);
$form->handleRequest($request);
if ($form->isValid()) {
$success = $importer->import($form->getData(), $this->get('session')->getFlashBag());
- if ($success === true) {
+ if (true === $success) {
$this->addFlash('status', $this->__('Media imported successfully.'));
return $this->redirectToRoute('cmfcmfmediamodule_collection_display', ['slug' => $form->getData()['collection']->getSlug()]);
diff --git a/Controller/LicenseController.php b/Controller/LicenseController.php
index 947dec4b..248ba18b 100644
--- a/Controller/LicenseController.php
+++ b/Controller/LicenseController.php
@@ -14,13 +14,11 @@
use Cmfcmf\Module\MediaModule\Entity\License\LicenseEntity;
use Cmfcmf\Module\MediaModule\Form\License\LicenseType;
use Doctrine\ORM\OptimisticLockException;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
@@ -29,9 +27,8 @@
class LicenseController extends AbstractController
{
/**
- * @Route("/")
- * @Method("GET")
- * @Template()
+ * @Route("/", methods={"GET"})
+ * @Template("CmfcmfMediaModule:License:index.html.twig")
*
* @return array
*/
@@ -52,7 +49,7 @@ public function indexAction()
/**
* @Route("/new")
- * @Template(template="CmfcmfMediaModule:License:edit.html.twig")
+ * @Template("CmfcmfMediaModule:License:edit.html.twig")
*
* @param Request $request
*
@@ -65,9 +62,7 @@ public function newAction(Request $request)
}
$entity = new LicenseEntity(null);
- $form = new LicenseType(false);
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm(LicenseType::class, $entity);
$form->handleRequest($request);
if ($form->isValid()) {
@@ -85,8 +80,7 @@ public function newAction(Request $request)
/**
* @Route("/edit/{id}")
- * @ParamConverter("entity", class="CmfcmfMediaModule:License\LicenseEntity")
- * @Template()
+ * @Template("CmfcmfMediaModule:License:edit.html.twig")
*
* @param Request $request
* @param LicenseEntity $entity
@@ -99,9 +93,7 @@ public function editAction(Request $request, LicenseEntity $entity)
throw new AccessDeniedException();
}
- $form = new LicenseType(true);
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm(LicenseType::class, $entity);
$form->handleRequest($request);
if ($form->isValid()) {
@@ -123,8 +115,7 @@ public function editAction(Request $request, LicenseEntity $entity)
/**
* @Route("/delete/{id}")
- * @ParamConverter("entity", class="CmfcmfMediaModule:License\LicenseEntity")
- * @Template()
+ * @Template("CmfcmfMediaModule:License:delete.html.twig")
*
* @param Request $request
* @param LicenseEntity $entity
diff --git a/Controller/MediaController.php b/Controller/MediaController.php
index cd6b9cf8..e4c67eab 100644
--- a/Controller/MediaController.php
+++ b/Controller/MediaController.php
@@ -14,7 +14,6 @@
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractFileEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
-use Cmfcmf\Module\MediaModule\Form\AbstractType;
use Cmfcmf\Module\MediaModule\MediaType\MediaTypeInterface;
use Cmfcmf\Module\MediaModule\MediaType\PasteMediaTypeInterface;
use Cmfcmf\Module\MediaModule\MediaType\UploadableMediaTypeInterface;
@@ -24,9 +23,7 @@
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\Tools\Pagination\Paginator;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -36,7 +33,10 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
+use Zikula\Bundle\HookBundle\Category\FormAwareCategory;
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Core\Response\PlainResponse;
use Zikula\Core\RouteUrl;
use Zikula\ThemeModule\Engine\Annotation\Theme;
@@ -44,9 +44,8 @@
class MediaController extends AbstractController
{
/**
- * @Route("/admin/media-list/{page}", requirements={"page" = "\d+"})
- * @Method("GET")
- * @Template()
+ * @Route("/admin/media-list/{page}", methods={"GET"}, requirements={"page" = "\d+"})
+ * @Template("CmfcmfMediaModule:Media:adminlist.html.twig")
* @Theme("admin")
*
* @param int $page
@@ -83,7 +82,7 @@ public function adminlistAction($page = 1)
/**
* @Route("/edit/{collectionSlug}/f/{slug}", requirements={"collectionSlug" = ".+?"})
* @ParamConverter("entity", class="CmfcmfMediaModule:Media\AbstractMediaEntity", options={"repository_method" = "findBySlugs", "map_method_signature" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Media:edit.html.twig")
*
* @param Request $request
* @param AbstractMediaEntity $entity
@@ -97,7 +96,7 @@ public function editAction(Request $request, AbstractMediaEntity $entity)
$entity,
CollectionPermissionSecurityTree::PERM_LEVEL_EDIT_MEDIA
);
- $isTemporaryUploadCollection = $entity->getCollection()->getId() == CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID;
+ $isTemporaryUploadCollection = CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID == $entity->getCollection()->getId();
$justUploadedIds = $request->getSession()->get('cmfcmfmediamodule_just_uploaded', []);
if (!$editPermission && !($isTemporaryUploadCollection && in_array($entity->getId(), $justUploadedIds))) {
@@ -106,32 +105,30 @@ public function editAction(Request $request, AbstractMediaEntity $entity)
$em = $this->getDoctrine()->getManager();
$parent = $request->query->get('parent', null);
- if ($parent != null) {
+ if (null != $parent) {
$parent = $em->getRepository('CmfcmfMediaModule:Collection\CollectionEntity')->findOneBy(['slug' => $parent]);
}
- $variableApi = $this->get('zikula_extensions_module.api.variable');
$mediaType = $this->get('cmfcmf_media_module.media_type_collection')->getMediaTypeFromEntity($entity);
$form = $mediaType->getFormTypeClass();
- /** @var AbstractType $form */
- $form = new $form($securityManager, $variableApi, $em, false, $parent);
- $form->setTranslator($this->get('translator'));
+ $formOptions = $mediaType->getFormOptions($entity);
+ $formOptions['parent'] = $parent;
/** @var \Symfony\Component\Form\Form $form */
- $form = $this->createForm($form, $entity, $mediaType->getFormOptions($entity));
+ $form = $this->createForm($form, $entity, $formOptions);
$form->handleRequest($request);
if (!$form->isValid()) {
goto edit_error;
}
- if (!$this->hookValidates('media', 'validate_edit')) {
+ if (!$this->hookValidates('media', UiHooksCategory::TYPE_VALIDATE_EDIT)) {
$this->hookValidationError($form);
goto edit_error;
}
$uploadManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$file = $form->has('file') ? $form->get('file')->getData() : null;
- if ($file !== null) {
+ if (null !== $file) {
if (!($mediaType instanceof UploadableMediaTypeInterface)) {
// Attempt to upload a file for a non-upload media type.
throw new NotFoundHttpException();
@@ -143,11 +140,10 @@ public function editAction(Request $request, AbstractMediaEntity $entity)
$uploadManager->markEntityToUpload($entity, $file);
- // Cleanup thumbnails
- /** @var \SystemPlugin_Imagine_Manager $imagineManager */
- $imagineManager = $this->get('systemplugin.imagine.manager');
- $imagineManager->setModule('CmfcmfMediaModule');
- $imagineManager->removeObjectThumbs($entity->getImagineId());
+ // Cleanup existing thumbnails
+ /** @var Liip\ImagineBundle\Imagine\Cache\CacheManager $imagineCacheManager */
+ $imagineCacheManager = $this->get('liip_imagine.cache.manager');
+ $imagineCacheManager->remove($entity->getPath(), ['thumbnail', 'cmfcmfmediamodule.custom_image_filter']);
}
try {
@@ -158,13 +154,12 @@ public function editAction(Request $request, AbstractMediaEntity $entity)
goto edit_error;
}
- $this->applyProcessHook('media', 'process_edit', $entity->getId(), new RouteUrl(
- 'cmfcmfmediamodule_media_display',
- [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ]
- ));
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
+ $this->applyFormAwareProcessHook($form, 'media', FormAwareCategory::TYPE_PROCESS_EDIT, $entity, $hookUrl);
+ $this->applyProcessHook('media', UiHooksCategory::TYPE_PROCESS_EDIT, $entity->getId(), $hookUrl);
$isPopup = $request->query->get('popup', false);
if ($isPopup) {
@@ -175,26 +170,25 @@ public function editAction(Request $request, AbstractMediaEntity $entity)
edit_error:
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
+ $formHook = $this->applyFormAwareDisplayHook($form, 'media', FormAwareCategory::TYPE_EDIT, $hookUrl);
+
return [
'form' => $form->createView(),
+ 'entity' => $entity,
'breadcrumbs' => $entity->getCollection()->getBreadcrumbs($this->get('router')),
- 'hook' => $this->getDisplayHookContent(
- 'media',
- 'form_edit',
- $entity->getId(),
- new RouteUrl('cmfcmfmediamodule_media_display', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ])
- ),
- 'entity' => $entity
+ 'hook' => $this->getDisplayHookContent('media', UiHooksCategory::TYPE_FORM_EDIT, $entity->getId(), $hookUrl),
+ 'formHookTemplates' => $formHook->getTemplates()
];
}
/**
* @Route("/delete/{collectionSlug}/f/{slug}", requirements={"collectionSlug" = ".+?"})
- * @ParamConverter("entity", class="CmfcmfMediaModule:Media\AbstractMediaEntity", options={"repository_method"="findBySlugs", "map_method_signature"=true})
- * @Template()
+ * @ParamConverter("entity", class="CmfcmfMediaModule:Media\AbstractMediaEntity", options={"repository_method" = "findBySlugs", "map_method_signature" = true})
+ * @Template("CmfcmfMediaModule:Media:delete.html.twig")
*
* @param Request $request
* @param AbstractMediaEntity $entity
@@ -211,7 +205,7 @@ public function deleteAction(Request $request, AbstractMediaEntity $entity)
}
if ($request->isMethod('POST')) {
- if ($this->hookValidates('media', 'validate_delete')) {
+ if ($this->hookValidates('media', UiHooksCategory::TYPE_VALIDATE_DELETE)) {
// Save entity id for use in hook event. It is set to null during the entitymanager flush.
$id = $entity->getId();
@@ -221,44 +215,33 @@ public function deleteAction(Request $request, AbstractMediaEntity $entity)
// @todo Delete file if appropriate.
- $this->applyProcessHook(
- 'media',
- 'process_delete',
- $id,
- new RouteUrl('cmfcmfmediamodule_media_display', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ])
- );
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
+ $this->applyProcessHook('media', UiHooksCategory::TYPE_PROCESS_DELETE, $id, $hookUrl);
return $this->redirectToRoute('cmfcmfmediamodule_collection_display', ['slug' => $entity->getCollection()->getSlug()]);
} else {
- /** @var \Zikula_Session $session */
- $session = $request->getSession();
- $session->getFlashbag()->add('error', $this->__('Hook validation failed!'));
+ $request->getSession()->getFlashbag()->add('error', $this->__('Hook validation failed!'));
}
}
- $breadcrumbs = $entity->getCollection()->getBreadcrumbs($this->get('router'));
+
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_media_edit', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
return [
- 'breadcrumbs' => $breadcrumbs,
'entity' => $entity,
- 'hook' => $this->getDisplayHookContent(
- 'media',
- 'form_delete',
- $entity->getId(),
- new RouteUrl('cmfcmfmediamodule_media_edit', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ])
- )
+ 'breadcrumbs' => $entity->getCollection()->getBreadcrumbs($this->get('router')),
+ 'hook' => $this->getDisplayHookContent('media', UiHooksCategory::TYPE_FORM_DELETE, $entity->getId(), $hookUrl)
];
}
/**
- * @Route("/media/new")
- * @Method("GET")
- * @Template()
+ * @Route("/media/new", methods={"GET"})
+ * @Template("CmfcmfMediaModule:Media:new.html.twig")
*
* @param Request $request
*
@@ -278,7 +261,8 @@ public function newAction(Request $request)
CollectionPermissionSecurityTree::PERM_LEVEL_ADD_MEDIA
)
->getQuery()
- ->execute();
+ ->execute()
+ ;
return [
'webMediaTypes' => $mediaTypeCollection->getWebMediaTypes(true),
@@ -290,7 +274,7 @@ public function newAction(Request $request)
/**
* @Route("/media/create/{type}/{mediaType}/{collection}", options={"expose"=true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Media:create.html.twig")
*
* @param Request $request
* @param $type
@@ -315,34 +299,26 @@ public function createAction(Request $request, $type, $mediaType, $collection =
$entity = $this->getDefaultEntity($request, $type, $mediaType, $init, $collection);
$form = $mediaType->getFormTypeClass();
- /** @var AbstractType $form */
- $form = new $form($securityManager, $variableApi, $em, true);
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity, $mediaType->getFormOptions($entity));
+ $formOptions = $mediaType->getFormOptions($entity);
+ $formOptions['isCreation'] = true;
/** @var \Symfony\Component\Form\Form $form */
+ $form = $this->createForm($form, $entity, $mediaType->getFormOptions($entity));
$form->handleRequest($request);
if ($form->isValid()) {
- if ($this->hookValidates('media', 'validate_edit')) {
- $em = $this->getDoctrine()->getManager();
+ if ($this->hookValidates('media', UiHooksCategory::TYPE_VALIDATE_EDIT)) {
$em->persist($entity);
$em->flush();
- $this->applyProcessHook(
- 'media',
- 'process_edit',
- $entity->getId(),
- new RouteUrl('cmfcmfmediamodule_media_display', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ])
- );
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
+ $this->applyFormAwareProcessHook($form, 'media', FormAwareCategory::TYPE_PROCESS_EDIT, $entity, $hookUrl);
+ $this->applyProcessHook('media', UiHooksCategory::TYPE_PROCESS_EDIT, $entity->getId(), $hookUrl);
if ($request->query->get('popup', false)) {
- return $this->redirectToRoute(
- 'cmfcmfmediamodule_media_popupembed',
- ['id' => $entity->getId()]
- );
+ return $this->redirectToRoute('cmfcmfmediamodule_media_popupembed', ['id' => $entity->getId()]);
}
return $this->redirectToRoute('cmfcmfmediamodule_media_display', [
@@ -355,16 +331,12 @@ public function createAction(Request $request, $type, $mediaType, $collection =
return [
'form' => $form->createView(),
- 'hook' => $this->getDisplayHookContent(
- 'media',
- 'form_edit'
- )
+ 'hook' => $this->getDisplayHookContent('media', UiHooksCategory::TYPE_FORM_EDIT)
];
}
/**
- * @Route("/media/ajax/matches-paste", options={"expose" = true})
- * @Method("POST")
+ * @Route("/media/ajax/matches-paste", methods={"POST"}, options={"expose" = true})
*
* @param Request $request
*
@@ -375,7 +347,7 @@ public function matchesPasteAction(Request $request)
$this->checkMediaCreationAllowed();
$pastedText = $request->request->get('pastedText', false);
- if ($pastedText === false) {
+ if (false === $pastedText) {
throw new NotFoundHttpException();
}
@@ -393,7 +365,7 @@ public function matchesPasteAction(Request $request)
return $b['score'] - $a['score'];
});
- return new JsonResponse($matches);
+ return $this->json($matches);
}
/**
@@ -430,8 +402,7 @@ public function reorderAction(Request $request)
}
/**
- * @Route("/media/ajax/creation-results/web/{mediaType}", options={"expose"=true})
- * @Method("POST")
+ * @Route("/media/ajax/creation-results/web/{mediaType}", methods={"POST"}, options={"expose"=true})
*
* @param Request $request
*
@@ -452,22 +423,21 @@ public function webCreationAjaxResultsAction(Request $request, $mediaType)
throw new NotFoundHttpException();
}
$q = $request->request->get('q', false);
- if ($q === false) {
+ if (false === $q) {
throw new NotFoundHttpException();
}
$dropdownValue = $request->request->get('dropdownValue', null);
- if ($dropdownValue == "") {
+ if ('' == $dropdownValue) {
$dropdownValue = null;
}
- $results = $mediaType->getSearchResults($request, $q, $dropdownValue);
+ $results = $mediaType->getSearchResults($q, $dropdownValue);
- return new JsonResponse($results);
+ return $this->json($results);
}
/**
- * @Route("/media/ajax/get-media-type", options={"expose"=true})
- * @Method("POST")
+ * @Route("/media/ajax/get-media-type", methods={"POST"}, options={"expose"=true})
*
* @param Request $request
*
@@ -479,7 +449,7 @@ public function getMediaTypeFromFileAction(Request $request)
$mediaTypes = $this->get('cmfcmf_media_module.media_type_collection')->getUploadableMediaTypes();
$files = $request->request->get('files', false);
- if ($files === false) {
+ if (false === $files) {
throw new NotFoundHttpException();
}
$result = [];
@@ -496,7 +466,7 @@ public function getMediaTypeFromFileAction(Request $request)
$selectedMediaType = $mediaType;
}
}
- if ($selectedMediaType === null) {
+ if (null === $selectedMediaType) {
$result[$c] = null;
$notFound++;
} else {
@@ -509,7 +479,7 @@ public function getMediaTypeFromFileAction(Request $request)
}
}
- return new JsonResponse([
+ return $this->json([
'result' => $result,
'multiple' => $multiple,
'notFound' => $notFound
@@ -519,8 +489,7 @@ public function getMediaTypeFromFileAction(Request $request)
/**
* Endpoint for file uploads.
*
- * @Route("/media/upload", options={"expose"=true})
- * @Method("POST")
+ * @Route("/media/upload", methods={"POST"}, options={"expose"=true})
*
* @param Request $request
*
@@ -537,11 +506,11 @@ public function uploadAction(Request $request)
$em = $this->getDoctrine()->getManager();
$collection = $request->request->get('collection', null);
- if ($collection == null) {
+ if (null == $collection) {
$collection = CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID;
}
- if ($request->files->count() != 1) {
+ if (1 != $request->files->count()) {
return new Response(null, Response::HTTP_BAD_REQUEST);
}
@@ -559,21 +528,23 @@ public function uploadAction(Request $request)
$selectedMediaType = $mediaType;
}
}
- if ($selectedMediaType === null) {
+ if (null === $selectedMediaType) {
return new Response($this->__('File type not supported!'), Response::HTTP_FORBIDDEN);
}
+ $dataDirectory = $this->get('service_container')->getParameter('datadir');
+
/** @var AbstractFileEntity $entity */
$entity = $selectedMediaType->getEntityClass();
- $entity = new $entity();
+ $entity = new $entity($this->get('request_stack'), $dataDirectory);
- $variableApi = $this->get('zikula_extensions_module.api.variable');
$form = $selectedMediaType->getFormTypeClass();
- /** @var AbstractType $form */
- $form = new $form($securityManager, $variableApi, $em, true, null, true);
- $form->setTranslator($this->get('translator'));
+ $formOptions = $mediaType->getFormOptions($entity);
+ $formOptions['isCreation'] = true;
+ $formOptions['allowTemporaryUploadCollection'] = true;
+ $formOptions['csrf_protection'] = false;
/** @var \Symfony\Component\Form\Form $form */
- $form = $this->createForm($form, $entity, ['csrf_protection' => false]);
+ $form = $this->createForm($form, $entity, $formOptions);
$form->remove('file');
$form->submit([
@@ -593,10 +564,10 @@ public function uploadAction(Request $request)
$justUploadedIds[] = $entity->getId();
$request->getSession()->set('cmfcmfmediamodule_just_uploaded', $justUploadedIds);
- return new JsonResponse([
+ return $this->json([
'msg' => $this->__('File uploaded!'),
'editUrl' => $this->generateUrl('cmfcmfmediamodule_media_edit', ['slug' => $entity->getSlug(), 'collectionSlug' => $entity->getCollection()->getSlug()]),
- 'openNewTabAndEdit' => $collection == CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID
+ 'openNewTabAndEdit' => CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID == $collection
], Response::HTTP_OK);
} catch (\Exception $e) {
return new Response($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
@@ -604,15 +575,35 @@ public function uploadAction(Request $request)
}
/**
- * @Route("/media/popup-embed/{id}")
- * @Template()
- * @Method("GET")
+ * @Route("/media/popup-embed/{id}", methods={"GET"})
+ * @Template("CmfcmfMediaModule:Media:popupEmbed.html.twig")
+ *
+ * @param Request $request
+ * @param AbstractMediaEntity $entity
+ *
+ * @return array
+ */
+ public function popupEmbedAction(Request $request, AbstractMediaEntity $entity)
+ {
+ if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission(
+ $entity,
+ CollectionPermissionSecurityTree::PERM_LEVEL_MEDIA_DETAILS)
+ ) {
+ throw new AccessDeniedException();
+ }
+
+ return $this->getEmbedDataAction($request, $entity);
+ }
+
+ /**
+ * @Route("/media/embed-data/{id}", methods={"GET"}, options={"expose"=true})
*
+ * @param Request $request
* @param AbstractMediaEntity $entity
*
* @return array
*/
- public function popupEmbedAction(AbstractMediaEntity $entity)
+ public function getEmbedDataAction(Request $request, AbstractMediaEntity $entity)
{
if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission(
$entity,
@@ -623,27 +614,43 @@ public function popupEmbedAction(AbstractMediaEntity $entity)
$mediaTypeCollection = $this->get('cmfcmf_media_module.media_type_collection');
+ $class = get_class($entity);
+ $type = substr($class, strrpos($class, '\\') + 1, -strlen('Entity'));
$mediaType = $mediaTypeCollection->getMediaTypeFromEntity($entity);
- return [
+ $preview = '';
+ if ('Image' == $type) {
+ $preview = $mediaType->renderFullpage($entity);
+ }
+
+ $result = [
+ 'title' => $entity->getTitle(),
+ 'preview' => $preview,
+ 'slug' => $entity->getSlug(),
'embedCodes' => [
'full' => $mediaType->getEmbedCode($entity, 'full'),
'medium' => $mediaType->getEmbedCode($entity, 'medium'),
'small' => $mediaType->getEmbedCode($entity, 'small')
- ]
+ ],
+ 'collection' => $entity->getCollection()
];
+
+ if (!$request->isXmlHttpRequest()) {
+ return $result;
+ }
+
+ return $this->json($result);
}
/**
- * @Route("/download/{collectionSlug}/f/{slug}", requirements={"collectionSlug" = ".+?"})
- * @Method("GET")
+ * @Route("/download/{collectionSlug}/f/{slug}", methods={"GET"}, requirements={"collectionSlug" = ".+?"}, options={"expose"=true})
* @ParamConverter("entity", class="CmfcmfMediaModule:Media\AbstractFileEntity", options={"repository_method" = "findBySlugs", "map_method_signature" = true})
*
* @param AbstractFileEntity $entity
*
* @return BinaryFileResponse
*/
- public function downloadAction(AbstractFileEntity $entity)
+ public function downloadAction(Request $request, AbstractFileEntity $entity)
{
if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission(
$entity,
@@ -667,16 +674,20 @@ public function downloadAction(AbstractFileEntity $entity)
$mediaType = $mediaTypeCollection->getMediaTypeFromEntity($entity);
$response = new BinaryFileResponse($mediaType->getOriginalWithWatermark($entity, 'path', false));
- $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $entity->getBeautifiedFileName());
+
+ if ($request->query->has('inline') && $request->query->get('inline', '0') == '1') {
+ $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $entity->getBeautifiedFileName());
+ } else {
+ $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $entity->getBeautifiedFileName());
+ }
return $response;
}
/**
- * @Route("/{collectionSlug}/f/{slug}", requirements={"collectionSlug" = ".+?"}, options={"expose" = true})
- * @Method("GET")
+ * @Route("/{collectionSlug}/f/{slug}", methods={"GET"}, requirements={"collectionSlug" = ".+?"}, options={"expose" = true})
* @ParamConverter("entity", class="CmfcmfMediaModule:Media\AbstractMediaEntity", options={"repository_method" = "findBySlugs", "map_method_signature" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Media:display.html.twig")
*
* @param AbstractMediaEntity $entity
*
@@ -704,21 +715,17 @@ public function displayAction(AbstractMediaEntity $entity)
}
$mediaTypeCollection = $this->get('cmfcmf_media_module.media_type_collection');
+ $hookUrl = new RouteUrl('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
return [
'mediaType' => $mediaTypeCollection->getMediaTypeFromEntity($entity),
'entity' => $entity,
- 'breadcrumbs' => $entity->getCollection()->getBreadcrumbs($this->get('router'), true),
+ 'breadcrumbs' => $entity->getCollection()->getBreadcrumbs($this->get('router'), true),
'views' => $this->getVar('enableMediaViewCounter', false) ? $entity->getViews() : '-1',
- 'hook' => $this->getDisplayHookContent(
- 'media',
- 'display_view',
- $entity->getId(),
- new RouteUrl('cmfcmfmediamodule_media_display', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ])
- )
+ 'hook' => $this->getDisplayHookContent('media', UiHooksCategory::TYPE_DISPLAY_VIEW, $entity->getId(), $hookUrl)
];
}
@@ -741,8 +748,9 @@ private function checkMediaCreationAllowed()
private function getDefaultEntity(Request $request, $type, MediaTypeInterface $mediaType, $init, $collection)
{
if (!$init) {
+ $dataDirectory = $this->get('service_container')->getParameter('datadir');
$entity = $mediaType->getEntityClass();
- $entity = new $entity();
+ $entity = new $entity($this->get('request_stack'), $dataDirectory);
return $entity;
}
@@ -750,7 +758,7 @@ private function getDefaultEntity(Request $request, $type, MediaTypeInterface $m
case 'web':
try {
/** @var MediaTypeInterface|WebMediaTypeInterface $mediaType */
- $entity = $mediaType->getEntityFromWeb($request);
+ $entity = $mediaType->getEntityFromWeb();
} catch (\Exception $e) {
throw new NotFoundHttpException();
}
@@ -766,7 +774,7 @@ private function getDefaultEntity(Request $request, $type, MediaTypeInterface $m
default:
throw new \LogicException();
}
- if ($collection !== null) {
+ if (null !== $collection) {
$entity->setCollection($this->getDoctrine()->getManager()->find('CmfcmfMediaModule:Collection\CollectionEntity', $collection));
}
diff --git a/Controller/MediaTypeController.php b/Controller/MediaTypeController.php
index dd34620b..92aa5034 100644
--- a/Controller/MediaTypeController.php
+++ b/Controller/MediaTypeController.php
@@ -22,12 +22,13 @@
use Google_Service_YouTube_Video;
use Google_Service_YouTube_VideoSnippet;
use Google_Service_YouTube_VideoStatus;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
@@ -38,7 +39,6 @@ class MediaTypeController extends AbstractController
{
/**
* @Route("/youtube/upload/{id}")
- * @ParamConverter()
*
* @param VideoEntity $entity
* @param Request $request
@@ -66,8 +66,6 @@ public function youtubeUploadAction(VideoEntity $entity, Request $request)
]);
}
- require_once __DIR__ . '/../vendor/autoload.php';
-
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
@@ -75,8 +73,6 @@ public function youtubeUploadAction(VideoEntity $entity, Request $request)
$client->setRedirectUri(
filter_var($this->generateUrl('cmfcmfmediamodule_mediatype_youtubeupload', ['id' => $entity->getId()], RouterInterface::ABSOLUTE_URL), FILTER_SANITIZE_URL));
-
-
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
@@ -107,94 +103,93 @@ public function youtubeUploadAction(VideoEntity $entity, Request $request)
END;
return new Response($htmlBody);
- } else {
- $form = $this->buildYouTubeUploadForm($entity);
- $form->handleRequest($request);
- if (!$form->isValid()) {
- return $this->render('CmfcmfMediaModule:MediaType:Video/youtubeUpload.html.twig', [
- 'entity' => $entity,
- 'form' => $form->createView()
- ]);
- }
+ }
- try {
- $videoPath = $entity->getPath();
-
- // Create a snippet with title, description, tags and category ID
- // Create an asset resource and set its snippet metadata and type.
- $snippet = $this->createVideoSnippet($entity);
-
- // Set the video's status to "public". Valid statuses are "public",
- // "private" and "unlisted".
- $status = new Google_Service_YouTube_VideoStatus();
- $status->privacyStatus = $form->getData()['privacyStatus'];
-
- // Associate the snippet and status objects with a new video resource.
- $video = new Google_Service_YouTube_Video();
- $video->setSnippet($snippet);
- $video->setStatus($status);
-
- // Specify the size of each chunk of data, in bytes. Set a higher value for
- // reliable connection as fewer chunks lead to faster uploads. Set a lower
- // value for better recovery on less reliable connections.
- $chunkSizeBytes = 1 * 1024 * 1024;
-
- // Setting the defer flag to true tells the client to return a request which can be called
- // with ->execute(); instead of making the API call immediately.
- $client->setDefer(true);
-
- // Create a request for the API's videos.insert method to create and upload the video.
- $insertRequest = $youtube->videos->insert("status,snippet", $video);
-
- // Create a MediaFileUpload object for resumable uploads.
- $media = new Google_Http_MediaFileUpload(
- $client,
- $insertRequest,
- $entity->getMimeType(),
- null,
- true,
- $chunkSizeBytes
- );
- $media->setFileSize(filesize($videoPath));
-
-
- // Read the media file and upload it chunk by chunk.
- $status = false;
- $handle = fopen($videoPath, "rb");
- while (!$status && !feof($handle)) {
- $chunk = fread($handle, $chunkSizeBytes);
- $status = $media->nextChunk($chunk);
- }
-
- fclose($handle);
-
- // If you want to make other calls after the file upload, set setDefer back to false
- $client->setDefer(false);
- } catch (Google_Service_Exception $e) {
- $this->addFlash('error', $this->get('translator')->trans('A Google service error occurred: %error%', ['%error%' => $e->getMessage()], 'cmfcmfmediamodule'));
-
- return $this->redirectToRoute('cmfcmfmediamodule_media_display', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ]);
- } catch (Google_Exception $e) {
- $this->addFlash('error', $this->get('translator')->trans('A client error occurred: %error%', ['%error%' => $e->getMessage()], 'cmfcmfmediamodule'));
-
- return $this->redirectToRoute('cmfcmfmediamodule_media_display', [
- 'slug' => $entity->getSlug(),
- 'collectionSlug' => $entity->getCollection()->getSlug()
- ]);
+ $form = $this->buildYouTubeUploadForm($entity);
+ $form->handleRequest($request);
+ if (!$form->isValid()) {
+ return $this->render('CmfcmfMediaModule:MediaType:Video/youtubeUpload.html.twig', [
+ 'entity' => $entity,
+ 'form' => $form->createView()
+ ]);
+ }
+
+ try {
+ $videoPath = $entity->getPath();
+
+ // Create a snippet with title, description, tags and category ID
+ // Create an asset resource and set its snippet metadata and type.
+ $snippet = $this->createVideoSnippet($entity, $request->getLocale());
+
+ // Set the video's status to "public". Valid statuses are "public",
+ // "private" and "unlisted".
+ $status = new Google_Service_YouTube_VideoStatus();
+ $status->privacyStatus = $form->getData()['privacyStatus'];
+
+ // Associate the snippet and status objects with a new video resource.
+ $video = new Google_Service_YouTube_Video();
+ $video->setSnippet($snippet);
+ $video->setStatus($status);
+
+ // Specify the size of each chunk of data, in bytes. Set a higher value for
+ // reliable connection as fewer chunks lead to faster uploads. Set a lower
+ // value for better recovery on less reliable connections.
+ $chunkSizeBytes = 1 * 1024 * 1024;
+
+ // Setting the defer flag to true tells the client to return a request which can be called
+ // with ->execute(); instead of making the API call immediately.
+ $client->setDefer(true);
+
+ // Create a request for the API's videos.insert method to create and upload the video.
+ $insertRequest = $youtube->videos->insert('status,snippet', $video);
+
+ // Create a MediaFileUpload object for resumable uploads.
+ $media = new Google_Http_MediaFileUpload(
+ $client,
+ $insertRequest,
+ $entity->getMimeType(),
+ null,
+ true,
+ $chunkSizeBytes
+ );
+ $media->setFileSize(filesize($videoPath));
+
+ // Read the media file and upload it chunk by chunk.
+ $status = false;
+ $handle = fopen($videoPath, 'rb');
+ while (!$status && !feof($handle)) {
+ $chunk = fread($handle, $chunkSizeBytes);
+ $status = $media->nextChunk($chunk);
}
- $request->getSession()->set('cmfcmfmediamodule_youtube_oauth_token', $client->getAccessToken());
+ fclose($handle);
- $this->addFlash('status', $this->get('translator')->trans('Your video was successfully uploaded.', [], 'cmfcmfmediamodule'));
+ // If you want to make other calls after the file upload, set setDefer back to false
+ $client->setDefer(false);
+ } catch (Google_Service_Exception $e) {
+ $this->addFlash('error', $this->get('translator')->trans('A Google service error occurred: %error%', ['%error%' => $e->getMessage()], 'cmfcmfmediamodule'));
+
+ return $this->redirectToRoute('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
+ } catch (Google_Exception $e) {
+ $this->addFlash('error', $this->get('translator')->trans('A client error occurred: %error%', ['%error%' => $e->getMessage()], 'cmfcmfmediamodule'));
return $this->redirectToRoute('cmfcmfmediamodule_media_display', [
'slug' => $entity->getSlug(),
'collectionSlug' => $entity->getCollection()->getSlug()
]);
}
+
+ $request->getSession()->set('cmfcmfmediamodule_youtube_oauth_token', $client->getAccessToken());
+
+ $this->addFlash('status', $this->get('translator')->trans('Your video was successfully uploaded.', [], 'cmfcmfmediamodule'));
+
+ return $this->redirectToRoute('cmfcmfmediamodule_media_display', [
+ 'slug' => $entity->getSlug(),
+ 'collectionSlug' => $entity->getCollection()->getSlug()
+ ]);
}
/**
@@ -206,14 +201,14 @@ private function buildYouTubeUploadForm(VideoEntity $entity)
{
$builder = $this->createFormBuilder();
$builder
- ->add('privacyStatus', 'choice', [
+ ->add('privacyStatus', ChoiceType::class, [
'choices' => [
- 'public' => $this->get('translator')->trans('Public', [], 'cmfcmfmediamodule'),
- 'unlisted' => $this->get('translator')->trans('Unlisted', [], 'cmfcmfmediamodule'),
- 'private' => $this->get('translator')->trans('Private', [], 'cmfcmfmediamodule')
+ $this->get('translator')->trans('Public', [], 'cmfcmfmediamodule') => 'public',
+ $this->get('translator')->trans('Unlisted', [], 'cmfcmfmediamodule') => 'unlisted',
+ $this->get('translator')->trans('Private', [], 'cmfcmfmediamodule') => 'private'
]
])
- ->add('submit', 'submit', [])
+ ->add('submit', SubmitType::class, [])
->setAction($this->generateUrl('cmfcmfmediamodule_mediatype_youtubeupload', ['id' => $entity->getId()]));
return $builder->getForm();
@@ -221,22 +216,17 @@ private function buildYouTubeUploadForm(VideoEntity $entity)
/**
* @param VideoEntity $entity
+ * @param string $locale
*
* @return Google_Service_YouTube_VideoSnippet
*/
- private function createVideoSnippet(VideoEntity $entity)
+ private function createVideoSnippet(VideoEntity $entity, $locale = 'en')
{
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($entity->getTitle());
$snippet->setDescription($entity->getDescription());
- $snippet->setTags($entity->getCategoryAssignments()->map(function (MediaCategoryAssignmentEntity $assignment) {
- $lang = \ZLanguage::getLanguageCode();
- $displayNames = $assignment->getCategory()->getDisplay_name();
- if (isset($displayNames[$lang])) {
- return $displayNames[$lang];
- }
-
- return $displayNames['en'];
+ $snippet->setTags($entity->getCategoryAssignments()->map(function (MediaCategoryAssignmentEntity $assignment) use ($locale) {
+ return $assignment->getCategory()->getDisplay_name($locale);
}));
// Numeric video category. See
// https://developers.google.com/youtube/v3/docs/videoCategories/list
diff --git a/Controller/PermissionController.php b/Controller/PermissionController.php
index 0b700f1f..e6a439ec 100644
--- a/Controller/PermissionController.php
+++ b/Controller/PermissionController.php
@@ -14,13 +14,11 @@
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\AbstractPermissionEntity;
use Cmfcmf\Module\MediaModule\Exception\InvalidPositionException;
-use Cmfcmf\Module\MediaModule\Form\AbstractType;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -28,6 +26,7 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Zikula\Core\Response\PlainResponse;
@@ -38,8 +37,7 @@ class PermissionController extends AbstractController
{
/**
* @Route("/show/{slug}", requirements={"slug" = ".+?"})
- * @ParamConverter("collectionEntity", class="Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity", options={"slug" = "slug"})
- * @Template()
+ * @Template("CmfcmfMediaModule:Permission:view.html.twig")
*
* @param Request $request
* @param CollectionEntity $collectionEntity
@@ -65,14 +63,14 @@ public function viewAction(Request $request, CollectionEntity $collectionEntity)
'entities' => $entities,
'collection' => $collectionEntity,
'collectionPermissionTypeContainer' => $collectionPermissionTypeContainer,
- 'userId' => \UserUtil::getVar('uid'),
+ 'userId' => $this->get('zikula_users_module.current_user')->get('uid'),
'highlight' => $request->query->get('highlight', null)
];
}
/**
* @Route("/new/{type}/{collection}/{afterPermission}", options={"expose"="true"})
- * @Template(template="CmfcmfMediaModule:Permission:edit.html.twig")
+ * @Template("CmfcmfMediaModule:Permission:edit.html.twig")
*
* @param Request $request
* @param $type
@@ -92,25 +90,23 @@ public function newAction(Request $request, $type, CollectionEntity $collection,
throw new NotFoundHttpException();
}
+ $dataDirectory = $this->get('service_container')->getParameter('datadir');
+
$entity = $permissionType->getEntityClass();
- $entity = new $entity();
+ $entity = new $entity($this->get('request_stack'), $dataDirectory);
$form = $permissionType->getFormClass();
- /** @var AbstractType $form */
- $form = new $form(
- $collection,
- $this->get('cmfcmf_media_module.security_manager'),
- $permissionLevel
- );
- $form->setTranslator($this->get('translator'));
/** @var \Symfony\Component\Form\Form $form */
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm($form, $entity, [
+ 'collection' => $collection,
+ 'permissionLevel' => $permissionLevel
+ ]);
$form->handleRequest($request);
/** @var AbstractPermissionEntity $entity */
$entity->setCollection($collection);
$entity->setPosition($afterPermission->getPosition() + 1);
- if ($permissionLevel == CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS) {
+ if (CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS == $permissionLevel) {
$entity->setGoOn(true);
}
@@ -128,13 +124,15 @@ public function newAction(Request $request, $type, CollectionEntity $collection,
]);
}
- return ['form' => $form->createView(), 'collection' => $collection];
+ return [
+ 'form' => $form->createView(),
+ 'collection' => $collection
+ ];
}
/**
* @Route("/edit/{id}")
- * @ParamConverter("entity", class="CmfcmfMediaModule:Collection\Permission\AbstractPermissionEntity")
- * @Template()
+ * @Template("CmfcmfMediaModule:Permission:edit.html.twig")
*
* @param Request $request
* @param AbstractPermissionEntity $permissionEntity
@@ -150,15 +148,11 @@ public function editAction(Request $request, AbstractPermissionEntity $permissio
->getCollectionPermissionFromEntity($permissionEntity)
->getFormClass();
- /** @var AbstractType $form */
- $form = new $form(
- $permissionEntity->getCollection(),
- $this->get('cmfcmf_media_module.security_manager'),
- $permissionLevel
- );
- $form->setTranslator($this->get('translator'));
/** @var \Symfony\Component\Form\Form $form */
- $form = $this->createForm($form, $permissionEntity);
+ $form = $this->createForm($form, $permissionEntity, [
+ 'collection' => $permissionEntity->getCollection(),
+ 'permissionLevel' => $permissionLevel
+ ]);
$form->handleRequest($request);
if (!$form->isValid()) {
@@ -188,8 +182,7 @@ public function editAction(Request $request, AbstractPermissionEntity $permissio
/**
* @Route("/delete/{id}")
- * @ParamConverter("permissionEntity", class="CmfcmfMediaModule:Collection\Permission\AbstractPermissionEntity")
- * @Template()
+ * @Template("CmfcmfMediaModule:Permission:delete.html.twig")
*
* @param Request $request
* @param AbstractPermissionEntity $permissionEntity
@@ -244,7 +237,7 @@ public function reorderAction(
try {
$this->getPermissionLevelOrException($permissionEntity->getCollection(), $permissionEntity);
} catch (AccessDeniedException $e) {
- return new JsonResponse([], JsonResponse::HTTP_FORBIDDEN);
+ return $this->json([], JsonResponse::HTTP_FORBIDDEN);
}
$repository = $this->getDoctrine()->getRepository(
@@ -262,16 +255,16 @@ public function reorderAction(
try {
$repository->save($permissionEntity, false);
} catch (OptimisticLockException $e) {
- return new JsonResponse(['error' => $this->__(
+ return $this->json(['error' => $this->__(
'Someone modified a permission rule. Please reload the page and try again!'
)], Response::HTTP_FORBIDDEN);
} catch (InvalidPositionException $e) {
- return new JsonResponse(['error' => $this->__(
+ return $this->json(['error' => $this->__(
'You cannot move the permission rule to this position!'
)], Response::HTTP_FORBIDDEN);
}
- return new JsonResponse(['newVersion' => $permissionEntity->getVersion()]);
+ return $this->json(['newVersion' => $permissionEntity->getVersion()]);
}
/**
@@ -317,10 +310,10 @@ private function getPermissionLevelOrException(
if ($securityManager->hasPermission($collectionEntity, CollectionPermissionSecurityTree::PERM_LEVEL_CHANGE_PERMISSIONS)) {
return CollectionPermissionSecurityTree::PERM_LEVEL_CHANGE_PERMISSIONS;
}
- if ($permissionEntity == null) {
+ if (null === $permissionEntity) {
throw new AccessDeniedException();
}
- if ($permissionEntity->getCreatedUserId() == \UserUtil::getVar('uid')) {
+ if ($permissionEntity->getCreatedBy()->getUid() == $this->get('zikula_users_module.current_user')->get('uid')) {
if ($securityManager->hasPermission($collectionEntity, CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS)) {
return CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS;
}
diff --git a/Controller/SettingsController.php b/Controller/SettingsController.php
index 3e61e12c..64bd3701 100644
--- a/Controller/SettingsController.php
+++ b/Controller/SettingsController.php
@@ -13,12 +13,12 @@
use Cmfcmf\Module\MediaModule\Form\SettingsType;
use Cmfcmf\Module\MediaModule\Helper\PHPIniHelper;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\FileinfoMimeTypeGuesser;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Zikula\ThemeModule\Engine\Annotation\Theme;
@@ -39,7 +39,7 @@ public function indexAction()
/**
* @Route("/requirements")
- * @Template()
+ * @Template("CmfcmfMediaModule:Settings:requirements.html.twig")
* @Theme("admin")
*/
public function requirementsAction()
@@ -74,7 +74,6 @@ public function requirementsAction()
['%size%' => PHPIniHelper::formatFileSize($maxUploadSize)], 'cmfcmfmediamodule'),
];
-
$highMemoryRequired = false;
try {
new \Imagine\Imagick\Imagine();
@@ -180,7 +179,7 @@ public function requirementsAction()
/**
* @Route("/general", options={"expose" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Settings:general.html.twig")
* @Theme("admin")
*
* @param Request $request
@@ -191,23 +190,13 @@ public function generalAction(Request $request)
{
$this->ensurePermission();
- $collectionTemplateCollection = $this->get(
- 'cmfcmf_media_module.collection_template_collection');
- $translator = $this->get('translator');
- $variableApi = $this->get('zikula_extensions_module.api.variable');
-
- $form = $this->createForm(new SettingsType(
- $translator,
- $variableApi,
- $collectionTemplateCollection->getCollectionTemplateTitles()
- )
- );
+ $form = $this->createForm(SettingsType::class);
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
foreach ($data as $name => $value) {
- \ModUtil::setVar('CmfcmfMediaModule', $name, $value);
+ $this->setVar($name, $value);
}
$this->addFlash('status', $this->__('Settings saved!'));
}
@@ -219,7 +208,7 @@ public function generalAction(Request $request)
/**
* @Route("/scribite", options={"expose" = true})
- * @Template()
+ * @Template("CmfcmfMediaModule:Settings:scribite.html.twig")
* @Theme("admin")
*
* @return array
@@ -228,26 +217,23 @@ public function scribiteAction()
{
$this->ensurePermission();
- $scribiteInstalled = \ModUtil::available('Scribite');
+ $scribiteInstalled = $this->get('kernel')->isBundle('ZikulaScribiteModule');
$descriptionEscapingStrategyForCollectionOk = true;
$descriptionEscapingStrategyForMediaOk = true;
if ($scribiteInstalled) {
- $mediaBinding = $this->get('hook_dispatcher')->getBindingBetweenAreas(
- "subscriber.cmfcmfmediamodule.ui_hooks.media",
- "provider.scribite.ui_hooks.editor");
- $collectionBinding = $this->get('hook_dispatcher')->getBindingBetweenAreas(
- "subscriber.cmfcmfmediamodule.ui_hooks.collection",
- "provider.scribite.ui_hooks.editor");
+ $hookDispatcher = $this->get('hook_dispatcher');
+ $mediaBinding = $hookDispatcher->getBindingBetweenAreas(
+ 'subscriber.cmfcmfmediamodule.ui_hooks.media',
+ 'provider.zikulascribitemodule.ui_hooks.editor');
+ $collectionBinding = $hookDispatcher->getBindingBetweenAreas(
+ 'subscriber.cmfcmfmediamodule.ui_hooks.collections',
+ 'provider.zikulascribitemodule.ui_hooks.editor');
$descriptionEscapingStrategyForCollectionOk = !is_object($collectionBinding)
- || \ModUtil::getVar(
- 'CmfcmfMediaModule',
- 'descriptionEscapingStrategyForCollection') == 'raw';
+ || 'raw' == $this->getVar('descriptionEscapingStrategyForCollection');
$descriptionEscapingStrategyForMediaOk = !is_object($mediaBinding)
- || \ModUtil::getVar(
- 'CmfcmfMediaModule',
- 'descriptionEscapingStrategyForMedia') == 'raw';
+ || 'raw' == $this->getVar('descriptionEscapingStrategyForMedia');
}
return [
diff --git a/Controller/UpgradeController.php b/Controller/UpgradeController.php
index 4207aea5..6d8ec89a 100644
--- a/Controller/UpgradeController.php
+++ b/Controller/UpgradeController.php
@@ -13,10 +13,10 @@
use Cmfcmf\Module\MediaModule\Exception\UpgradeFailedException;
use Cmfcmf\Module\MediaModule\Exception\UpgradeNotRequiredException;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Zikula\ThemeModule\Engine\Annotation\Theme;
@@ -24,7 +24,7 @@ class UpgradeController extends AbstractController
{
/**
* @Route("/settings/upgrade")
- * @Template()
+ * @Template("CmfcmfMediaModule:Upgrade:doUpgrade.html.twig")
* @Theme("admin")
*
* @return array|RedirectResponse
@@ -35,7 +35,7 @@ public function doUpgradeAction()
throw new AccessDeniedException();
}
- $hasPermission = \SecurityUtil::checkPermission('ZikulaExtensionsModule::', '::', ACCESS_ADMIN);
+ $hasPermission = $this->hasPermission('ZikulaExtensionsModule::', '::', ACCESS_ADMIN);
$upgrader = $this->get('cmfcmf_media_module.upgrade.module_upgrader');
return [
@@ -69,7 +69,7 @@ public function ajaxAction($step)
$this->resetUpgradeMessage();
}
- return new JsonResponse([
+ return $this->json([
'proceed' => true,
'message' => null,
'done' => $upgradeDone
@@ -77,19 +77,19 @@ public function ajaxAction($step)
} catch (UpgradeNotRequiredException $e) {
$this->resetUpgradeMessage();
- return new JsonResponse([
+ return $this->json([
'proceed' => false,
'message' => $e->getMessage(),
'done' => false
]);
} catch (UpgradeFailedException $e) {
- return new JsonResponse([
+ return $this->json([
'proceed' => false,
'message' => $e->getMessage(),
'done' => false
]);
} catch (\Exception $e) {
- return new JsonResponse([
+ return $this->json([
'proceed' => false,
'message' => $this->get('translator')->trans(
'Something unexpected happened. Please report this problem and give the following information: %s',
@@ -102,7 +102,7 @@ public function ajaxAction($step)
private function resetUpgradeMessage()
{
- \ModUtil::setVar('CmfcmfMediaModule', 'newVersionAvailable', false);
- \ModUtil::setVar('CmfcmfMediaModule', 'lastNewVersionCheck', 0);
+ $this->setVar('newVersionAvailable', false);
+ $this->setVar('lastNewVersionCheck', 0);
}
}
diff --git a/Controller/WatermarkController.php b/Controller/WatermarkController.php
index c364fc54..8966a2a2 100644
--- a/Controller/WatermarkController.php
+++ b/Controller/WatermarkController.php
@@ -19,15 +19,13 @@
use Cmfcmf\Module\MediaModule\Form\Watermark\TextWatermarkType;
use Doctrine\ORM\OptimisticLockException;
use Gedmo\Uploadable\Uploadable;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
@@ -36,9 +34,8 @@
class WatermarkController extends AbstractController
{
/**
- * @Route("/")
- * @Method("GET")
- * @Template()
+ * @Route("/", methods={"GET"})
+ * @Template("CmfcmfMediaModule:Watermark:index.html.twig")
*/
public function indexAction()
{
@@ -55,7 +52,7 @@ public function indexAction()
/**
* @Route("/new/{type}", requirements={"type"="image|text"})
- * @Template(template="CmfcmfMediaModule:Watermark:edit.html.twig")
+ * @Template("CmfcmfMediaModule:Watermark:edit.html.twig")
*
* @param Request $request
* @param $type
@@ -67,18 +64,18 @@ public function newAction(Request $request, $type)
if (!$this->get('cmfcmf_media_module.security_manager')->hasPermission('watermark', 'new')) {
throw new AccessDeniedException();
}
- if ($type == 'image') {
- $entity = new ImageWatermarkEntity();
- $form = new ImageWatermarkType();
- } elseif ($type == 'text') {
- $entity = new TextWatermarkEntity();
- $form = new TextWatermarkType();
+ $dataDirectory = $this->get('service_container')->getParameter('datadir');
+ if ('image' == $type) {
+ $entity = new ImageWatermarkEntity($this->get('request_stack'), $dataDirectory);
+ $form = ImageWatermarkType::class;
+ } elseif ('text' == $type) {
+ $entity = new TextWatermarkEntity($this->get('request_stack'), $dataDirectory);
+ $form = TextWatermarkType::class;
} else {
throw new NotFoundHttpException();
}
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm($form, $entity, ['entity' => $entity]);
$form->handleRequest($request);
if ($form->isValid()) {
@@ -104,8 +101,7 @@ public function newAction(Request $request, $type)
/**
* @Route("/edit/{id}")
- * @ParamConverter("entity", class="CmfcmfMediaModule:Watermark\AbstractWatermarkEntity")
- * @Template()
+ * @Template("CmfcmfMediaModule:Watermark:edit.html.twig")
*
* @param Request $request
* @param AbstractWatermarkEntity $entity
@@ -119,15 +115,14 @@ public function editAction(Request $request, AbstractWatermarkEntity $entity)
}
if ($entity instanceof ImageWatermarkEntity) {
- $form = new ImageWatermarkType($entity);
+ $form = ImageWatermarkType::class;
} elseif ($entity instanceof TextWatermarkEntity) {
- $form = new TextWatermarkType();
+ $form = TextWatermarkType::class;
} else {
throw new \LogicException();
}
- $form->setTranslator($this->get('translator'));
- $form = $this->createForm($form, $entity);
+ $form = $this->createForm($form, $entity, ['entity' => $entity]);
$form->handleRequest($request);
if (!$form->isValid()) {
@@ -138,7 +133,7 @@ public function editAction(Request $request, AbstractWatermarkEntity $entity)
if ($entity instanceof Uploadable) {
/** @var UploadedFile $file */
$file = $form->get('file')->getData();
- if ($file !== null && $file->isValid()) {
+ if (null !== $file && $file->isValid()) {
// If the file is invalid, it means that no new file has been selected
// to replace the already uploaded file.
$manager = $this->get('stof_doctrine_extensions.uploadable.manager');
@@ -154,14 +149,13 @@ public function editAction(Request $request, AbstractWatermarkEntity $entity)
goto edit_error;
}
- // Cleanup existing thumbnails.
- /** @var \SystemPlugin_Imagine_Manager $imagineManager */
- $imagineManager = $this->get('systemplugin.imagine.manager');
- $imagineManager->setModule('CmfcmfMediaModule');
+ // Cleanup existing thumbnails
+ /** @var Liip\ImagineBundle\Imagine\Cache\CacheManager $imagineCacheManager */
+ $imagineCacheManager = $this->get('liip_imagine.cache.manager');
/** @var WatermarkRepository $repository */
$repository = $em->getRepository('CmfcmfMediaModule:Watermark\AbstractWatermarkEntity');
- $repository->cleanupThumbs($entity, $imagineManager);
+ $repository->cleanupThumbs($entity, $imagineCacheManager);
$this->addFlash('status', $this->__('Watermark updated!'));
@@ -174,8 +168,7 @@ public function editAction(Request $request, AbstractWatermarkEntity $entity)
/**
* @Route("/delete/{id}")
- * @ParamConverter("entity", class="CmfcmfMediaModule:Watermark\AbstractWatermarkEntity")
- * @Template()
+ * @Template("CmfcmfMediaModule:Watermark:delete.html.twig")
*
* @param Request $request
* @param AbstractWatermarkEntity $entity
@@ -192,14 +185,15 @@ public function deleteAction(Request $request, AbstractWatermarkEntity $entity)
return ['entity' => $entity];
}
- // Cleanup existing thumbnails.
- /** @var \SystemPlugin_Imagine_Manager $imagineManager */
- $imagineManager = $this->get('systemplugin.imagine.manager');
- $imagineManager->setModule('CmfcmfMediaModule');
-
$em = $this->getDoctrine()->getManager();
+
+ // Cleanup existing thumbnails
+ /** @var Liip\ImagineBundle\Imagine\Cache\CacheManager $imagineCacheManager */
+ $imagineCacheManager = $this->get('liip_imagine.cache.manager');
+
+ /** @var WatermarkRepository $repository */
$repository = $em->getRepository('CmfcmfMediaModule:Watermark\AbstractWatermarkEntity');
- $repository->cleanupThumbs($entity, $imagineManager);
+ $repository->cleanupThumbs($entity, $imagineCacheManager);
$em->remove($entity);
$em->flush();
diff --git a/DependencyInjection/CollectionPermissionCompilerPass.php b/DependencyInjection/Compiler/CollectionPermissionCompilerPass.php
similarity index 94%
rename from DependencyInjection/CollectionPermissionCompilerPass.php
rename to DependencyInjection/Compiler/CollectionPermissionCompilerPass.php
index 70405a8b..30d7c2c3 100644
--- a/DependencyInjection/CollectionPermissionCompilerPass.php
+++ b/DependencyInjection/Compiler/CollectionPermissionCompilerPass.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\DependencyInjection;
+namespace Cmfcmf\Module\MediaModule\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
diff --git a/DependencyInjection/CollectionTemplateCompilerPass.php b/DependencyInjection/Compiler/CollectionTemplateCompilerPass.php
similarity index 94%
rename from DependencyInjection/CollectionTemplateCompilerPass.php
rename to DependencyInjection/Compiler/CollectionTemplateCompilerPass.php
index 59e3c512..014882ef 100644
--- a/DependencyInjection/CollectionTemplateCompilerPass.php
+++ b/DependencyInjection/Compiler/CollectionTemplateCompilerPass.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\DependencyInjection;
+namespace Cmfcmf\Module\MediaModule\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
diff --git a/DependencyInjection/FontCompilerPass.php b/DependencyInjection/Compiler/FontCompilerPass.php
similarity index 88%
rename from DependencyInjection/FontCompilerPass.php
rename to DependencyInjection/Compiler/FontCompilerPass.php
index 02101a26..bbf46341 100644
--- a/DependencyInjection/FontCompilerPass.php
+++ b/DependencyInjection/Compiler/FontCompilerPass.php
@@ -9,14 +9,14 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\DependencyInjection;
+namespace Cmfcmf\Module\MediaModule\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
- * Calls "add_FontLoader" for each font loader on the font collection.
+ * Calls "addFontLoader" for each font loader on the font collection.
*/
class FontCompilerPass implements CompilerPassInterface
{
diff --git a/DependencyInjection/ImporterCompilerPass.php b/DependencyInjection/Compiler/ImporterCompilerPass.php
similarity index 87%
rename from DependencyInjection/ImporterCompilerPass.php
rename to DependencyInjection/Compiler/ImporterCompilerPass.php
index 992cf0f0..751b31c1 100644
--- a/DependencyInjection/ImporterCompilerPass.php
+++ b/DependencyInjection/Compiler/ImporterCompilerPass.php
@@ -9,12 +9,15 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\DependencyInjection;
+namespace Cmfcmf\Module\MediaModule\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
+/**
+ * Calls "addImporter" for each importer on the importer collection.
+ */
class ImporterCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
diff --git a/DependencyInjection/MediaTypeCompilerPass.php b/DependencyInjection/Compiler/MediaTypeCompilerPass.php
similarity index 94%
rename from DependencyInjection/MediaTypeCompilerPass.php
rename to DependencyInjection/Compiler/MediaTypeCompilerPass.php
index 7fc9c488..4206997f 100644
--- a/DependencyInjection/MediaTypeCompilerPass.php
+++ b/DependencyInjection/Compiler/MediaTypeCompilerPass.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\DependencyInjection;
+namespace Cmfcmf\Module\MediaModule\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
diff --git a/Entity/Collection/CollectionEntity.php b/Entity/Collection/CollectionEntity.php
index 6905316c..503c07a7 100644
--- a/Entity/Collection/CollectionEntity.php
+++ b/Entity/Collection/CollectionEntity.php
@@ -17,9 +17,9 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Watermark\AbstractWatermarkEntity;
use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
+use Cmfcmf\Module\MediaModule\Traits\StandardFieldsTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
-use DoctrineExtensions\StandardFields\Mapping\Annotation as ZK;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Sluggable\Sluggable;
use Gedmo\Tree\Node;
@@ -34,6 +34,8 @@
*/
class CollectionEntity implements Node, Sluggable
{
+ use StandardFieldsTrait;
+
const TEMPORARY_UPLOAD_COLLECTION_ID = 1;
/**
@@ -158,46 +160,6 @@ class CollectionEntity implements Node, Sluggable
*/
private $categoryAssignments;
- /**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="create")
- *
- * No assertions.
- *
- * @var int
- */
- protected $createdUserId;
-
- /**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="update")
- *
- * No assertions.
- *
- * @var int
- */
- protected $updatedUserId;
-
- /**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="create")
- *
- * No assertions.
- *
- * @var \DateTime
- */
- protected $createdDate;
-
- /**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="update")
- *
- * No assertions.
- *
- * @var \DateTime
- */
- protected $updatedDate;
-
/**
* @ORM\Column(type="integer")
* @ORM\Version
@@ -295,7 +257,7 @@ public function __construct()
*/
public function isPrimaryMediumInMediaCollection()
{
- return $this->primaryMedium === null || $this->media->contains($this->primaryMedium);
+ return null === $this->primaryMedium || $this->media->contains($this->primaryMedium);
}
/**
@@ -313,7 +275,7 @@ public function toArrayForJsTree(
$children = true;
$isSelected = false;
- if ($hookedObjectEntity != null) {
+ if (null != $hookedObjectEntity) {
/** @var HookedObjectCollectionEntity $hookedObjectCollectionEntity */
foreach ($hookedObjectEntity->getHookedObjectCollections() as $hookedObjectCollectionEntity) {
if ($this->id == $hookedObjectCollectionEntity->getCollection()->getId()) {
@@ -398,7 +360,7 @@ public function setTitle($title)
}
/**
- * @deprecated Use $this->getPrimaryMedium() instead.
+ * @deprecated use $this->getPrimaryMedium() instead
*
* @return AbstractMediaEntity|null
*/
@@ -409,7 +371,7 @@ public function getMediaForThumbnail()
/**
* @param RouterInterface $router
- * @param bool $selfIsClickable Whether or not this collection is clickable.
+ * @param bool $selfIsClickable whether or not this collection is clickable
*
* @return array
*/
@@ -419,7 +381,7 @@ public function getBreadcrumbs(RouterInterface $router, $selfIsClickable = false
$breadcrumbs = [];
/** @var CollectionEntity $parent */
- while (($parent = $child->getParent()) !== null) {
+ while (null !== ($parent = $child->getParent())) {
$breadcrumbs[] = [
'url' => $router->generate('cmfcmfmediamodule_collection_display', ['slug' => $parent->getSlug()]),
'title' => $parent->getTitle()
@@ -451,7 +413,7 @@ public function getBreadcrumbs(RouterInterface $router, $selfIsClickable = false
*/
public function isRoot()
{
- return $this->parent === null;
+ return null === $this->parent;
}
/**
@@ -533,86 +495,6 @@ public function setDescription($description)
return $this;
}
- /**
- * @return int
- */
- public function getCreatedUserId()
- {
- return $this->createdUserId;
- }
-
- /**
- * @param int $createdUserId
- *
- * @return CollectionEntity
- */
- public function setCreatedUserId($createdUserId)
- {
- $this->createdUserId = $createdUserId;
-
- return $this;
- }
-
- /**
- * @return int
- */
- public function getUpdatedUserId()
- {
- return $this->updatedUserId;
- }
-
- /**
- * @param int $updatedUserId
- *
- * @return CollectionEntity
- */
- public function setUpdatedUserId($updatedUserId)
- {
- $this->updatedUserId = $updatedUserId;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getCreatedDate()
- {
- return $this->createdDate;
- }
-
- /**
- * @param \DateTime $createdDate
- *
- * @return CollectionEntity
- */
- public function setCreatedDate($createdDate)
- {
- $this->createdDate = $createdDate;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getUpdatedDate()
- {
- return $this->updatedDate;
- }
-
- /**
- * @param \DateTime $updatedDate
- *
- * @return CollectionEntity
- */
- public function setUpdatedDate($updatedDate)
- {
- $this->updatedDate = $updatedDate;
-
- return $this;
- }
-
/**
* @return AbstractWatermarkEntity|null
*/
@@ -868,7 +750,7 @@ public function setPrimaryMedium($primaryMedium)
*/
public function getPrimaryMedium($useFirstIfNoneSpecified = false)
{
- if ($useFirstIfNoneSpecified && $this->primaryMedium === null && !$this->media->isEmpty()) {
+ if ($useFirstIfNoneSpecified && null === $this->primaryMedium && !$this->media->isEmpty()) {
return $this->media->first();
}
diff --git a/Entity/Collection/Permission/AbstractPermissionEntity.php b/Entity/Collection/Permission/AbstractPermissionEntity.php
index c798dab9..323ec8f3 100644
--- a/Entity/Collection/Permission/AbstractPermissionEntity.php
+++ b/Entity/Collection/Permission/AbstractPermissionEntity.php
@@ -13,9 +13,9 @@
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\Restriction\AbstractPermissionRestrictionEntity;
+use Cmfcmf\Module\MediaModule\Traits\StandardFieldsTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
-use DoctrineExtensions\StandardFields\Mapping\Annotation as ZK;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Sortable\Sortable;
use Symfony\Component\Validator\Constraints as Assert;
@@ -35,6 +35,8 @@
*/
abstract class AbstractPermissionEntity implements Sortable
{
+ use StandardFieldsTrait;
+
/**
* @ORM\Column(type="integer")
* @ORM\Id
@@ -159,46 +161,6 @@ abstract class AbstractPermissionEntity implements Sortable
*/
protected $restrictions;
- /**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="create")
- *
- * No assertions.
- *
- * @var int.
- */
- protected $createdUserId;
-
- /**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="update")
- *
- * No assertions.
- *
- * @var int.
- */
- protected $updatedUserId;
-
- /**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="create")
- *
- * No assertions.
- *
- * @var \DateTime.
- */
- protected $createdDate;
-
- /**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="update")
- *
- * No assertions.
- *
- * @var \DateTime.
- */
- protected $updatedDate;
-
public function __construct()
{
$this->description = "";
@@ -477,84 +439,4 @@ public function setLocked($locked)
return $this;
}
-
- /**
- * @return int
- */
- public function getCreatedUserId()
- {
- return $this->createdUserId;
- }
-
- /**
- * @param int $createdUserId
- *
- * @return $this
- */
- public function setCreatedUserId($createdUserId)
- {
- $this->createdUserId = $createdUserId;
-
- return $this;
- }
-
- /**
- * @return int
- */
- public function getUpdatedUserId()
- {
- return $this->updatedUserId;
- }
-
- /**
- * @param int $updatedUserId
- *
- * @return $this
- */
- public function setUpdatedUserId($updatedUserId)
- {
- $this->updatedUserId = $updatedUserId;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getCreatedDate()
- {
- return $this->createdDate;
- }
-
- /**
- * @param \DateTime $createdDate
- *
- * @return $this
- */
- public function setCreatedDate($createdDate)
- {
- $this->createdDate = $createdDate;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getUpdatedDate()
- {
- return $this->updatedDate;
- }
-
- /**
- * @param \DateTime $updatedDate
- *
- * @return $this
- */
- public function setUpdatedDate($updatedDate)
- {
- $this->updatedDate = $updatedDate;
-
- return $this;
- }
}
diff --git a/Entity/Media/AbstractFileEntity.php b/Entity/Media/AbstractFileEntity.php
index 390898d9..63ad5e25 100644
--- a/Entity/Media/AbstractFileEntity.php
+++ b/Entity/Media/AbstractFileEntity.php
@@ -14,6 +14,7 @@
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Uploadable\Uploadable;
+use Symfony\Component\HttpFoundation\RequestStack;
/**
* @ORM\Entity(repositoryClass="Cmfcmf\Module\MediaModule\Entity\Media\Repository\MediaRepository")
@@ -52,9 +53,13 @@ abstract class AbstractFileEntity extends AbstractMediaEntity implements Uploada
*/
protected $downloadAllowed;
- public function __construct()
+ /**
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
+ */
+ public function __construct(RequestStack $requestStack, $dataDirectory = '')
{
- parent::__construct();
+ parent::__construct($requestStack, $dataDirectory);
$this->downloadAllowed = true;
}
@@ -63,7 +68,7 @@ public function getPathToUploadTo($defaultPath)
{
unset($defaultPath);
- return \FileUtil::getDataDirectory() . '/cmfcmf-media-module/media';
+ return $this->dataDirectory . '/cmfcmf-media-module/media';
}
public function getPath()
@@ -73,7 +78,7 @@ public function getPath()
public function getUrl()
{
- return \System::getBaseUri() . '/' . $this->getPath();
+ return $this->getBaseUri() . '/' . $this->getPath();
}
public function getBeautifiedFileName()
diff --git a/Entity/Media/AbstractMediaEntity.php b/Entity/Media/AbstractMediaEntity.php
index 9e552d5b..3d1aa179 100644
--- a/Entity/Media/AbstractMediaEntity.php
+++ b/Entity/Media/AbstractMediaEntity.php
@@ -16,12 +16,13 @@
use Cmfcmf\Module\MediaModule\Entity\HookedObject\HookedObjectMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\License\LicenseEntity;
use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
+use Cmfcmf\Module\MediaModule\Traits\StandardFieldsTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
-use DoctrineExtensions\StandardFields\Mapping\Annotation as ZK;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Sluggable\Sluggable;
use Gedmo\Sortable\Sortable;
+use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraints as Assert;
/**
@@ -51,6 +52,8 @@
*/
abstract class AbstractMediaEntity implements Sluggable, Sortable
{
+ use StandardFieldsTrait;
+
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
@@ -181,38 +184,20 @@ abstract class AbstractMediaEntity implements Sluggable, Sortable
private $categoryAssignments;
/**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="create")
- *
- * @var int.
- */
- protected $createdUserId;
-
- /**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="update")
- *
- * @var int.
+ * @var RequestStack
*/
- protected $updatedUserId;
+ protected $requestStack;
/**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="create")
- *
- * @var \DateTime.
+ * @var string
*/
- protected $createdDate;
+ protected $dataDirectory;
/**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="update")
- *
- * @var \DateTime.
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
*/
- protected $updatedDate;
-
- public function __construct()
+ public function __construct(RequestStack $requestStack, $dataDirectory = '')
{
// Position at the end of the album.
$this->position = -1;
@@ -221,6 +206,10 @@ public function __construct()
$this->downloads = 0;
$this->hookedObjectMedia = new ArrayCollection();
$this->categoryAssignments = new ArrayCollection();
+
+ // TODO refactor these dependencies out of the entities
+ $this->requestStack = $requestStack;
+ $this->dataDirectory = $dataDirectory;
}
/**
@@ -236,36 +225,35 @@ public function makeNonPrimaryOnDelete()
public function getImagineId()
{
- return "media-{$this->id}";
+ return 'media-' . $this->id;
}
public function getAttribution($format = 'html')
{
- if ($this->author === null && $this->authorUrl === null) {
+ if (null === $this->author && null === $this->authorUrl) {
return null;
}
- $dom = \ZLanguage::getModuleDomain('CmfcmfMediaModule');
- if ($format == 'html') {
- if ($this->authorUrl === null) {
+ if ('html' == $format) {
+ if (null === $this->authorUrl) {
$author = htmlentities($this->author);
- } elseif ($this->author === null) {
+ } elseif (null === $this->author) {
$author = '' . htmlentities($this->authorUrl) . ' ';
} else {
$author = '' . htmlentities($this->author) . ' ';
}
- } elseif ($format == 'raw') {
- $author = "";
- if ($this->author !== null) {
- $author .= $this->author . " ";
+ } elseif ('raw' == $format) {
+ $author = '';
+ if (null !== $this->author) {
+ $author .= $this->author . ' ';
}
- if ($this->authorUrl !== null) {
- $author .= "(" . $this->authorUrl . ")";
+ if (null !== $this->authorUrl) {
+ $author .= '(' . $this->authorUrl . ')';
}
$author = trim($author);
}
- return __f('By %s', [$author], $dom);
+ return $author;
}
/**
@@ -390,86 +378,6 @@ public function getLicense()
return $this->license;
}
- /**
- * @return int
- */
- public function getCreatedUserId()
- {
- return $this->createdUserId;
- }
-
- /**
- * @param int $createdUserId
- *
- * @return $this
- */
- public function setCreatedUserId($createdUserId)
- {
- $this->createdUserId = $createdUserId;
-
- return $this;
- }
-
- /**
- * @return int
- */
- public function getUpdatedUserId()
- {
- return $this->updatedUserId;
- }
-
- /**
- * @param int $updatedUserId
- *
- * @return $this
- */
- public function setUpdatedUserId($updatedUserId)
- {
- $this->updatedUserId = $updatedUserId;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getCreatedDate()
- {
- return $this->createdDate;
- }
-
- /**
- * @param \DateTime $createdDate
- *
- * @return $this
- */
- public function setCreatedDate($createdDate)
- {
- $this->createdDate = $createdDate;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getUpdatedDate()
- {
- return $this->updatedDate;
- }
-
- /**
- * @param \DateTime $updatedDate
- *
- * @return $this
- */
- public function setUpdatedDate($updatedDate)
- {
- $this->updatedDate = $updatedDate;
-
- return $this;
- }
-
/**
* @return mixed
*/
@@ -568,13 +476,19 @@ public function toArrayForFinder(MediaTypeCollection $mediaTypeCollection, $incl
$type = substr($class, strrpos($class, '\\') + 1, -strlen('Entity'));
$mediaType = $mediaTypeCollection->getMediaTypeFromEntity($this);
+ $preview = '';
+ if ('Image' == $type) {
+ $preview = $mediaType->renderFullpage($this);
+ }
+
return [
'id' => $this->id,
'type' => $type,
'title' => $this->title,
+ 'preview' => $preview,
'slug' => $this->slug,
'description' => $this->description,
- 'license' => $this->getLicense() !== null ? $this->getLicense()->toArray() : null,
+ 'license' => null !== $this->getLicense() ? $this->getLicense()->toArray() : null,
'embedCodes' => [
'full' => $mediaType->getEmbedCode($this),
'medium' => $mediaType->getEmbedCode($this, 'medium'),
@@ -737,4 +651,33 @@ public function setDownloads($downloads)
return $this;
}
+
+ protected function getBaseUri()
+ {
+ return $this->requestStack->getCurrentRequest()->getBasePath();
+ }
+
+ /**
+ * @param RequestStack $requestStack
+ *
+ * @return AbstractWatermarkEntity
+ */
+ public function setRequestStack(RequestStack $requestStack)
+ {
+ $this->requestStack = $requestStack;
+
+ return $this;
+ }
+
+ /**
+ * @param string $dataDirectory
+ *
+ * @return AbstractWatermarkEntity
+ */
+ public function setDataDirectory($dataDirectory)
+ {
+ $this->dataDirectory = $dataDirectory;
+
+ return $this;
+ }
}
diff --git a/Entity/Media/PlaintextEntity.php b/Entity/Media/PlaintextEntity.php
index 542b80c5..24dfe899 100644
--- a/Entity/Media/PlaintextEntity.php
+++ b/Entity/Media/PlaintextEntity.php
@@ -12,15 +12,20 @@
namespace Cmfcmf\Module\MediaModule\Entity\Media;
use Doctrine\ORM\Mapping as ORM;
+use Symfony\Component\HttpFoundation\RequestStack;
/**
* @ORM\Entity()
*/
class PlaintextEntity extends AbstractFileEntity
{
- public function __construct()
+ /**
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
+ */
+ public function __construct(RequestStack $requestStack, $dataDirectory = '')
{
- parent::__construct();
+ parent::__construct($requestStack, $dataDirectory);
$this->setUseSyntaxHighlighting(true);
}
diff --git a/Entity/Watermark/AbstractWatermarkEntity.php b/Entity/Watermark/AbstractWatermarkEntity.php
index 15185f75..14443738 100644
--- a/Entity/Watermark/AbstractWatermarkEntity.php
+++ b/Entity/Watermark/AbstractWatermarkEntity.php
@@ -12,11 +12,11 @@
namespace Cmfcmf\Module\MediaModule\Entity\Watermark;
use Cmfcmf\Module\MediaModule\Font\FontCollection;
+use Cmfcmf\Module\MediaModule\Traits\StandardFieldsTrait;
use Doctrine\ORM\Mapping as ORM;
-use DoctrineExtensions\StandardFields\Mapping\Annotation as ZK;
-use Gedmo\Mapping\Annotation as Gedmo;
use Imagine\Image\ImageInterface;
use Imagine\Image\ImagineInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraints as Assert;
/**
@@ -33,6 +33,8 @@
*/
abstract class AbstractWatermarkEntity
{
+ use StandardFieldsTrait;
+
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
@@ -110,49 +112,27 @@ abstract class AbstractWatermarkEntity
protected $relativeSize;
/**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="create")
- *
- * No assertions.
- *
- * @var int.
+ * @var RequestStack
*/
- protected $createdUserId;
+ protected $requestStack;
/**
- * @ORM\Column(type="integer")
- * @ZK\StandardFields(type="userid", on="update")
- *
- * No assertions.
- *
- * @var int.
- */
- protected $updatedUserId;
-
- /**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="create")
- *
- * No assertions.
- *
- * @var \DateTime.
+ * @var string
*/
- protected $createdDate;
+ protected $dataDirectory;
/**
- * @ORM\Column(type="datetime")
- * @Gedmo\Timestampable(on="update")
- *
- * No assertions.
- *
- * @var \DateTime.
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
*/
- protected $updatedDate;
-
- public function __construct()
+ public function __construct(RequestStack $requestStack, $dataDirectory = '')
{
$this->minSizeX = 200;
$this->minSizeY = 80;
+
+ // TODO refactor these dependencies out of the entities
+ $this->requestStack = $requestStack;
+ $this->dataDirectory = $dataDirectory;
}
/**
@@ -277,86 +257,6 @@ public function setRelativeSize($relativeSize)
return $this;
}
- /**
- * @return int
- */
- public function getCreatedUserId()
- {
- return $this->createdUserId;
- }
-
- /**
- * @param int $createdUserId
- *
- * @return AbstractWatermarkEntity
- */
- public function setCreatedUserId($createdUserId)
- {
- $this->createdUserId = $createdUserId;
-
- return $this;
- }
-
- /**
- * @return int
- */
- public function getUpdatedUserId()
- {
- return $this->updatedUserId;
- }
-
- /**
- * @param int $updatedUserId
- *
- * @return AbstractWatermarkEntity
- */
- public function setUpdatedUserId($updatedUserId)
- {
- $this->updatedUserId = $updatedUserId;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getCreatedDate()
- {
- return $this->createdDate;
- }
-
- /**
- * @param \DateTime $createdDate
- *
- * @return AbstractWatermarkEntity
- */
- public function setCreatedDate($createdDate)
- {
- $this->createdDate = $createdDate;
-
- return $this;
- }
-
- /**
- * @return \DateTime
- */
- public function getUpdatedDate()
- {
- return $this->updatedDate;
- }
-
- /**
- * @param \DateTime $updatedDate
- *
- * @return AbstractWatermarkEntity
- */
- public function setUpdatedDate($updatedDate)
- {
- $this->updatedDate = $updatedDate;
-
- return $this;
- }
-
/**
* Get the value of Min Size.
*
@@ -424,4 +324,28 @@ public function getVersion()
{
return $this->version;
}
+
+ /**
+ * @param RequestStack $requestStack
+ *
+ * @return AbstractWatermarkEntity
+ */
+ public function setRequestStack(RequestStack $requestStack)
+ {
+ $this->requestStack = $requestStack;
+
+ return $this;
+ }
+
+ /**
+ * @param string $dataDirectory
+ *
+ * @return AbstractWatermarkEntity
+ */
+ public function setDataDirectory($dataDirectory)
+ {
+ $this->dataDirectory = $dataDirectory;
+
+ return $this;
+ }
}
diff --git a/Entity/Watermark/ImageWatermarkEntity.php b/Entity/Watermark/ImageWatermarkEntity.php
index 674de300..f4e5fa7c 100644
--- a/Entity/Watermark/ImageWatermarkEntity.php
+++ b/Entity/Watermark/ImageWatermarkEntity.php
@@ -15,6 +15,7 @@
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Uploadable\Uploadable;
+use Imagine\Image\Box;
use Imagine\Image\ImagineInterface;
/**
@@ -55,7 +56,7 @@ public function getImagineImage(
$height
) {
$watermarkImage = $imagine->open($this->getPath());
- if ($this->getRelativeSize() !== null) {
+ if (null !== $this->getRelativeSize()) {
$y = (int) $height * $this->getRelativeSize() / 100;
$factor = $y / $watermarkImage->getSize()->getHeight();
$x = $watermarkImage->getSize()->getWidth() * $factor;
@@ -65,7 +66,7 @@ public function getImagineImage(
$x = $actualWidth;
$y *= $factor;
}
- $watermarkImage->resize(new \Imagine\Image\Box($x, $y));
+ $watermarkImage->resize(new Box($x, $y));
}
return $watermarkImage;
@@ -75,7 +76,7 @@ public function getPathToUploadTo($defaultPath)
{
unset($defaultPath);
- return \FileUtil::getDataDirectory() . '/cmfcmf-media-module/watermarks';
+ return $this->dataDirectory . '/cmfcmf-media-module/watermarks';
}
public function getPath()
@@ -83,9 +84,14 @@ public function getPath()
return $this->getPathToUploadTo(null) . '/' . $this->fileName;
}
+ public function getFileName()
+ {
+ return $this->fileName;
+ }
+
public function getUrl()
{
- return \System::getBaseUri() . '/' . $this->getPath();
+ return $this->requestStack->getCurrentRequest()->getBasePath() . '/' . $this->getPath();
}
/**
@@ -97,7 +103,7 @@ public function getViewTableContent()
$title = htmlentities($this->title);
return <<
+
EOD;
}
}
diff --git a/Entity/Watermark/Repository/WatermarkRepository.php b/Entity/Watermark/Repository/WatermarkRepository.php
index 0ff911ca..594a445f 100644
--- a/Entity/Watermark/Repository/WatermarkRepository.php
+++ b/Entity/Watermark/Repository/WatermarkRepository.php
@@ -14,21 +14,20 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Watermark\AbstractWatermarkEntity;
use Doctrine\ORM\EntityRepository;
+use Liip\ImagineBundle\Imagine\Cache\CacheManager;
class WatermarkRepository extends EntityRepository
{
/**
* Removes all thumbnails generated for media with the given entity.
*
- * @param AbstractWatermarkEntity $entity
- * @param \SystemPlugin_Imagine_Manager $imagineManager
+ * @param AbstractWatermarkEntity $entity
+ * @param CacheManager $imagineCacheManager
*/
public function cleanupThumbs(
AbstractWatermarkEntity $entity,
- \SystemPlugin_Imagine_Manager $imagineManager
+ CacheManager $imagineCacheManager
) {
- $imagineManager->setModule('CmfcmfMediaModule');
-
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('m')
->from('CmfcmfMediaModule:Media\AbstractMediaEntity', 'm')
@@ -39,7 +38,7 @@ public function cleanupThumbs(
/** @var AbstractMediaEntity[] $media */
$media = $qb->getQuery()->execute();
foreach ($media as $medium) {
- $imagineManager->removeObjectThumbs($medium->getImagineId());
+ $imagineCacheManager->remove($medium->getPath(), ['thumbnail', 'cmfcmfmediamodule.custom_image_filter']);
}
}
}
diff --git a/Entity/Watermark/TextWatermarkEntity.php b/Entity/Watermark/TextWatermarkEntity.php
index 9fcbb388..dfda4303 100644
--- a/Entity/Watermark/TextWatermarkEntity.php
+++ b/Entity/Watermark/TextWatermarkEntity.php
@@ -16,6 +16,7 @@
use Imagine\Image\ImagineInterface;
use Imagine\Image\Palette\RGB;
use Imagine\Image\Point;
+use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraints as Assert;
/**
@@ -68,12 +69,16 @@ class TextWatermarkEntity extends AbstractWatermarkEntity
*/
protected $backgroundColor;
- public function __construct()
+ /**
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
+ */
+ public function __construct(RequestStack $requestStack, $dataDirectory = '')
{
- parent::__construct();
+ parent::__construct($requestStack, $dataDirectory);
- $this->fontColor = "#000000FF";
- $this->backgroundColor = "#00000000";
+ $this->fontColor = '#000000FF';
+ $this->backgroundColor = '#00000000';
}
/**
@@ -99,9 +104,9 @@ public function setText($text)
public function getImagineImage(ImagineInterface $imagine, FontCollection $fontCollection, $width, $height)
{
$fontPath = $fontCollection->getFontById($this->font)->getPath();
- if ($this->getAbsoluteSize() !== null) {
+ if (null !== $this->getAbsoluteSize()) {
$fontSize = $this->getAbsoluteSize();
- } elseif ($this->getRelativeSize() !== null) {
+ } elseif (null !== $this->getRelativeSize()) {
$fontSize = (int) $this->getRelativeSize() / 100 * $height;
} else {
throw new \LogicException('Either relative or absolute watermark size must be set!');
@@ -128,8 +133,8 @@ public function getImagineImage(ImagineInterface $imagine, FontCollection $fontC
*/
public function assertRelativeOrAbsoluteSizeSet()
{
- $r = $this->relativeSize !== null;
- $a = $this->absoluteSize !== null;
+ $r = null !== $this->relativeSize;
+ $a = null !== $this->absoluteSize;
return $r xor $a;
}
diff --git a/Font/FontCollection.php b/Font/FontCollection.php
index 901e8fce..7933ed25 100644
--- a/Font/FontCollection.php
+++ b/Font/FontCollection.php
@@ -27,7 +27,7 @@ class FontCollection
private $fonts;
/**
- * @var bool Whether or not the fonts have already been loaded.
+ * @var bool whether or not the fonts have already been loaded
*/
private $loaded;
@@ -76,15 +76,18 @@ public function getFontsForForm()
$this->load();
}
- return array_map(function (FontInterface $font) {
- return $font->getTitle();
- }, $this->getFonts());
+ $choices = [];
+ foreach ($this->getFonts() as $font) {
+ $choices[$font->getTitle()] = $font->getId();
+ }
+
+ return $choices;
}
/**
* Returns a font by id.
*
- * @param string $id The font id.
+ * @param string $id the font id
*
* @return FontInterface
*/
@@ -113,7 +116,7 @@ public function getFontUrl()
$fontUrl = 'https://fonts.googleapis.com/css?family=';
foreach ($this->getFonts() as $font) {
- if ($font->getGoogleFontName() !== null) {
+ if (null !== $font->getGoogleFontName()) {
$fontUrl .= str_replace('_', '+', $font->getGoogleFontName()) . '|';
}
}
diff --git a/Form/AbstractType.php b/Form/AbstractType.php
index 1ad4356a..cac3d298 100644
--- a/Form/AbstractType.php
+++ b/Form/AbstractType.php
@@ -12,6 +12,7 @@
namespace Cmfcmf\Module\MediaModule\Form;
use Symfony\Component\Form\AbstractType as BaseAbstractType;
+use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Translation\TranslatorInterface;
@@ -35,7 +36,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
- $builder->add('version', 'hidden');
+ $builder->add('version', HiddenType::class);
}
/**
@@ -55,7 +56,7 @@ public function setDefaultOptions(OptionsResolverInterface $resolver)
/**
* {@inheritdoc}
*/
- public function getName()
+ public function getBlockPrefix()
{
$class = get_class($this);
$class = substr($class, strlen('Cmfcmf\\Module\\MediaModule\\Form\\'));
diff --git a/Form/Collection/CollectionBlockType.php b/Form/Collection/CollectionBlockType.php
index 486746f8..48c28653 100644
--- a/Form/Collection/CollectionBlockType.php
+++ b/Form/Collection/CollectionBlockType.php
@@ -11,34 +11,61 @@
namespace Cmfcmf\Module\MediaModule\Form\Collection;
-use Cmfcmf\Module\MediaModule\CollectionTemplate\TemplateCollection;
+use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Repository\CollectionRepository;
+use Cmfcmf\Module\MediaModule\Form\CollectionTemplate\TemplateType;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
-use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
class CollectionBlockType extends AbstractType
{
+ /**
+ * @var TranslatorInterface
+ */
+ private $translator;
+
+ /**
+ * @var CollectionRepository
+ */
+ private $collectionRepository;
+
+ /**
+ * @var SecurityManager
+ */
+ private $securityManager;
+
+ /**
+ * @param TranslatorInterface $translator
+ * @param SecurityManager $securityManager
+ * @param EntityManagerInterface $em
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ SecurityManager $securityManager,
+ EntityManagerInterface $em
+ ) {
+ $this->translator = $translator;
+ $this->securityManager = $securityManager;
+ $this->collectionRepository = $em->getRepository('CmfcmfMediaModule:Collection\CollectionEntity');
+ }
+
public function buildForm(FormBuilderInterface $builder, array $options)
{
- /** @var TranslatorInterface $translator */
- $translator = $options['translator'];
- /** @var SecurityManager $securityManager */
- $securityManager = $options['securityManager'];
- /** @var TemplateCollection $templateCollection */
- $templateCollection = $options['templateCollection'];
- /** @var CollectionRepository $collectionRepository */
- $collectionRepository = $options['collectionRepository'];
+ $securityManager = $this->securityManager;
+ $collectionRepository = $this->collectionRepository;
$collectionOptions = [
'required' => true,
- 'label' => $translator->trans('Collection', [], 'cmfcmfmediamodule'),
- 'class' => 'CmfcmfMediaModule:Collection\CollectionEntity',
+ 'label' => $this->translator->trans('Collection', [], 'cmfcmfmediamodule'),
+ 'class' => CollectionEntity::class,
'query_builder' => function (EntityRepository $er) use ($securityManager) {
/** @var CollectionRepository $er */
$qb = $securityManager->getCollectionsWithAccessQueryBuilder(
@@ -49,29 +76,26 @@ public function buildForm(FormBuilderInterface $builder, array $options)
return $qb;
},
- 'placeholder' => $translator->trans('Select collection', [], 'cmfcmfmediamodule'),
- 'property' => 'indentedTitle',
+ 'placeholder' => $this->translator->trans('Select collection', [], 'cmfcmfmediamodule'),
+ 'choice_label' => 'indentedTitle',
'multiple' => false
];
$builder
- ->add('id', 'Symfony\Bridge\Doctrine\Form\Type\EntityType', $collectionOptions)
- ->add('showHooks', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', [
- 'label' => $translator->trans('Show hooks', [], 'cmfcmfmediamodule'),
+ ->add('id', EntityType::class, $collectionOptions)
+ ->add('showHooks', CheckboxType::class, [
+ 'label' => $this->translator->trans('Show hooks', [], 'cmfcmfmediamodule'),
'required' => false,
'disabled' => true
])
- ->add('template', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', [
- 'label' => $translator->trans('Template', [], 'cmfcmfmediamodule'),
- 'required' => false,
- 'placeholder' => $translator->trans('Default', [], 'cmfcmfmediamodule'),
- 'choices' => $templateCollection->getCollectionTemplateTitles()
+ ->add('template', TemplateType::class, [
+ 'label' => $this->translator->trans('Display', [], 'cmfcmfmediamodule'),
])
- ->add('showChildCollections', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', [
- 'label' => $translator->trans('Show child collections', [], 'cmfcmfmediamodule'),
+ ->add('showChildCollections', CheckboxType::class, [
+ 'label' => $this->translator->trans('Show child collections', [], 'cmfcmfmediamodule'),
'required' => false
])
- ->add('showEditAndDownloadLinks', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', [
- 'label' => $translator->trans('Show edit and download links', [], 'cmfcmfmediamodule'),
+ ->add('showEditAndDownloadLinks', CheckboxType::class, [
+ 'label' => $this->translator->trans('Show edit and download links', [], 'cmfcmfmediamodule'),
'required' => false
])
->addModelTransformer(new CallbackTransformer(
@@ -89,16 +113,8 @@ function ($data) {
;
}
- public function getName()
+ public function getBlockPrefix()
{
return 'cmfcmfmediamodule_collectionblock';
}
-
- /**
- * @param OptionsResolver $resolver
- */
- public function configureOptions(OptionsResolver $resolver)
- {
- $resolver->setRequired(['translator', 'securityManager', 'templateCollection', 'collectionRepository']);
- }
}
diff --git a/Form/Collection/CollectionType.php b/Form/Collection/CollectionType.php
index 7508af54..79ea9f6f 100644
--- a/Form/Collection/CollectionType.php
+++ b/Form/Collection/CollectionType.php
@@ -12,23 +12,29 @@
namespace Cmfcmf\Module\MediaModule\Form\Collection;
use Cmfcmf\Module\MediaModule\CollectionTemplate\TemplateCollection;
+use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionCategoryAssignmentEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Repository\CollectionRepository;
+use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\Repository\MediaRepository;
+use Cmfcmf\Module\MediaModule\Entity\Watermark\AbstractWatermarkEntity;
use Cmfcmf\Module\MediaModule\Form\AbstractType;
+use Cmfcmf\Module\MediaModule\Form\CollectionTemplate\TemplateType;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Parameter;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
+use Symfony\Component\Form\Extension\Core\Type\TextareaType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+use Symfony\Component\Translation\TranslatorInterface;
+use Zikula\CategoriesModule\Form\Type\CategoriesType;
+use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
class CollectionType extends AbstractType
{
- /**
- * @var CollectionEntity|null
- */
- private $parent;
-
/**
* @var TemplateCollection
*/
@@ -39,14 +45,27 @@ class CollectionType extends AbstractType
*/
private $securityManager;
+ /**
+ * @var VariableApiInterface
+ */
+ private $variableApi;
+
+ /**
+ * @param TranslatorInterface $translator
+ * @param TemplateCollection $templateCollection
+ * @param SecurityManager $securityManager
+ * @param VariableApiInterface $variableApi
+ */
public function __construct(
+ TranslatorInterface $translator,
TemplateCollection $templateCollection,
- CollectionEntity $parent = null,
- SecurityManager $securityManager
+ SecurityManager $securityManager,
+ VariableApiInterface $variableApi
) {
- $this->parent = $parent;
+ $this->translator = $translator;
$this->templateCollection = $templateCollection;
$this->securityManager = $securityManager;
+ $this->variableApi = $variableApi;
}
/**
@@ -56,9 +75,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
- $escapingStrategy = \ModUtil::getVar(
- 'CmfcmfMediaModule',
- 'descriptionEscapingStrategyForCollection');
+ $escapingStrategy = $this->variableApi->get('CmfcmfMediaModule', 'descriptionEscapingStrategyForCollection');
switch ($escapingStrategy) {
case 'raw':
$descriptionHelp = $this->translator->trans('You may use HTML.', [], 'cmfcmfmediamodule');
@@ -77,120 +94,119 @@ public function buildForm(FormBuilderInterface $builder, array $options)
$theCollection = $options['data'];
$securityManager = $this->securityManager;
- $builder
- ->add(
- 'title',
- 'text',
- [
- 'label' => $this->translator->trans('Title', [], 'cmfcmfmediamodule')
- ]);
- // If enabled, breaks slug generation of children when the slug is changed.
- //if (\ModUtil::getVar('CmfcmfMediaModule', 'slugEditable')) {
- // $builder
- // ->add('slug', 'text', [
- // 'label' => $this->translator->trans('Slug', [], 'cmfcmfmediamodule'),
- // 'required'=> false,
- // 'attr' => [
- // 'placeholder' => $this->translator->trans('Leave empty to autogenerate', [], 'cmfcmfmediamodule')
- // ]
- // ])
- // ;
- //}
+ $builder->add('title', TextType::class, [
+ 'label' => $this->translator->trans('Title', [], 'cmfcmfmediamodule')
+ ]);
+ /**
+ If enabled, breaks slug generation of children when the slug is changed.
+ if ($this->variableApi->get('CmfcmfMediaModule', 'slugEditable')) {
+ $builder->add('slug', TextType::class, [
+ 'label' => $this->translator->trans('Slug', [], 'cmfcmfmediamodule'),
+ 'required'=> false,
+ 'attr' => [
+ 'placeholder' => $this->translator->trans('Leave empty to autogenerate', [], 'cmfcmfmediamodule')
+ ]
+ ]);
+ }*/
$builder
- ->add(
- 'description',
- 'textarea',
- [
- 'label' => $this->translator->trans('Description', [], 'cmfcmfmediamodule'),
- 'required' => false,
- 'attr' => [
- 'help' => $descriptionHelp
- ]
- ])
- ->add('categoryAssignments', 'Zikula\CategoriesModule\Form\Type\CategoriesType', [
+ ->add('description', TextareaType::class, [
+ 'label' => $this->translator->trans('Description', [], 'cmfcmfmediamodule'),
+ 'required' => false,
+ 'attr' => [
+ 'help' => $descriptionHelp
+ ]
+ ])
+ ->add('categoryAssignments', CategoriesType::class, [
+ 'label' => $this->translator->trans('Categories', [], 'cmfcmfmediamodule'),
'required' => false,
'multiple' => true,
'module' => 'CmfcmfMediaModule',
'entity' => 'CollectionEntity',
- 'entityCategoryClass' => 'Cmfcmf\Module\MediaModule\Entity\Collection\CollectionCategoryAssignmentEntity',
+ 'entityCategoryClass' => CollectionCategoryAssignmentEntity::class,
+ ])
+ ->add('defaultTemplate', TemplateType::class, [
+ 'label' => $this->translator->trans('Display', [], 'cmfcmfmediamodule'),
])
- ->add('defaultTemplate', 'cmfcmfmediamodule_collectiontemplate')
- ->add(
- 'parent',
- 'entity',
- [
- 'class' => 'Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity',
- 'required' => false,
- 'label' => $this->translator->trans('Parent', [], 'cmfcmfmediamodule'),
- 'placeholder' => $this->translator->trans('No parent', [], 'cmfcmfmediamodule'),
- 'query_builder' => function (EntityRepository $er) use (
- $theCollection,
- $securityManager
- ) {
- /** @var CollectionRepository $er */
- $qb = $securityManager->getCollectionsWithAccessQueryBuilder(
- CollectionPermissionSecurityTree::PERM_LEVEL_ADD_SUB_COLLECTIONS
- );
- $qb->orderBy('c.root', 'ASC')
- ->addOrderBy('c.lft', 'ASC');
- if ($theCollection->getId() != null) {
- // The collection is currently edited. Make sure it's not placed into
- // itself or one of it's children.
- $childrenQuery = $er->getChildrenQuery($theCollection);
- $qb
- ->andWhere(
- $qb->expr()->notIn(
- 'c.id',
- $childrenQuery->getDQL()
- )
+ ->add('parent', EntityType::class, [
+ 'class' => CollectionEntity::class,
+ 'required' => false,
+ 'label' => $this->translator->trans('Parent', [], 'cmfcmfmediamodule'),
+ 'placeholder' => $this->translator->trans('No parent', [], 'cmfcmfmediamodule'),
+ 'query_builder' => function (EntityRepository $er) use (
+ $theCollection,
+ $securityManager
+ ) {
+ /** @var CollectionRepository $er */
+ $qb = $securityManager->getCollectionsWithAccessQueryBuilder(
+ CollectionPermissionSecurityTree::PERM_LEVEL_ADD_SUB_COLLECTIONS
+ );
+ $qb->orderBy('c.root', 'ASC')
+ ->addOrderBy('c.lft', 'ASC');
+ if (null != $theCollection->getId()) {
+ // The collection is currently edited. Make sure it's not placed into
+ // itself or one of it's children.
+ $childrenQuery = $er->getChildrenQuery($theCollection);
+ $qb
+ ->andWhere(
+ $qb->expr()->notIn(
+ 'c.id',
+ $childrenQuery->getDQL()
)
- ->andWhere($qb->expr()->neq('c.id', ':id'))
- ->setParameter('id', $theCollection->getId())
- ;
- $childrenQuery->getParameters()->forAll(function ($key, Parameter $parameter) use ($qb) {
- $qb->setParameter($parameter->getName(), $parameter->getValue());
- });
- }
+ )
+ ->andWhere($qb->expr()->neq('c.id', ':id'))
+ ->setParameter('id', $theCollection->getId())
+ ;
+ $childrenQuery->getParameters()->forAll(function ($key, Parameter $parameter) use ($qb) {
+ $qb->setParameter($parameter->getName(), $parameter->getValue());
+ });
+ }
- return $qb;
- },
- 'data' => $this->parent,
- 'property' => 'indentedTitle',
- ])
- ->add(
- 'watermark',
- 'entity',
- [
- 'class' => 'CmfcmfMediaModule:Watermark\AbstractWatermarkEntity',
- 'required' => false,
- 'label' => $this->translator->trans('Watermark', [], 'cmfcmfmediamodule'),
- 'data' => $theCollection->getId() !== null ? $theCollection->getWatermark() :
- (isset($this->parent) ? $this->parent->getWatermark() : null),
- 'placeholder' => $this->translator->trans('No watermark', [], 'cmfcmfmediamodule'),
- 'property' => 'title',
- ])
- ->add(
- 'primaryMedium',
- 'entity',
- [
- 'class' => 'CmfcmfMediaModule:Media\AbstractMediaEntity',
- 'required' => false,
- 'label' => $this->translator->trans('Primary medium', [], 'cmfcmfmediamodule'),
- 'placeholder' => $this->translator->trans('First medium of collection', [], 'cmfcmfmediamodule'),
- 'disabled' => $theCollection->getId() == null,
- 'property' => 'title',
- 'query_builder' => function (EntityRepository $er) use ($theCollection) {
- /** @var MediaRepository $er */
- $qb = $er->createQueryBuilder('m');
- $qb->where($qb->expr()->eq('m.collection', ':collection'))
- ->setParameter('collection', $theCollection->getId());
+ return $qb;
+ },
+ 'data' => $options['parent'],
+ 'choice_label' => 'indentedTitle',
+ ])
+ ->add('watermark', EntityType::class, [
+ 'class' => AbstractWatermarkEntity::class,
+ 'required' => false,
+ 'label' => $this->translator->trans('Watermark', [], 'cmfcmfmediamodule'),
+ 'data' => null !== $theCollection->getId() ? $theCollection->getWatermark() :
+ (isset($options['parent']) ? $options['parent']->getWatermark() : null),
+ 'placeholder' => $this->translator->trans('No watermark', [], 'cmfcmfmediamodule'),
+ 'choice_label' => 'title',
+ ])
+ ->add('primaryMedium', EntityType::class, [
+ 'class' => AbstractMediaEntity::class,
+ 'required' => false,
+ 'label' => $this->translator->trans('Primary medium', [], 'cmfcmfmediamodule'),
+ 'placeholder' => $this->translator->trans('First medium of collection', [], 'cmfcmfmediamodule'),
+ 'disabled' => null === $theCollection->getId(),
+ 'choice_label' => 'title',
+ 'query_builder' => function (EntityRepository $er) use ($theCollection) {
+ /** @var MediaRepository $er */
+ $qb = $er->createQueryBuilder('m');
+ $qb->where($qb->expr()->eq('m.collection', ':collection'))
+ ->setParameter('collection', $theCollection->getId());
+
+ return $qb;
+ },
+ 'attr' => [
+ 'help' => $this->translator->trans('The primary medium is used as collection thumbnail. It must be part of the collection.', [], 'cmfcmfmediamodule')
+ ]
+ ])
+ ;
+ }
- return $qb;
- },
- 'attr' => [
- 'help' => $this->translator->trans('The primary medium is used as collection thumbnail. It must be part of the collection.', [], 'cmfcmfmediamodule')
- ]
- ]);
+ /**
+ * {@inheritdoc}
+ */
+ public function configureOptions(OptionsResolver $resolver)
+ {
+ $resolver
+ ->setDefaults([
+ 'parent' => null
+ ])
+ ;
}
}
diff --git a/Form/Collection/Permission/AbstractPermissionType.php b/Form/Collection/Permission/AbstractPermissionType.php
index 7413c2da..8ee36619 100644
--- a/Form/Collection/Permission/AbstractPermissionType.php
+++ b/Form/Collection/Permission/AbstractPermissionType.php
@@ -11,37 +11,52 @@
namespace Cmfcmf\Module\MediaModule\Form\Collection\Permission;
-use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Form\AbstractType;
+use Cmfcmf\Module\MediaModule\Form\Type\PermissionLevelType;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
+use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+use Symfony\Component\Translation\TranslatorInterface;
+use Zikula\GroupsModule\Entity\RepositoryInterface\GroupRepositoryInterface;
+use Zikula\UsersModule\Entity\RepositoryInterface\UserRepositoryInterface;
abstract class AbstractPermissionType extends AbstractType
{
/**
* @var SecurityManager
*/
- private $securityManager;
+ protected $securityManager;
/**
- * @var CollectionEntity
+ * @var GroupRepositoryInterface
*/
- private $collectionEntity;
+ protected $groupRepository;
/**
- * @var
+ * @var UserRepositoryInterface
*/
- private $permissionLevel;
+ protected $userRepository;
+ /**
+ * @param TranslatorInterface $translator
+ * @param SecurityManager $securityManager
+ * @param GroupRepositoryInterface $groupRepository
+ * @param UserRepositoryInterface $userRepository
+ */
public function __construct(
- CollectionEntity $collectionEntity,
+ TranslatorInterface $translator,
SecurityManager $securityManager,
- $permissionLevel
+ GroupRepositoryInterface $groupRepository,
+ UserRepositoryInterface $userRepository
) {
+ $this->translator = $translator;
$this->securityManager = $securityManager;
- $this->collectionEntity = $collectionEntity;
- $this->permissionLevel = $permissionLevel;
+ $this->groupRepository = $groupRepository;
+ $this->userRepository = $userRepository;
}
/**
@@ -51,16 +66,12 @@ public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
- $builder->add(
- 'permissionLevels',
- 'cmfcmfmediamodule_permission',
- [
+ $builder
+ ->add('permissionLevels', PermissionLevelType::class, [
'label' => $this->translator->trans('Permission level', [], 'cmfcmfmediamodule'),
- 'permissionLevel' => $this->permissionLevel
- ])->add(
- 'description',
- 'textarea',
- [
+ 'permissionLevel' => $options['permissionLevel']
+ ])
+ ->add('description', TextareaType::class, [
'label' => $this->translator->trans('Description', [], 'cmfcmfmediamodule'),
'required' => false,
'attr' => [
@@ -69,49 +80,34 @@ public function buildForm(FormBuilderInterface $builder, array $options)
[],
'cmfcmfmediamodule')
]
- ])->add(
- 'appliedToSelf',
- 'checkbox',
- [
+ ])
+ ->add('appliedToSelf', CheckboxType::class, [
'label' => $this->translator->trans('Applies to the collection itself', [], 'cmfcmfmediamodule'),
'required' => false
- ])->add(
- 'appliedToSubCollections',
- 'checkbox',
- [
+ ])
+ ->add('appliedToSubCollections', CheckboxType::class, [
'label' => $this->translator->trans('Applies to sub-collections', [], 'cmfcmfmediamodule'),
'required' => false
- ]);
+ ])
+ ;
- if ($this->securityManager->hasPermission(
- $this->collectionEntity,
- CollectionPermissionSecurityTree::PERM_LEVEL_CHANGE_PERMISSIONS)
- ) {
- $builder->add(
- 'goOn',
- 'checkbox',
- [
- 'label' => $this->translator->trans('Go on if this permission is not sufficient', [], 'cmfcmfmediamodule'),
- 'required' => false
- ]);
+ if ($this->securityManager->hasPermission($options['collection'], CollectionPermissionSecurityTree::PERM_LEVEL_CHANGE_PERMISSIONS)) {
+ $builder->add('goOn', CheckboxType::class, [
+ 'label' => $this->translator->trans('Go on if this permission is not sufficient', [], 'cmfcmfmediamodule'),
+ 'required' => false
+ ]);
} else {
- $builder->add(
- 'goOn',
- 'checkbox',
- [
- 'label' => $this->translator->trans('Go on if this permission is not sufficient', [], 'cmfcmfmediamodule'),
- 'required' => true,
- 'data' => true,
- 'attr' => [
- 'disabled' => true
- ],
- ]);
+ $builder->add('goOn', CheckboxType::class, [
+ 'label' => $this->translator->trans('Go on if this permission is not sufficient', [], 'cmfcmfmediamodule'),
+ 'data' => true,
+ 'attr' => [
+ 'disabled' => true
+ ],
+ ]);
}
- $builder->add(
- 'validAfter',
- 'datetime',
- [
+ $builder
+ ->add('validAfter', DateTimeType::class, [
'label' => $this->translator->trans('Valid after', [], 'cmfcmfmediamodule'),
'widget' => 'choice',
'required' => false,
@@ -121,10 +117,8 @@ public function buildForm(FormBuilderInterface $builder, array $options)
[],
'cmfcmfmediamodule')
]
- ])->add(
- 'validUntil',
- 'datetime',
- [
+ ])
+ ->add('validUntil', DateTimeType::class, [
'label' => $this->translator->trans('Valid until', [], 'cmfcmfmediamodule'),
'widget' => 'choice',
'required' => false,
@@ -134,6 +128,20 @@ public function buildForm(FormBuilderInterface $builder, array $options)
[],
'cmfcmfmediamodule')
]
- ]);
+ ])
+ ;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function configureOptions(OptionsResolver $resolver)
+ {
+ $resolver
+ ->setDefaults([
+ 'collection' => null,
+ 'permissionLevel' => null
+ ])
+ ;
}
}
diff --git a/Form/Collection/Permission/GroupPermissionType.php b/Form/Collection/Permission/GroupPermissionType.php
index 1cf0c1ab..8b323161 100644
--- a/Form/Collection/Permission/GroupPermissionType.php
+++ b/Form/Collection/Permission/GroupPermissionType.php
@@ -11,8 +11,8 @@
namespace Cmfcmf\Module\MediaModule\Form\Collection\Permission;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
-use Zikula\GroupsModule\Entity\GroupEntity;
class GroupPermissionType extends AbstractPermissionType
{
@@ -21,20 +21,16 @@ class GroupPermissionType extends AbstractPermissionType
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
- /** @var GroupEntity[]|false $groups */
- $groups = \ModUtil::apiFunc('ZikulaGroupsModule', 'user', 'getall');
- if ($groups === false) {
- $groups = [];
- }
+ $groupNames = $this->groupRepository->getGroupNamesById();
$choices = [];
- $choices[-1] = $this->translator->trans('All groups', [], 'cmfcmfmediamodule');
+ $choices[$this->translator->trans('All groups', [], 'cmfcmfmediamodule')] = -1;
- foreach ($groups as $group) {
- $choices[$group->getGid()] = $group->getName();
+ foreach ($groupNames as $groupId => $groupName) {
+ $choices[$groupName] = $groupId;
}
- $builder->add('groupIds', 'choice', [
+ $builder->add('groupIds', ChoiceType::class, [
'label' => $this->translator->trans('Groups', [], 'cmfcmfmediamodule'),
'multiple' => true,
'choices' => $choices
diff --git a/Form/Collection/Permission/PasswordPermissionType.php b/Form/Collection/Permission/PasswordPermissionType.php
index de842be7..f99eba74 100644
--- a/Form/Collection/Permission/PasswordPermissionType.php
+++ b/Form/Collection/Permission/PasswordPermissionType.php
@@ -11,6 +11,7 @@
namespace Cmfcmf\Module\MediaModule\Form\Collection\Permission;
+use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
class PasswordPermissionType extends AbstractPermissionType
@@ -20,7 +21,7 @@ class PasswordPermissionType extends AbstractPermissionType
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder->add('password', 'password', [
+ $builder->add('password', PasswordType::class, [
'label' => $this->translator->trans('Password', [], 'cmfcmfmediamodule'),
]);
diff --git a/Form/Collection/Permission/UserPermissionType.php b/Form/Collection/Permission/UserPermissionType.php
index a68727c4..46e62cce 100644
--- a/Form/Collection/Permission/UserPermissionType.php
+++ b/Form/Collection/Permission/UserPermissionType.php
@@ -11,6 +11,7 @@
namespace Cmfcmf\Module\MediaModule\Form\Collection\Permission;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
class UserPermissionType extends AbstractPermissionType
@@ -20,12 +21,13 @@ class UserPermissionType extends AbstractPermissionType
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
- $users = \UserUtil::getAll();
- $choices = array_map(function ($user) {
- return $user['uname'];
- }, $users);
+ $users = $this->userRepository->findAll();
+ $choices = [];
+ foreach ($users as $user) {
+ $choices[$user['uname']] = $user['uid'];
+ }
- $builder->add('userIds', 'choice', [
+ $builder->add('userIds', ChoiceType::class, [
'label' => $this->translator->trans('Users', [], 'cmfcmfmediamodule'),
'multiple' => true,
'choices' => $choices
diff --git a/Form/CollectionTemplate/GalleriaType.php b/Form/CollectionTemplate/GalleriaType.php
index c4cb8611..8e3bc1ab 100644
--- a/Form/CollectionTemplate/GalleriaType.php
+++ b/Form/CollectionTemplate/GalleriaType.php
@@ -12,15 +12,30 @@
namespace Cmfcmf\Module\MediaModule\Form\CollectionTemplate;
use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\Translation\TranslatorInterface;
class GalleriaType extends AbstractType
{
+ /**
+ * @var TranslatorInterface
+ */
+ private $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(
+ TranslatorInterface $translator
+ ) {
+ $this->translator = $translator;
+ }
+
public function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder->add('height', 'Symfony\Component\Form\Extension\Core\Type\NumberType', [
- 'label' => 'Slider height',
- 'required' => true
+ $builder->add('height', NumberType::class, [
+ 'label' => $this->translator->trans('Slider height', [], 'cmfcmfmediamodule')
]);
}
}
diff --git a/Form/CollectionTemplate/LightGalleryType.php b/Form/CollectionTemplate/LightGalleryType.php
index 5495d2ca..85153c37 100644
--- a/Form/CollectionTemplate/LightGalleryType.php
+++ b/Form/CollectionTemplate/LightGalleryType.php
@@ -12,30 +12,49 @@
namespace Cmfcmf\Module\MediaModule\Form\CollectionTemplate;
use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
+use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\Translation\TranslatorInterface;
class LightGalleryType extends AbstractType
{
+ /**
+ * @var TranslatorInterface
+ */
+ private $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(
+ TranslatorInterface $translator
+ ) {
+ $this->translator = $translator;
+ }
+
public function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder->add('thumbWidth', 'Symfony\Component\Form\Extension\Core\Type\NumberType', [
- 'label' => 'Thumbnail width',
- 'required' => true
- ])->add('thumbHeight', 'Symfony\Component\Form\Extension\Core\Type\NumberType', [
- 'label' => 'Thumbnail height',
- 'required' => true
- ])->add('thumbMode', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', [
- 'label' => 'Thumbnail mode',
- 'required' => true,
+ $builder->add('thumbWidth', NumberType::class, [
+ 'label' => $this->translator->trans('Thumbnail width', [], 'cmfcmfmediamodule')
+ ])
+ ->add('thumbHeight', NumberType::class, [
+ 'label' => $this->translator->trans('Thumbnail height', [], 'cmfcmfmediamodule')
+ ])
+ ->add('thumbMode', ChoiceType::class, [
+ 'label' => $this->translator->trans('Thumbnail mode', [], 'cmfcmfmediamodule'),
'choices' => [
- 'inset' => 'inset',
- 'outbound' => 'outbound'
+ $this->translator->trans('inset', [], 'cmfcmfmediamodule') => 'inset',
+ $this->translator->trans('outbound', [], 'cmfcmfmediamodule') => 'outbound'
],
- ])->add('showTitleBelowThumbs', 'checkbox', [
- 'label' => 'Show the image titles below thumbnails.',
+ ])
+ ->add('showTitleBelowThumbs', CheckboxType::class, [
+ 'label' => $this->translator->trans('Show the image titles below thumbnails.', [], 'cmfcmfmediamodule'),
'required' => false
- ])->add('showAttributionBelowThumbs', 'checkbox', [
- 'label' => 'Show the image attributions below thumbnails.',
+ ])
+ ->add('showAttributionBelowThumbs', CheckboxType::class, [
+ 'label' => $this->translator->trans('Show the image attributions below thumbnails.', [], 'cmfcmfmediamodule'),
'required' => false
]);
}
diff --git a/Form/CollectionTemplate/TemplateType.php b/Form/CollectionTemplate/TemplateType.php
index bac9e6b4..e8eee3f2 100644
--- a/Form/CollectionTemplate/TemplateType.php
+++ b/Form/CollectionTemplate/TemplateType.php
@@ -16,6 +16,8 @@
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
+use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
@@ -44,8 +46,16 @@ public static function getSubscribedEvents()
*/
private $selectedTemplateFactory;
- public function __construct(TranslatorInterface $translator, TemplateCollection $templateCollection, SelectedTemplateFactory $selectedTemplateFactory)
- {
+ /**
+ * @param TranslatorInterface $translator
+ * @param TemplateCollection $templateCollection
+ * @param SelectedTemplateFactory $selectedTemplateFactory
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ TemplateCollection $templateCollection,
+ SelectedTemplateFactory $selectedTemplateFactory
+ ) {
$this->translator = $translator;
$this->templateCollection = $templateCollection;
$this->selectedTemplateFactory = $selectedTemplateFactory;
@@ -55,57 +65,64 @@ public function buildForm(FormBuilderInterface $builder, array $options)
{
$selectedTemplateFactory = $this->selectedTemplateFactory;
- $builder->add('template', 'choice', [
- 'label' => $this->translator->trans('Template', [], 'cmfcmfmediamodule'),
- 'required' => !$options['allowDefaultTemplate'],
- 'placeholder' => $options['allowDefaultTemplate'] ? $this->translator->trans('Default', [], 'cmfcmfmediamodule') : false,
- 'choices' => $this->templateCollection->getCollectionTemplateTitles()
- ])->add('options', 'form', [
- 'required' => false
- ])->addModelTransformer(new CallbackTransformer(function ($modelData) use ($selectedTemplateFactory) {
- if ($modelData === null) {
- return [
- 'template' => null,
- 'options' => []
- ];
- }
- $selectedTemplate = $selectedTemplateFactory->fromDB($modelData);
-
- return [
- 'template' => $selectedTemplate->getTemplate()->getName(),
- 'options' => $selectedTemplate->getOptions()
- ];
- }, function ($viewData) use ($selectedTemplateFactory) {
- if (null === $viewData['template']) {
- return null;
- }
-
- return $selectedTemplateFactory->fromTemplateName($viewData['template'], (array) $viewData['options'])->toDB();
- }))->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
- $form = $event->getForm();
- $data = $event->getData();
-
- if (null === $data) {
- $form->add('options', 'form', [
- 'required' => false
- ]);
-
- return;
- }
-
- $selectedTemplate = $this->selectedTemplateFactory->fromDB($data);
-
- $settingsForm = $selectedTemplate->getTemplate()->getSettingsForm();
- if (null !== $settingsForm) {
- $form->add('options', $settingsForm);
- }
- });
+ $builder
+ ->add('template', ChoiceType::class, [
+ 'label' => $this->translator->trans('Template', [], 'cmfcmfmediamodule'),
+ 'required' => !$options['allowDefaultTemplate'],
+ 'placeholder' => $options['allowDefaultTemplate'] ? $this->translator->trans('Default', [], 'cmfcmfmediamodule') : false,
+ 'choices' => $this->templateCollection->getCollectionTemplateTitles()
+ ])
+ ->add('options', FormType::class, [
+ 'required' => false
+ ])
+ ->addModelTransformer(
+ new CallbackTransformer(function ($modelData) use ($selectedTemplateFactory) {
+ if (null === $modelData) {
+ return [
+ 'template' => null,
+ 'options' => []
+ ];
+ }
+ $selectedTemplate = $selectedTemplateFactory->fromDB($modelData);
+
+ return [
+ 'template' => $selectedTemplate->getTemplate()->getName(),
+ 'options' => $selectedTemplate->getOptions()
+ ];
+ }, function ($viewData) use ($selectedTemplateFactory) {
+ if (null === $viewData['template']) {
+ return null;
+ }
+
+ return $selectedTemplateFactory->fromTemplateName($viewData['template'], (array) $viewData['options'])->toDB();
+ })
+ )
+ ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
+ $form = $event->getForm();
+ $data = $event->getData();
+
+ if (null === $data) {
+ $form->add('options', FormType::class, [
+ 'required' => false
+ ]);
+
+ return;
+ }
+
+ $selectedTemplate = $this->selectedTemplateFactory->fromDB($data);
+
+ $settingsForm = $selectedTemplate->getTemplate()->getSettingsForm();
+ if (null !== $settingsForm) {
+ $form->add('options', $settingsForm);
+ }
+ })
+ ;
$builder->get('template')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
$template = $form->getData();
if (null === $template) {
- $form->getParent()->add('options', 'form', [
+ $form->getParent()->add('options', FormType::class, [
'required' => false
]);
@@ -116,7 +133,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
if (null !== $settingsForm) {
$form->getParent()->add('options', $settingsForm);
} else {
- $form->getParent()->add('options', 'form', [
+ $form->getParent()->add('options', FormType::class, [
'required' => false
]);
}
@@ -128,8 +145,8 @@ public function configureOptions(OptionsResolver $resolver)
$resolver->setDefault('allowDefaultTemplate', true);
}
- public function getName()
+ public function getBlockPrefix()
{
- return "cmfcmfmediamodule_collectiontemplate";
+ return 'cmfcmfmediamodule_collectiontemplate';
}
}
diff --git a/Form/ImportType.php b/Form/ImportType.php
index 41c89956..4d0d1408 100644
--- a/Form/ImportType.php
+++ b/Form/ImportType.php
@@ -16,18 +16,15 @@
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
use Doctrine\ORM\EntityRepository;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType as SymfonyAbstractType;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
-use Symfony\Component\Form\FormTypeInterface;
+use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
class ImportType extends SymfonyAbstractType
{
- /**
- * @var FormTypeInterface
- */
- private $importerForm;
-
/**
* @var TranslatorInterface
*/
@@ -38,44 +35,61 @@ class ImportType extends SymfonyAbstractType
*/
private $securityManager;
- public function __construct(FormTypeInterface $importerForm, TranslatorInterface $translator, SecurityManager $securityManager)
- {
- $this->importerForm = $importerForm;
+ /**
+ * @param TranslatorInterface $translator
+ * @param SecurityManager $securityManager
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ SecurityManager $securityManager
+ ) {
$this->translator = $translator;
$this->securityManager = $securityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder
- ->add('collection', 'entity', [
- 'required' => true,
- 'class' => 'CmfcmfMediaModule:Collection\CollectionEntity',
- 'query_builder' => function (EntityRepository $er) {
- /** @var CollectionRepository $qb */
- $qb = $this->securityManager->getCollectionsWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_ADD_SUB_COLLECTIONS);
- $qb
- ->orderBy('c.root', 'ASC')
- ->addOrderBy('c.lft', 'ASC')
- ->andWhere($qb->expr()->not($qb->expr()->eq('c.id', ':uploadCollectionId')))
- ->setParameter('uploadCollectionId', CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID);
+ $builder->add('collection', EntityType::class, [
+ 'required' => true,
+ 'class' => CollectionEntity::class,
+ 'query_builder' => function (EntityRepository $er) {
+ /** @var CollectionRepository $qb */
+ $qb = $this->securityManager->getCollectionsWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_ADD_SUB_COLLECTIONS);
+ $qb
+ ->orderBy('c.root', 'ASC')
+ ->addOrderBy('c.lft', 'ASC')
+ ->andWhere($qb->expr()->not($qb->expr()->eq('c.id', ':uploadCollectionId')))
+ ->setParameter('uploadCollectionId', CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID);
- return $qb;
- },
- 'placeholder' => $this->translator->trans('Select collection', [], 'cmfcmfmediamodule'),
- 'property' => 'indentedTitle',
- ])
- ->add('importSettings', $this->importerForm)
- ->add('import', 'submit', [
- 'attr' => [
- 'class' => 'btn-success'
- ]
- ])
- ;
+ return $qb;
+ },
+ 'placeholder' => $this->translator->trans('Select collection', [], 'cmfcmfmediamodule'),
+ 'choice_label' => 'indentedTitle',
+ ]);
+ if (null !== $options['importerForm']) {
+ $builder->add('importSettings', $options['importerForm']);
+ }
+ $builder->add('import', SubmitType::class, [
+ 'attr' => [
+ 'class' => 'btn-success'
+ ]
+ ]);
+ }
+
+ public function getBlockPrefix()
+ {
+ return 'cmfcmfmediamodule_importtype';
}
- public function getName()
+ /**
+ * {@inheritdoc}
+ */
+ public function configureOptions(OptionsResolver $resolver)
{
- return 'cmfcmfmediamodule_settingstype';
+ $resolver
+ ->setDefaults([
+ 'importerForm' => null
+ ])
+ ;
}
}
diff --git a/Form/Importer/AbstractImporterType.php b/Form/Importer/AbstractImporterType.php
index 6312bc8b..e6867ad1 100644
--- a/Form/Importer/AbstractImporterType.php
+++ b/Form/Importer/AbstractImporterType.php
@@ -29,7 +29,7 @@ public function __construct(TranslatorInterface $translator)
$this->translator = $translator;
}
- public function getName()
+ public function getBlockPrefix()
{
$type = get_class($this);
$type = substr($type, strrpos($type, '\\') + 1, -strlen('Type'));
diff --git a/Form/Importer/ServerDirectoryType.php b/Form/Importer/ServerDirectoryType.php
index b8b000e9..445fa58c 100644
--- a/Form/Importer/ServerDirectoryType.php
+++ b/Form/Importer/ServerDirectoryType.php
@@ -11,6 +11,8 @@
namespace Cmfcmf\Module\MediaModule\Form\Importer;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class ServerDirectoryType extends AbstractImporterType
@@ -18,18 +20,18 @@ class ServerDirectoryType extends AbstractImporterType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
- ->add('serverDirectory', 'text', [
+ ->add('serverDirectory', TextType::class, [
'required' => true,
'label' => $this->translator->trans('Server directory', [], 'cmfcmfmediamodule'),
'attr' => [
'help' => $this->translator->trans('Either provide an absolute path or a path relative to the Zikula root directory.', [], 'cmfcmfmediamodule')
]
])
- ->add('includeSubDirectories', 'checkbox', [
+ ->add('includeSubDirectories', CheckboxType::class, [
'required' => false,
'label' => $this->translator->trans('Include sub directories', [], 'cmfcmfmediamodule')
])
- ->add('createSubCollectionsForSubDirectories', 'checkbox', [
+ ->add('createSubCollectionsForSubDirectories', CheckboxType::class, [
'required' => false,
'label' => $this->translator->trans('Create sub collections for sub directories', [], 'cmfcmfmediamodule')
])
diff --git a/Form/License/LicenseType.php b/Form/License/LicenseType.php
index 5ba29310..caca62b4 100644
--- a/Form/License/LicenseType.php
+++ b/Form/License/LicenseType.php
@@ -12,21 +12,22 @@
namespace Cmfcmf\Module\MediaModule\Form\License;
use Cmfcmf\Module\MediaModule\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;
+use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+use Symfony\Component\Translation\TranslatorInterface;
class LicenseType extends AbstractType
{
/**
- * @var bool
+ * @param TranslatorInterface $translator
*/
- private $isEdit;
-
- /**
- * @param bool $isEdit Whether or not the license is currenlty edited.
- */
- public function __construct($isEdit)
+ public function __construct(TranslatorInterface $translator)
{
- $this->isEdit = $isEdit;
+ $this->translator = $translator;
}
/**
@@ -37,59 +38,70 @@ public function buildForm(FormBuilderInterface $builder, array $options)
parent::buildForm($builder, $options);
$builder
- ->add('id', 'text', [
- 'required' => true,
- 'disabled' => $this->isEdit,
+ ->add('id', TextType::class, [
+ 'disabled' => $options['isEdit'],
'label' => $this->translator->trans('License ID', [], 'cmfcmfmediamodule'),
'attr' => [
'help' => $this->translator->trans('You won\'t be able to change the ID after creation. It should be something like "gplv3" or similar.', [], 'cmfcmfmediamodule')
]
])
- ->add('title', 'text', [
+ ->add('title', TextType::class, [
'label' => $this->translator->trans('Title', [], 'cmfcmfmediamodule'),
- 'required' => true,
'attr' => [
'help' => $this->translator->trans('The title of the license to use for displaying it.', [], 'cmfcmfmediamodule')
]
])
- ->add('url', 'url', [
+ ->add('url', UrlType::class, [
'label' => $this->translator->trans('Url', [], 'cmfcmfmediamodule'),
'required' => false,
'attr' => [
'help' => $this->translator->trans('The place where you can look up the license text.', [], 'cmfcmfmediamodule')
]
])
- ->add('imageUrl', 'url', [
+ ->add('imageUrl', UrlType::class, [
'label' => $this->translator->trans('Image Url', [], 'cmfcmfmediamodule'),
'required' => false,
'attr' => [
'help' => $this->translator->trans('Optional url of a small license icon.', [], 'cmfcmfmediamodule')
]
])
- ->add('outdated', 'checkbox', [
+ ->add('outdated', CheckboxType::class, [
'label' => $this->translator->trans('Outdated', [], 'cmfcmfmediamodule'),
'required' => false,
'attr' => [
'help' => $this->translator->trans('Marks a license as outdated to give a visual hint while uploading.', [], 'cmfcmfmediamodule')
]
])
- ->add('enabledForUpload', 'checkbox', [
+ ->add('enabledForUpload', CheckboxType::class, [
'label' => $this->translator->trans('Allow to use for uploads', [], 'cmfcmfmediamodule'),
'required' => false,
'attr' => [
'help' => $this->translator->trans('If you check this box, you will be able to upload media and license it under this license.', [], 'cmfcmfmediamodule')
]
])
- ->add('enabledForWeb', 'checkbox', [
+ ->add('enabledForWeb', CheckboxType::class, [
'label' => $this->translator->trans('Allow to use for web embeds', [], 'cmfcmfmediamodule'),
'required' => false,
'attr' => [
'help' => $this->translator->trans('If you check this box, you will be able to embed media from the web using this license.', [], 'cmfcmfmediamodule')
]
])
- ->add('submit', 'submit', [
+ ->add('submit', SubmitType::class, [
'label' => $this->translator->trans('Save', [], 'cmfcmfmediamodule')
])
;
}
+
+ /**
+ * {@inheritdoc}
+ */
+ public function configureOptions(OptionsResolver $resolver)
+ {
+ $resolver
+ ->setDefaults([
+ 'isEdit' => false
+ ])
+ ->setAllowedTypes('isEdit', 'bool')
+ ;
+ }
}
diff --git a/Form/Media/AbstractFileType.php b/Form/Media/AbstractFileType.php
index 12dc7c13..4fdf8c96 100644
--- a/Form/Media/AbstractFileType.php
+++ b/Form/Media/AbstractFileType.php
@@ -11,6 +11,8 @@
namespace Cmfcmf\Module\MediaModule\Form\Media;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
class AbstractFileType extends AbstractMediaEntityType
@@ -23,12 +25,12 @@ public function buildForm(FormBuilderInterface $builder, array $options)
parent::buildForm($builder, $options);
$builder
- ->add('file', 'file', [
+ ->add('file', FileType::class, [
'label' => $this->translator->trans('Change file', [], 'cmfcmfmediamodule'),
'mapped' => false,
'required' => false
])
- ->add('downloadAllowed', 'checkbox', [
+ ->add('downloadAllowed', CheckboxType::class, [
'required' => false,
'label' => $this->translator->trans('Allow download', [], 'cmfcmfmediamodule')
])
diff --git a/Form/Media/AbstractMediaEntityType.php b/Form/Media/AbstractMediaEntityType.php
index 1dd282ce..97a57a10 100644
--- a/Form/Media/AbstractMediaEntityType.php
+++ b/Form/Media/AbstractMediaEntityType.php
@@ -14,62 +14,58 @@
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Repository\CollectionRepository;
use Cmfcmf\Module\MediaModule\Entity\License\LicenseEntity;
+use Cmfcmf\Module\MediaModule\Entity\Media\MediaCategoryAssignmentEntity;
use Cmfcmf\Module\MediaModule\Form\AbstractType;
use Cmfcmf\Module\MediaModule\Form\DataTransformer\ArrayToJsonTransformer;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
+use Symfony\Component\Form\Extension\Core\Type\HiddenType;
+use Symfony\Component\Form\Extension\Core\Type\TextareaType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
+use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
-use Zikula\ExtensionsModule\Api\VariableApi;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+use Symfony\Component\Translation\TranslatorInterface;
+use Zikula\CategoriesModule\Form\Type\CategoriesType;
+use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
/**
* Provides some convenience methods for all media form types.
*/
abstract class AbstractMediaEntityType extends AbstractType
{
- /**
- * @var bool
- */
- protected $isCreation;
-
- /**
- * @var CollectionEntity|null
- */
- private $parent;
-
- /**
- * @var bool
- */
- private $allowTemporaryUploadCollection;
-
/**
* @var SecurityManager
*/
- private $securityManager;
+ protected $securityManager;
/**
- * @var VariableApi
+ * @var VariableApiInterface
*/
- private $variableApi;
+ protected $variableApi;
/**
* @var EntityManagerInterface
*/
- private $em;
+ protected $em;
+ /**
+ * @param TranslatorInterface $translator
+ * @param SecurityManager $securityManager
+ * @param VariableApiInterface $variableApi
+ * @param EntityManagerInterface $em
+ */
public function __construct(
+ TranslatorInterface $translator,
SecurityManager $securityManager,
- VariableApi $variableApi,
- EntityManagerInterface $em,
- $isCreation = false,
- CollectionEntity $parent = null,
- $allowTemporaryUploadCollection = false
+ VariableApiInterface $variableApi,
+ EntityManagerInterface $em
) {
+ $this->translator = $translator;
$this->securityManager = $securityManager;
- $this->isCreation = $isCreation;
- $this->parent = $parent;
- $this->allowTemporaryUploadCollection = $allowTemporaryUploadCollection;
$this->variableApi = $variableApi;
$this->em = $em;
}
@@ -112,7 +108,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
];
$securityManager = $this->securityManager;
- $allowTemporaryUploadCollection = $this->allowTemporaryUploadCollection;
+ $allowTemporaryUploadCollection = isset($options['allowTemporaryUploadCollection']) ? $options['allowTemporaryUploadCollection'] : false;
$collectionOptions = [
'required' => true,
'label' => $this->translator->trans('Collection', [], 'cmfcmfmediamodule'),
@@ -137,10 +133,10 @@ public function buildForm(FormBuilderInterface $builder, array $options)
return $qb;
},
'placeholder' => $this->translator->trans('Select collection', [], 'cmfcmfmediamodule'),
- 'property' => 'indentedTitle',
+ 'choice_label' => 'indentedTitle',
];
- if ($this->parent !== null) {
- $collectionOptions['data'] = $this->parent;
+ if (isset($options['parent']) && null !== $options['parent']) {
+ $collectionOptions['data'] = $options['parent'];
}
$defaultLicense = $this->variableApi->get('CmfcmfMediaModule', 'defaultLicense', null);
@@ -149,41 +145,41 @@ public function buildForm(FormBuilderInterface $builder, array $options)
}
$builder
- ->add('collection', 'entity', $collectionOptions)
- ->add('categoryAssignments', 'Zikula\CategoriesModule\Form\Type\CategoriesType', [
+ ->add('collection', EntityType::class, $collectionOptions)
+ ->add('categoryAssignments', CategoriesType::class, [
+ 'label' => $this->translator->trans('Categories', [], 'cmfcmfmediamodule'),
'required' => false,
'multiple' => true,
'module' => 'CmfcmfMediaModule',
'entity' => 'AbstractMediaEntity',
- 'entityCategoryClass' => 'Cmfcmf\Module\MediaModule\Entity\Media\MediaCategoryAssignmentEntity',
+ 'entityCategoryClass' => MediaCategoryAssignmentEntity::class,
])
- ->add(
- 'title',
+ ->add('title',
isset($options['hiddenFields']) && in_array(
'title',
- $options['hiddenFields']) ? 'hidden' : 'text',
+ $options['hiddenFields']) ? HiddenType::class : TextType::class,
[
'label' => $this->translator->trans('Title', [], 'cmfcmfmediamodule')
- ])
+ ]
+ )
->add(
'description',
isset($options['hiddenFields']) && in_array(
'description',
- $options['hiddenFields']) ? 'hidden' : 'textarea',
+ $options['hiddenFields']) ? HiddenType::class : TextareaType::class,
[
'required' => false,
'label' => $this->translator->trans('Description', [], 'cmfcmfmediamodule'),
'attr' => [
'help' => $descriptionHelp
]
- ])
+ ]
+ )
->add(
- 'license',
- 'entity',
- [
+ 'license', EntityType::class, [
'required' => false,
'label' => $this->translator->trans('License', [], 'cmfcmfmediamodule'),
- 'class' => 'CmfcmfMediaModule:License\LicenseEntity',
+ 'class' => LicenseEntity::class,
'preferred_choices' => function (LicenseEntity $license) {
return !$license->isOutdated();
},
@@ -192,58 +188,70 @@ public function buildForm(FormBuilderInterface $builder, array $options)
return $er->createQueryBuilder('l')
->orderBy('l.title', 'ASC')
->where('l.enabledForUpload = 1');
- // @todo Move to the actual uploadable file types.
+ // @todo Move to the actual uploadable file types.
},
'placeholder' => $this->translator->trans('Unknown', [], 'cmfcmfmediamodule'),
- 'property' => 'title',
+ 'choice_label' => 'title',
'attr' => isset($options['hiddenFields']) && in_array(
'license',
$options['hiddenFields']) ? $hiddenAttr : [],
'label_attr' => isset($options['hiddenFields']) && in_array(
'license',
$options['hiddenFields']) ? $hiddenAttr : []
- ])
- ->add(
- 'author',
+ ]
+ )
+ ->add('author',
isset($options['hiddenFields']) && in_array(
'author',
- $options['hiddenFields']) ? 'hidden' : 'text',
+ $options['hiddenFields']) ? HiddenType::class : TextType::class,
[
'label' => $this->translator->trans('Author', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null
- ])
- ->add(
- 'authorUrl',
+ ]
+ )
+ ->add('authorUrl',
isset($options['hiddenFields']) && in_array(
'authorUrl',
- $options['hiddenFields']) ? 'hidden' : 'url',
+ $options['hiddenFields']) ? HiddenType::class : UrlType::class,
[
'label' => $this->translator->trans('Author URL', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null
- ])
- ->add(
- 'authorAvatarUrl',
+ ]
+ )
+ ->add('authorAvatarUrl',
isset($options['hiddenFields']) && in_array(
'authorAvatarUrl',
- $options['hiddenFields']) ? 'hidden' : 'url',
+ $options['hiddenFields']) ? HiddenType::class : UrlType::class,
[
- 'label' => $this->translator->trans(
- 'Author Avatar URL',
- [],
- 'cmfcmfmediamodule'),
+ 'label' => $this->translator->trans('Author Avatar URL', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null
- ])
- ->add(
- 'mediaType',
- 'hidden',
- [
- 'mapped' => false
- ])
- ->add('extraData', 'hidden');
+ ]
+ )
+ ->add('mediaType', HiddenType::class, [
+ 'mapped' => false
+ ])
+ ->add('extraData', HiddenType::class)
+ ;
$builder->get('extraData')->addModelTransformer(new ArrayToJsonTransformer());
}
+
+ /**
+ * {@inheritdoc}
+ */
+ public function configureOptions(OptionsResolver $resolver)
+ {
+ $resolver
+ ->setDefaults([
+ 'isCreation' => false,
+ 'parent' => null,
+ 'allowTemporaryUploadCollection' => false
+ ])
+ ->setAllowedTypes('isCreation', 'bool')
+ ->setAllowedTypes('allowTemporaryUploadCollection', 'bool')
+ ;
+ }
}
diff --git a/Form/Media/DeezerType.php b/Form/Media/DeezerType.php
index 1e002c2b..f9245d8d 100644
--- a/Form/Media/DeezerType.php
+++ b/Form/Media/DeezerType.php
@@ -11,6 +11,8 @@
namespace Cmfcmf\Module\MediaModule\Form\Media;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
@@ -27,11 +29,11 @@ public function buildForm(FormBuilderInterface $builder, array $options)
parent::buildForm($builder, $options);
$builder
- ->add('musicType', 'hidden')
- ->add('musicId', 'hidden')
+ ->add('musicType', HiddenType::class)
+ ->add('musicId', HiddenType::class)
;
if ($options['showPlaylistCheckbox']) {
- $builder->add('showPlaylist', 'checkbox', [
+ $builder->add('showPlaylist', CheckboxType::class, [
'label' => $this->translator->trans('Show playlist', [], 'cmfcmfmediamodule'),
'required' => false
]);
diff --git a/Form/Media/FlickrType.php b/Form/Media/FlickrType.php
index b86453fc..62d0fbdd 100644
--- a/Form/Media/FlickrType.php
+++ b/Form/Media/FlickrType.php
@@ -11,6 +11,7 @@
namespace Cmfcmf\Module\MediaModule\Form\Media;
+use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
class FlickrType extends WebType
@@ -22,10 +23,10 @@ public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
- ->add('flickrid', 'hidden')
- ->add('flickrfarm', 'hidden')
- ->add('flickrsecret', 'hidden')
- ->add('flickrserver', 'hidden')
+ ->add('flickrid', HiddenType::class)
+ ->add('flickrfarm', HiddenType::class)
+ ->add('flickrsecret', HiddenType::class)
+ ->add('flickrserver', HiddenType::class)
;
}
}
diff --git a/Form/Media/PlaintextType.php b/Form/Media/PlaintextType.php
index fa67ee78..2afbc573 100644
--- a/Form/Media/PlaintextType.php
+++ b/Form/Media/PlaintextType.php
@@ -11,6 +11,7 @@
namespace Cmfcmf\Module\MediaModule\Form\Media;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
class PlaintextType extends AbstractFileType
@@ -23,7 +24,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
parent::buildForm($builder, $options);
$builder
- ->add('useSyntaxHighlighting', 'checkbox', [
+ ->add('useSyntaxHighlighting', CheckboxType::class, [
'required' => false,
'label' => $this->translator->trans('Use syntax highlighting', [], 'cmfcmfmediamodule')
])
diff --git a/Form/Media/SoundCloudType.php b/Form/Media/SoundCloudType.php
index de1d8dab..deae052f 100644
--- a/Form/Media/SoundCloudType.php
+++ b/Form/Media/SoundCloudType.php
@@ -11,6 +11,7 @@
namespace Cmfcmf\Module\MediaModule\Form\Media;
+use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
class SoundCloudType extends WebType
@@ -24,9 +25,10 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'url', 'license'
];
parent::buildForm($builder, $options);
+
$builder
- ->add('musicType', 'hidden')
- ->add('musicId', 'hidden')
+ ->add('musicType', HiddenType::class)
+ ->add('musicId', HiddenType::class)
;
}
}
diff --git a/Form/Media/WebType.php b/Form/Media/WebType.php
index 099b3822..0ad2a293 100644
--- a/Form/Media/WebType.php
+++ b/Form/Media/WebType.php
@@ -11,6 +11,8 @@
namespace Cmfcmf\Module\MediaModule\Form\Media;
+use Symfony\Component\Form\Extension\Core\Type\HiddenType;
+use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
class WebType extends AbstractMediaEntityType
@@ -21,8 +23,9 @@ class WebType extends AbstractMediaEntityType
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
+
$builder
- ->add('url', isset($options['hiddenFields']) && in_array('url', $options['hiddenFields']) ? 'hidden' : 'url')
+ ->add('url', isset($options['hiddenFields']) && in_array('url', $options['hiddenFields']) ? HiddenType::class : UrlType::class)
;
}
}
diff --git a/Form/SettingsType.php b/Form/SettingsType.php
index a1e8c13e..35291d45 100644
--- a/Form/SettingsType.php
+++ b/Form/SettingsType.php
@@ -11,37 +11,60 @@
namespace Cmfcmf\Module\MediaModule\Form;
+use Cmfcmf\Module\MediaModule\CollectionTemplate\TemplateCollection;
use Cmfcmf\Module\MediaModule\Entity\License\LicenseEntity;
+use Cmfcmf\Module\MediaModule\Form\CollectionTemplate\TemplateType;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType as SymfonyAbstractType;
use Symfony\Component\Form\CallbackTransformer;
+use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Translation\TranslatorInterface;
-use Zikula\ExtensionsModule\Api\VariableApi;
+use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
class SettingsType extends SymfonyAbstractType
{
- /**
- * @var array
- */
- private $templates;
-
/**
* @var TranslatorInterface
*/
private $translator;
/**
- * @var VariableApi
+ * @var VariableApiInterface
*/
private $variableApi;
- public function __construct(TranslatorInterface $translator, VariableApi $variableApi, array $templates)
- {
- $this->templates = $templates;
+ /**
+ * @var EntityManagerInterface
+ */
+ private $em;
+
+ /**
+ * @var array
+ */
+ private $templates;
+
+ /**
+ * @param TranslatorInterface $translator
+ * @param VariableApiInterface $variableApi
+ * @param EntityManagerInterface $em
+ * @param TemplateCollection $templateCollection
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ VariableApiInterface $variableApi,
+ EntityManagerInterface $em,
+ TemplateCollection $templateCollection
+ ) {
$this->translator = $translator;
$this->variableApi = $variableApi;
+ $this->em = $em;
+ $this->templates = $templateCollection->getCollectionTemplateTitles();
}
/**
@@ -49,37 +72,32 @@ public function __construct(TranslatorInterface $translator, VariableApi $variab
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
- /** @var EntityManagerInterface $em */
- $em = \ServiceUtil::get('doctrine.orm.entity_manager');
-
$builder
- ->add('descriptionEscapingStrategyForCollection', 'choice', [
+ ->add('descriptionEscapingStrategyForCollection', ChoiceType::class, [
'label' => $this->translator->trans('Collection description escaping strategy', [], 'cmfcmfmediamodule'),
- 'required' => true,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'descriptionEscapingStrategyForCollection'),
'choices' => [
- 'text' => $this->translator->trans('Safe - no HTML permitted, only plain text', [], 'cmfcmfmediamodule'),
- 'markdown' => $this->translator->trans('MarkDown', [], 'cmfcmfmediamodule'),
- 'raw' => $this->translator->trans('As is - use with editors like Scribite', [], 'cmfcmfmediamodule'),
+ $this->translator->trans('Safe - no HTML permitted, only plain text', [], 'cmfcmfmediamodule') => 'text',
+ $this->translator->trans('MarkDown', [], 'cmfcmfmediamodule') => 'markdown',
+ $this->translator->trans('As is - use with editors like Scribite', [], 'cmfcmfmediamodule') => 'raw'
]
])
- ->add('descriptionEscapingStrategyForMedia', 'choice', [
+ ->add('descriptionEscapingStrategyForMedia', ChoiceType::class, [
'label' => $this->translator->trans('Media description escaping strategy', [], 'cmfcmfmediamodule'),
- 'required' => true,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'descriptionEscapingStrategyForMedia'),
'choices' => [
- 'text' => $this->translator->trans('Safe - no HTML permitted, only plain text', [], 'cmfcmfmediamodule'),
- 'markdown' => $this->translator->trans('MarkDown', [], 'cmfcmfmediamodule'),
- 'raw' => $this->translator->trans('As is - use with editors like Scribite', [], 'cmfcmfmediamodule'),
+ $this->translator->trans('Safe - no HTML permitted, only plain text', [], 'cmfcmfmediamodule') => 'text',
+ $this->translator->trans('MarkDown', [], 'cmfcmfmediamodule') => 'markdown',
+ $this->translator->trans('As is - use with editors like Scribite', [], 'cmfcmfmediamodule') => 'raw'
]
])
- ->add('defaultCollectionTemplate', 'cmfcmfmediamodule_collectiontemplate', [
+ ->add('defaultCollectionTemplate', TemplateType::class, [
'label' => $this->translator->trans('Default collection template', [], 'cmfcmfmediamodule'),
'required' => true,
'allowDefaultTemplate' => false,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'defaultCollectionTemplate'),
])
- ->add('defaultLicense', 'entity', [
+ ->add('defaultLicense', EntityType::class, [
'label' => $this->translator->trans('Default license', [], 'cmfcmfmediamodule'),
'required' => false,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'defaultLicense', null),
@@ -93,30 +111,30 @@ public function buildForm(FormBuilderInterface $builder, array $options)
},
'empty_data' => null,
'placeholder' => $this->translator->trans('Unknown', [], 'cmfcmfmediamodule'),
- 'property' => 'title',
+ 'choice_label' => 'title',
])
- // @todo Allow to edit slugs.
- //->add('slugEditable', 'checkbox', [
- // 'label' => $this->translator->trans('Make slugs editable', [], 'cmfcmfmediamodule'),
- // 'data' => $this->variableApi->get('CmfcmfMediaModule', 'slugEditable')
- //])
- ->add('enableMediaViewCounter', 'checkbox', [
+ /*@todo Allow to edit slugs.
+ ->add('slugEditable', CheckboxType::class, [
+ 'label' => $this->translator->trans('Make slugs editable', [], 'cmfcmfmediamodule'),
+ 'data' => $this->variableApi->get('CmfcmfMediaModule', 'slugEditable')
+ ])*/
+ ->add('enableMediaViewCounter', CheckboxType::class, [
'label' => $this->translator->trans('Enable media view counter', [], 'cmfcmfmediamodule'),
'required' => false,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'enableMediaViewCounter', false),
'attr' => [
- 'help' => $this->translator->trans('Please note that this will cause an additional database update query per page view. Be also aware that the "updated date" and "updated user" fields will be updated every time as well.')
+ 'help' => $this->translator->trans('Please note that this will cause an additional database update query per page view. Be also aware that the "updated date" and "updated user" fields will be updated every time as well.', [], 'cmfcmfmediamodule')
]
])
- ->add('enableCollectionViewCounter', 'checkbox', [
+ ->add('enableCollectionViewCounter', CheckboxType::class, [
'label' => $this->translator->trans('Enable collection view counter', [], 'cmfcmfmediamodule'),
'required' => false,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'enableCollectionViewCounter', false),
'attr' => [
- 'help' => $this->translator->trans('Please note that this will cause an additional database update query per page view. Be also aware that the "updated date" and "updated user" fields will be updated every time as well.')
+ 'help' => $this->translator->trans('Please note that this will cause an additional database update query per page view. Be also aware that the "updated date" and "updated user" fields will be updated every time as well.', [], 'cmfcmfmediamodule')
]
])
- ->add('soundCloudApiKey', 'text', [
+ ->add('soundCloudApiKey', TextType::class, [
'label' => $this->translator->trans('SoundCloud "Client ID"', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
@@ -125,17 +143,17 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'help' => $this->translator->trans('Go to http://soundcloud.com/you/apps/new and create a new application. The name doesn\'t matter. In the next screen, enter the url of your Zikula installation at "Website of your App" and leave "Redirect URI for Authentication" empty. Then save and paste the "Client ID" here.', [], 'cmfcmfmediamodule')
]
])
- // @todo Flickr currently disabled.
- //->add('flickrApiKey', 'text', [
- // 'label' => $this->translator->trans('Flickr API Client Key', [], 'cmfcmfmediamodule'),
- // 'required' => false,
- // 'empty_data' => null,
- // 'data' => $this->variableApi->get('CmfcmfMediaModule', 'flickrApiKey'),
- // 'attr' => [
- // 'help' => $this->translator->trans('Go to https://www.flickr.com/services/apps/create/apply and create a new application. The name doesn\'t matter. Paste the "Key" here (not the "secret key", [], 'cmfcmfmediamodule').')
- // ]
- //])
- ->add('googleApiKey', 'text', [
+ /*@todo Flickr currently disabled.
+ ->add('flickrApiKey', TextType::class, [
+ 'label' => $this->translator->trans('Flickr API Client Key', [], 'cmfcmfmediamodule'),
+ 'required' => false,
+ 'empty_data' => null,
+ 'data' => $this->variableApi->get('CmfcmfMediaModule', 'flickrApiKey'),
+ 'attr' => [
+ 'help' => $this->translator->trans('Go to https://www.flickr.com/services/apps/create/apply and create a new application. The name doesn\'t matter. Paste the "Key" here (not the "secret key", [], 'cmfcmfmediamodule').')
+ ]
+ ])*/
+ ->add('googleApiKey', TextType::class, [
'label' => $this->translator->trans('Google API Developer Key', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
@@ -144,7 +162,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'help' => $this->translator->trans('Go to https://console.developers.google.com/project and create a new project. The name and id don\'t matter. Then go to "APIs and Authentication -> APIs" and enable the "YouTube Data API v3". Then go to "APIs and Authentication -> Credentials" and click "Add credentials -> API-Key -> Server-Key". Again, the name does\'t matter. Then paste the API key here.', [], 'cmfcmfmediamodule')
]
])
- ->add('googleApiOAuthClientID', 'text', [
+ ->add('googleApiOAuthClientID', TextType::class, [
'label' => $this->translator->trans('Google API OAuth2 Client ID', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
@@ -153,7 +171,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'help' => $this->translator->trans('Go to https://console.developers.google.com/project and create a new project. The name and id don\'t matter. Then go to "APIs and Authentication -> APIs" and enable the "YouTube Data API v3". Then go to "APIs and Authentication -> Credentials" and click "Add credentials -> OAuth-Client-ID -> Webapplication". Again, the name does\'t matter. Then paste the Client-ID here.', [], 'cmfcmfmediamodule')
]
])
- ->add('googleApiOAuthClientSecret', 'text', [
+ ->add('googleApiOAuthClientSecret', TextType::class, [
'label' => $this->translator->trans('Google API OAuth2 Client Secret', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
@@ -162,7 +180,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'help' => $this->translator->trans('Use the OAuth Client-Secret you got when creating your OAuth Client-ID.', [], 'cmfcmfmediamodule')
]
])
- ->add('twitterApiKey', 'text', [
+ ->add('twitterApiKey', TextType::class, [
'label' => $this->translator->trans('Twitter API Consumer Key', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
@@ -171,31 +189,32 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'help' => $this->translator->trans('Go to https://apps.twitter.com/ and create a new application. The name doesn\'t matter and "Callback URL" should be empty. Then go to "Keys and Access Tokens". At the bottom, click at "Create my access token".', [], 'cmfcmfmediamodule')
]
])
- ->add('twitterApiSecret', 'text', [
+ ->add('twitterApiSecret', TextType::class, [
'label' => $this->translator->trans('Twitter API Secret', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiSecret')
])
- ->add('twitterApiAccessToken', 'text', [
+ ->add('twitterApiAccessToken', TextType::class, [
'label' => $this->translator->trans('Twitter API Access Token', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiAccessToken')
])
- ->add('twitterApiAccessTokenSecret', 'text', [
+ ->add('twitterApiAccessTokenSecret', TextType::class, [
'label' => $this->translator->trans('Twitter API Access Token Secret', [], 'cmfcmfmediamodule'),
'required' => false,
'empty_data' => null,
'data' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiAccessTokenSecret')
])
- ->add('save', 'submit', [
+ ->add('save', SubmitType::class, [
'label' => $this->translator->trans('Save', [], 'cmfcmfmediamodule'),
'attr' => [
'class' => 'btn-success'
]
])
;
+ $em = $this->em;
$builder->get('defaultLicense')
->addModelTransformer(new CallbackTransformer(function ($modelData) use ($em) {
if (null === $modelData) {
@@ -216,7 +235,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
/**
* {@inheritdoc}
*/
- public function getName()
+ public function getBlockPrefix()
{
return 'cmfcmfmediamodule_settingstype';
}
diff --git a/Form/Type/ColorType.php b/Form/Type/ColorType.php
index 18854395..134893d8 100644
--- a/Form/Type/ColorType.php
+++ b/Form/Type/ColorType.php
@@ -13,10 +13,15 @@
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Displays a color selector.
+ *
+ * TODO consider replacing by native color picker
+ * check http://symfony.com/doc/current/reference/forms/types/color.html
+ * NOTE this would process RGB instead of RGBA values!
*/
class ColorType extends AbstractType
{
@@ -25,10 +30,10 @@ public function buildForm(FormBuilderInterface $builder, array $options)
$builder->addViewTransformer(new CallbackTransformer(
function ($rgba) {
if (empty($rgba)) {
- return "";
- } else {
- return "#" . substr($rgba, 7, 2) . substr($rgba, 1, 6);
+ return '';
}
+
+ return "#" . substr($rgba, 7, 2) . substr($rgba, 1, 6);
}, function ($argb) {
return "#" . substr($argb, 3, 6) . substr($argb, 1, 2);
}
@@ -40,13 +45,13 @@ function ($rgba) {
*/
public function getParent()
{
- return 'text';
+ return TextType::class;
}
/**
* {@inheritdoc}
*/
- public function getName()
+ public function getBlockPrefix()
{
return 'cmfcmfmediamodule_color';
}
diff --git a/Form/Type/FontType.php b/Form/Type/FontType.php
index 087481fd..f80b5d06 100644
--- a/Form/Type/FontType.php
+++ b/Form/Type/FontType.php
@@ -13,6 +13,7 @@
use Cmfcmf\Module\MediaModule\Font\FontCollection;
use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
@@ -59,13 +60,13 @@ public function buildView(FormView $view, FormInterface $form, array $options)
*/
public function getParent()
{
- return 'choice';
+ return ChoiceType::class;
}
/**
* {@inheritdoc}
*/
- public function getName()
+ public function getBlockPrefix()
{
return 'cmfcmfmediamodule_font_choice';
}
diff --git a/Form/Type/PermissionLevelType.php b/Form/Type/PermissionLevelType.php
index 23ab8024..01d7b2d8 100644
--- a/Form/Type/PermissionLevelType.php
+++ b/Form/Type/PermissionLevelType.php
@@ -17,6 +17,7 @@
use Fhaculty\Graph\Edge\Base;
use Fhaculty\Graph\Vertex;
use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Options;
@@ -48,7 +49,7 @@ public function __construct(SecurityManager $securityManager)
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
- if ($options['permissionLevel'] == CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS) {
+ if (CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS == $options['permissionLevel']) {
$this->fixSecurityGraph();
}
$view->vars['securityGraph'] = $this->securityGraph;
@@ -64,13 +65,13 @@ public function configureOptions(OptionsResolver $resolver)
'expanded' => true,
'multiple' => true,
'choices' => function (Options $options) {
- if ($options['permissionLevel'] == CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS) {
+ if (CollectionPermissionSecurityTree::PERM_LEVEL_ENHANCE_PERMISSIONS == $options['permissionLevel']) {
$this->fixSecurityGraph();
}
- return array_map(function (Vertex $vertex) {
+ return array_flip(array_map(function (Vertex $vertex) {
return $vertex->getAttribute('title');
- }, $this->securityGraph->getVertices()->getMap());
+ }, $this->securityGraph->getVertices()->getMap()));
}
])->setRequired('permissionLevel');
}
@@ -80,13 +81,13 @@ public function configureOptions(OptionsResolver $resolver)
*/
public function getParent()
{
- return 'choice';
+ return ChoiceType::class;
}
/**
* {@inheritdoc}
*/
- public function getName()
+ public function getBlockPrefix()
{
return 'cmfcmfmediamodule_permission';
}
diff --git a/Form/Watermark/AbstractWatermarkType.php b/Form/Watermark/AbstractWatermarkType.php
index 188b1365..0a1a6f0d 100644
--- a/Form/Watermark/AbstractWatermarkType.php
+++ b/Form/Watermark/AbstractWatermarkType.php
@@ -12,13 +12,27 @@
namespace Cmfcmf\Module\MediaModule\Form\Watermark;
use Cmfcmf\Module\MediaModule\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\NumberType;
+use Symfony\Component\Form\Extension\Core\Type\PercentType;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+use Symfony\Component\Translation\TranslatorInterface;
/**
* Form type for a watermark.
*/
class AbstractWatermarkType extends AbstractType
{
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
/**
* {@inheritdoc}
*/
@@ -27,47 +41,63 @@ public function buildForm(FormBuilderInterface $builder, array $options)
parent::buildForm($builder, $options);
$builder
- ->add('title', 'text', [
+ ->add('title', TextType::class, [
'attr' => [
'help' => $this->translator->trans('A title for you to recognize the watermark.', [], 'cmfcmfmediamodule')
]
])
- ->add('positionX', 'number', [
+ ->add('positionX', NumberType::class, [
'scale' => 0,
'attr' => [
'help' => $this->translator->trans('The x position of the watermark inside the picture. Negative numbers will position it right aligned.', [], 'cmfcmfmediamodule')
]
])
- ->add('positionY', 'number', [
+ ->add('positionY', NumberType::class, [
'scale' => 0,
'attr' => [
'help' => $this->translator->trans('The y position of the watermark inside the picture. Negative numbers will position it bottom aligned.', [], 'cmfcmfmediamodule')
]
])
- ->add('minSizeX', 'number', [
+ ->add('minSizeX', NumberType::class, [
+ 'label' => $this->translator->trans('Minimum size x', [], 'cmfcmfmediamodule'),
'scale' => 0,
'required' => false,
'attr' => [
'help' => $this->translator->trans('Smaller images will not be watermarked.', [], 'cmfcmfmediamodule')
]
])
- ->add('minSizeY', 'number', [
+ ->add('minSizeY', NumberType::class, [
+ 'label' => $this->translator->trans('Minimum size y', [], 'cmfcmfmediamodule'),
'scale' => 0,
'required' => false,
'attr' => [
'help' => $this->translator->trans('Smaller images will not be watermarked.', [], 'cmfcmfmediamodule')
]
])
- ->add('relativeSize', 'number', [
+ ->add('relativeSize', PercentType::class, [
+ 'label' => $this->translator->trans('Relative size', [], 'cmfcmfmediamodule'),
'scale' => 0,
+ 'type' => 'integer',
'required' => false,
'attr' => [
'help' => $this->translator->trans('The size of the watermark in percent. If set, it will resize the watermark accordingly.', [], 'cmfcmfmediamodule')
]
])
- ->add('submit', 'submit', [
+ ->add('submit', SubmitType::class, [
'label' => $this->translator->trans('Save', [], 'cmfcmfmediamodule')
])
;
}
+
+ /**
+ * {@inheritdoc}
+ */
+ public function configureOptions(OptionsResolver $resolver)
+ {
+ $resolver
+ ->setDefaults([
+ 'entity' => null
+ ])
+ ;
+ }
}
diff --git a/Form/Watermark/ImageWatermarkType.php b/Form/Watermark/ImageWatermarkType.php
index b230297e..f654decc 100644
--- a/Form/Watermark/ImageWatermarkType.php
+++ b/Form/Watermark/ImageWatermarkType.php
@@ -11,7 +11,7 @@
namespace Cmfcmf\Module\MediaModule\Form\Watermark;
-use Cmfcmf\Module\MediaModule\Entity\Watermark\ImageWatermarkEntity;
+use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
@@ -21,50 +21,35 @@
*/
class ImageWatermarkType extends AbstractWatermarkType
{
- /**
- * @var ImageWatermarkEntity
- */
- protected $entity;
-
- /**
- * @param ImageWatermarkEntity|null $entity
- */
- public function __construct(ImageWatermarkEntity $entity = null)
- {
- $this->entity = $entity;
- }
-
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$file = null;
- if ($this->entity !== null) {
- $file = new File($this->entity->getPath());
+ if (isset($options['entity']) && null !== $options['entity'] && $options['entity']->getFileName()) {
+ $file = new File($options['entity']->getPath());
}
- $builder
- ->add('file', 'file', [
- 'multiple' => false,
- 'mapped' => false,
- 'attr' => [
- 'help' => $this->translator->trans('Image to be used as watermark.', [], 'cmfcmfmediamodule')
- ],
- 'data' => $file, // @todo Still needed??
- 'required' => $this->entity === null,
- 'constraints' => [
- new Assert\File([
- // NOTE: If you change the allowed mime types here, make sure to
- // also change them in {@link ImageWatermarkEntity}
- 'mimeTypes' => [
- 'image/png',
- 'image/jpeg',
- 'image/gif'
- ]
- ])
- ]
- ])
- ;
+ $builder->add('file', FileType::class, [
+ 'multiple' => false,
+ 'mapped' => false,
+ 'attr' => [
+ 'help' => $this->translator->trans('Image to be used as watermark.', [], 'cmfcmfmediamodule')
+ ],
+ 'data' => $file, // @todo Still needed??
+ 'required' => (null === $file),
+ 'constraints' => [
+ new Assert\File([
+ // NOTE: If you change the allowed mime types here, make sure to
+ // also change them in {@link ImageWatermarkEntity}
+ 'mimeTypes' => [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif'
+ ]
+ ])
+ ]
+ ]);
parent::buildForm($builder, $options);
}
}
diff --git a/Form/Watermark/TextWatermarkType.php b/Form/Watermark/TextWatermarkType.php
index 19d01eb4..b33c2695 100644
--- a/Form/Watermark/TextWatermarkType.php
+++ b/Form/Watermark/TextWatermarkType.php
@@ -11,7 +11,11 @@
namespace Cmfcmf\Module\MediaModule\Form\Watermark;
+use Cmfcmf\Module\MediaModule\Form\Type\ColorType;
+use Cmfcmf\Module\MediaModule\Form\Type\FontType;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\Form\Extension\Core\Type\NumberType;
+use Symfony\Component\Form\Extension\Core\Type\TextType;
/**
* Form type for a text watermark.
@@ -24,12 +28,12 @@ class TextWatermarkType extends AbstractWatermarkType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
- ->add('text', 'text', [
+ ->add('text', TextType::class, [
'attr' => [
'help' => $this->translator->trans('Text to be used as watermark.', [], 'cmfcmfmediamodule')
]
])
- ->add('absoluteSize', 'number', [
+ ->add('absoluteSize', NumberType::class, [
'scale' => 0,
'label' => $this->translator->trans('Font size', [], 'cmfcmfmediamodule'),
'required' => false,
@@ -37,14 +41,20 @@ public function buildForm(FormBuilderInterface $builder, array $options)
'help' => $this->translator->trans('The font size to use, reagardless of the image size. Either this or the "Relative size" option must be set.', [], 'cmfcmfmediamodule')
]
])
- ->add('font', 'cmfcmfmediamodule_font_choice', [
+ ->add('font', FontType::class, [
'label' => $this->translator->trans('Font', [], 'cmfcmfmediamodule')
])
- ->add('fontColor', 'cmfcmfmediamodule_color', [
- 'label' => $this->translator->trans('Font color', [], 'cmfcmfmediamodule')
+ ->add('fontColor', ColorType::class, [
+ 'label' => $this->translator->trans('Font color', [], 'cmfcmfmediamodule'),
+ 'attr' => [
+ 'help' => $this->translator->trans('R-G-B-A', [], 'cmfcmfmediamodule')
+ ]
])
- ->add('backgroundColor', 'cmfcmfmediamodule_color', [
- 'label' => $this->translator->trans('Background color', [], 'cmfcmfmediamodule')
+ ->add('backgroundColor', ColorType::class, [
+ 'label' => $this->translator->trans('Background color', [], 'cmfcmfmediamodule'),
+ 'attr' => [
+ 'help' => $this->translator->trans('R-G-B-A', [], 'cmfcmfmediamodule')
+ ]
])
;
parent::buildForm($builder, $options);
diff --git a/Helper/SearchHelper.php b/Helper/SearchHelper.php
index b45d4002..cf35a6eb 100644
--- a/Helper/SearchHelper.php
+++ b/Helper/SearchHelper.php
@@ -14,41 +14,52 @@
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Cmfcmf\Module\MediaModule\Security\SecurityManager;
+use Doctrine\ORM\QueryBuilder;
+use Doctrine\ORM\Query\Expr\Composite;
+use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
use Zikula\Core\RouteUrl;
-use Zikula\SearchModule\AbstractSearchable;
+use Zikula\SearchModule\Entity\SearchResultEntity;
+use Zikula\SearchModule\SearchableInterface;
-class SearchHelper extends AbstractSearchable
+class SearchHelper implements SearchableInterface
{
/**
- * get the UI options for search form.
- *
- * @param bool $active if the module should be checked as active
- * @param array|null $modVars module form vars as previously set
- *
- * @return string
+ * @var RequestStack
*/
- public function getOptions($active, $modVars = null)
- {
- return $this->getContainer()->get('templating')
- ->render('@CmfcmfMediaModule/Search/options.html.twig', ['active' => $active]);
- }
+ private $requestStack;
/**
- * Get the search results.
- *
- * @param array $words array of words to search for
- * @param string $searchType AND|OR|EXACT
- * @param array|null $modVars module form vars passed though
- *
- * @return array
+ * @var SecurityManager
+ */
+ private $securityManager;
+
+ /**
+ * @param RequestStack $requestStack
+ * @param SecurityManager $securityManager
*/
+ public function __construct(
+ RequestStack $requestStack,
+ SecurityManager $securityManager
+ ) {
+ $this->requestStack = $requestStack;
+ $this->securityManager = $securityManager;
+
+ include_once __DIR__ . '/../bootstrap.php';
+ }
+
+ public function amendForm(FormBuilderInterface $builder)
+ {
+ // nothing
+ }
+
public function getResults(array $words, $searchType = 'AND', $modVars = null)
{
$results = [];
- $securityManager = $this->getContainer()->get('cmfcmf_media_module.security_manager');
- $sessionId = $this->container->get('session')->getId();
+ $sessionId = $this->requestStack->getCurrentRequest()->getSession()->getId();
- $qb = $securityManager->getCollectionsWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW);
+ $qb = $this->securityManager->getCollectionsWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_OVERVIEW);
$where = $this->formatWhere($qb, $words, ['c.title'], $searchType);
$qb->andWhere($where);
/** @var CollectionEntity[] $collections */
@@ -65,26 +76,66 @@ public function getResults(array $words, $searchType = 'AND', $modVars = null)
];
}
- $qb = $securityManager->getMediaWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_MEDIA_DETAILS);
+ $qb = $this->securityManager->getMediaWithAccessQueryBuilder(CollectionPermissionSecurityTree::PERM_LEVEL_MEDIA_DETAILS);
$where = $this->formatWhere($qb, $words, ['m.title'], $searchType);
$qb->andWhere($where);
/** @var AbstractMediaEntity[] $media */
$media = $qb->getQuery()->execute();
foreach ($media as $medium) {
- $results[] = [
- 'title' => $medium->getTitle(),
- 'text' => $medium->getDescription(),
- 'module' => 'CmfcmfMediaModule',
- 'created' => $medium->getCreatedDate(),
- 'sesid' => $sessionId,
- 'url' => new RouteUrl('cmfcmfmediamodule_media_display', [
+ $result = new SearchResultEntity();
+ $result->setTitle($medium->getTitle())
+ ->setText($medium->getDescription())
+ ->setModule('CmfcmfMediaModule')
+ ->setCreated($medium->getCreatedDate())
+ ->setSesid($sessionId)
+ ->setUrl(new RouteUrl('cmfcmfmediamodule_media_display', [
'slug' => $medium->getSlug(),
'collectionSlug' => $medium->getCollection()->getSlug()
- ])
- ];
+ ]))
+ ;
+ $results[] = $result;
}
return $results;
}
+
+ public function getErrors()
+ {
+ return [];
+ }
+
+ /**
+ * Construct a QueryBuilder Where orX|andX Expr instance.
+ *
+ * @param QueryBuilder $qb
+ * @param string[] $words List of words to query for
+ * @param string[] $fields List of fields to include into query
+ * @param string $searchtype AND|OR|EXACT
+ *
+ * @return null|Composite
+ */
+ protected function formatWhere(QueryBuilder $qb, array $words = [], array $fields = [], $searchtype = 'AND')
+ {
+ if (empty($words) || empty($fields)) {
+ return null;
+ }
+
+ $method = ('OR' == $searchtype) ? 'orX' : 'andX';
+ /** @var $where Composite */
+ $where = $qb->expr()->$method();
+ $i = 1;
+ foreach ($words as $word) {
+ $subWhere = $qb->expr()->orX();
+ foreach ($fields as $field) {
+ $expr = $qb->expr()->like($field, "?$i");
+ $subWhere->add($expr);
+ $qb->setParameter($i, '%' . $word . '%');
+ $i++;
+ }
+ $where->add($subWhere);
+ }
+
+ return $where;
+ }
}
diff --git a/HookHandler/AbstractHookHandler.php b/HookProvider/AbstractUiHooksProvider.php
similarity index 67%
rename from HookHandler/AbstractHookHandler.php
rename to HookProvider/AbstractUiHooksProvider.php
index df3a0b67..ea261375 100644
--- a/HookHandler/AbstractHookHandler.php
+++ b/HookProvider/AbstractUiHooksProvider.php
@@ -9,22 +9,30 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\HookHandler;
+namespace Cmfcmf\Module\MediaModule\HookProvider;
use Cmfcmf\Module\MediaModule\Security\SecurityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\TranslatorInterface;
-use Zikula\Bundle\HookBundle\Hook\DisplayHook;
-use Zikula\Bundle\HookBundle\Hook\DisplayHookResponse;
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Bundle\HookBundle\Hook\ProcessHook;
+use Zikula\Bundle\HookBundle\HookProviderInterface;
+use Zikula\Bundle\HookBundle\ServiceIdTrait;
/**
* Provides convenience methods for hook handling.
*/
-abstract class AbstractHookHandler
+abstract class AbstractUiHooksProvider implements HookProviderInterface
{
+ use ServiceIdTrait;
+
+ /**
+ * @var TranslatorInterface
+ */
+ protected $translator;
+
/**
* @var EntityManagerInterface
*/
@@ -46,33 +54,34 @@ abstract class AbstractHookHandler
protected $securityManager;
/**
- * @var TranslatorInterface
+ * @param EntityManagerInterface $entityManager
+ * @param RequestStack $requestStack
+ * @param EngineInterface $renderEngine
+ * @param SecurityManager $securityManager
+ * @param TranslatorInterface $translator
*/
- protected $translator;
-
public function __construct(
+ TranslatorInterface $translator,
EntityManagerInterface $entityManager,
RequestStack $requestStack,
EngineInterface $renderEngine,
- SecurityManager $securityManager,
- TranslatorInterface $translator
+ SecurityManager $securityManager
) {
+ $this->translator = $translator;
$this->entityManager = $entityManager;
$this->requestStack = $requestStack;
$this->renderEngine = $renderEngine;
$this->securityManager = $securityManager;
- $this->translator = $translator;
}
- /**
- * Generates a Hook response using the given content.
- *
- * @param DisplayHook $hook
- * @param string $content
- */
- public function uiResponse(DisplayHook $hook, $content)
+ public function getOwner()
{
- $hook->setResponse(new DisplayHookResponse($this->getProvider(), $content));
+ return 'CmfcmfMediaModule';
+ }
+
+ public function getCategory()
+ {
+ return UiHooksCategory::NAME;
}
/**
@@ -89,22 +98,4 @@ public function processDelete(ProcessHook $hook)
$this->entityManager->remove($hookedObject);
$this->entityManager->flush();
}
-
- /**
- * @return string
- */
- public function getType()
- {
- $class = get_class($this);
-
- return lcfirst(substr($class, strrpos($class, '\\') + 1, -strlen('HookHandler')));
- }
-
- /**
- * @return string
- */
- protected function getProvider()
- {
- return 'provider.cmfcmfmediamodule.ui_hooks.' . $this->getType();
- }
}
diff --git a/HookHandler/CollectionHookHandler.php b/HookProvider/CollectionUiHooksProvider.php
similarity index 66%
rename from HookHandler/CollectionHookHandler.php
rename to HookProvider/CollectionUiHooksProvider.php
index 0cc373b2..8ad2a1ab 100644
--- a/HookHandler/CollectionHookHandler.php
+++ b/HookProvider/CollectionUiHooksProvider.php
@@ -9,20 +9,22 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\HookHandler;
+namespace Cmfcmf\Module\MediaModule\HookProvider;
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
use Cmfcmf\Module\MediaModule\Entity\HookedObject\HookedObjectCollectionEntity;
use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Bundle\HookBundle\Hook\DisplayHook;
+use Zikula\Bundle\HookBundle\Hook\DisplayHookResponse;
use Zikula\Bundle\HookBundle\Hook\ProcessHook;
use Zikula\Bundle\HookBundle\Hook\ValidationHook;
use Zikula\Bundle\HookBundle\Hook\ValidationResponse;
/**
- * Handles collection hooks.
+ * Collection ui hooks provider.
*/
-class CollectionHookHandler extends AbstractHookHandler
+class CollectionUiHooksProvider extends AbstractUiHooksProvider
{
/**
* @var CollectionEntity[]
@@ -44,6 +46,22 @@ public function setMediaTypeCollection(MediaTypeCollection $mediaTypeCollection)
$this->mediaTypeCollection = $mediaTypeCollection;
}
+ public function getTitle()
+ {
+ return $this->translator->__('Collection ui hooks provider');
+ }
+
+ public function getProviderTypes()
+ {
+ return [
+ UiHooksCategory::TYPE_DISPLAY_VIEW => 'uiView',
+ UiHooksCategory::TYPE_FORM_EDIT => 'uiEdit',
+ UiHooksCategory::TYPE_VALIDATE_EDIT => 'validateEdit',
+ UiHooksCategory::TYPE_PROCESS_EDIT => 'processEdit',
+ UiHooksCategory::TYPE_PROCESS_DELETE => 'processDelete'
+ ];
+ }
+
/**
* @param DisplayHook $hook
*/
@@ -52,12 +70,12 @@ public function uiView(DisplayHook $hook)
$repository = $this->entityManager->getRepository('CmfcmfMediaModule:HookedObject\HookedObjectEntity');
$hookedObject = $repository->getByHookOrCreate($hook);
- $content = $this->renderEngine->render('CmfcmfMediaModule:Collection:hookView.html.twig', [
+ $content = $this->renderEngine->render('@CmfcmfMediaModule/Collection/hookView.html.twig', [
'hookedObjectCollections' => $hookedObject->getHookedObjectCollections(),
'mediaTypeCollection' => $this->mediaTypeCollection
]);
- $this->uiResponse($hook, $content);
+ $hook->setResponse(new DisplayHookResponse($this->getProviderArea(), $content));
}
/**
@@ -72,11 +90,12 @@ public function uiEdit(DisplayHook $hook)
return $hookedObjectCollectionEntity->getCollection()->getId();
}, $hookedObject->getHookedObjectCollections()->getValues());
- $content = $this->renderEngine->render('CmfcmfMediaModule:Collection:hookEdit.html.twig', [
+ $content = $this->renderEngine->render('@CmfcmfMediaModule/Collection/hookEdit.html.twig', [
'selectedCollections' => $selectedCollections,
'hookedObject' => $hookedObject
]);
- $this->uiResponse($hook, $content);
+
+ $hook->setResponse(new DisplayHookResponse($this->getProviderArea(), $content));
}
/**
@@ -84,9 +103,13 @@ public function uiEdit(DisplayHook $hook)
*/
public function validateEdit(ValidationHook $hook)
{
- $request = $this->requestStack->getCurrentRequest()->request;
+ include_once __DIR__ . '/../bootstrap.php';
- $collectionIds = json_decode($request->get('cmfcmfmediamodule[collections]', "[]", true));
+ // TODO migrate this to a FormAware hook provider
+ $collectionData = $this->requestStack->getCurrentRequest()
+ ->request->get('cmfcmfmediamodule[collections]', '[]', true);
+ $collectionData = isset($_POST['cmfcmfmediamodule']['collections']) ? $_POST['cmfcmfmediamodule']['collections'] : [];
+ $collectionIds = json_decode($collectionData);
$this->entities = [];
$validationResponse = new ValidationResponse('collections', $collectionIds);
@@ -101,7 +124,7 @@ public function validateEdit(ValidationHook $hook)
}
}
- $hook->setValidator($this->getProvider(), $validationResponse);
+ $hook->setValidator($this->getProviderArea(), $validationResponse);
}
/**
@@ -121,4 +144,12 @@ public function processEdit(ProcessHook $hook)
$repository->saveOrDelete($hookedObject);
}
+
+ /**
+ * @return string
+ */
+ private function getProviderArea()
+ {
+ return 'provider.cmfcmfmediamodule.ui_hooks.collections';
+ }
}
diff --git a/HookHandler/LicenseHookHandler.php b/HookProvider/LicenseUiHooksProvider.php
similarity index 66%
rename from HookHandler/LicenseHookHandler.php
rename to HookProvider/LicenseUiHooksProvider.php
index cc942d0e..642baf99 100644
--- a/HookHandler/LicenseHookHandler.php
+++ b/HookProvider/LicenseUiHooksProvider.php
@@ -9,24 +9,42 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\HookHandler;
+namespace Cmfcmf\Module\MediaModule\HookProvider;
use Cmfcmf\Module\MediaModule\Entity\License\LicenseEntity;
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Bundle\HookBundle\Hook\DisplayHook;
+use Zikula\Bundle\HookBundle\Hook\DisplayHookResponse;
use Zikula\Bundle\HookBundle\Hook\ProcessHook;
use Zikula\Bundle\HookBundle\Hook\ValidationHook;
use Zikula\Bundle\HookBundle\Hook\ValidationResponse;
/**
- * Handles license hooks.
+ * License ui hooks provider.
*/
-class LicenseHookHandler extends AbstractHookHandler
+class LicenseUiHooksProvider extends AbstractUiHooksProvider
{
/**
* @var LicenseEntity[]
*/
private $entities;
+ public function getTitle()
+ {
+ return $this->translator->__('License ui hooks provider');
+ }
+
+ public function getProviderTypes()
+ {
+ return [
+ UiHooksCategory::TYPE_DISPLAY_VIEW => 'uiView',
+ UiHooksCategory::TYPE_FORM_EDIT => 'uiEdit',
+ UiHooksCategory::TYPE_VALIDATE_EDIT => 'validateEdit',
+ UiHooksCategory::TYPE_PROCESS_EDIT => 'processEdit',
+ UiHooksCategory::TYPE_PROCESS_DELETE => 'processDelete'
+ ];
+ }
+
/**
* @param DisplayHook $hook
*/
@@ -35,10 +53,11 @@ public function uiView(DisplayHook $hook)
$repository = $this->entityManager->getRepository('CmfcmfMediaModule:HookedObject\HookedObjectEntity');
$hookedObject = $repository->getByHookOrCreate($hook);
- $content = $this->renderEngine->render('CmfcmfMediaModule:License:hookView.html.twig', [
+ $content = $this->renderEngine->render('@CmfcmfMediaModule/License/hookView.html.twig', [
'licenses' => $hookedObject->getLicenses()
]);
- $this->uiResponse($hook, $content);
+
+ $hook->setResponse(new DisplayHookResponse($this->getProviderArea(), $content));
}
/**
@@ -56,12 +75,13 @@ public function uiEdit(DisplayHook $hook)
return $licenseEntity->getId();
}, $hookedObject->getLicenses()->getValues());
- $content = $this->renderEngine->render('CmfcmfMediaModule:License:hookEdit.html.twig', [
+ $content = $this->renderEngine->render('@CmfcmfMediaModule/License/hookEdit.html.twig', [
'selectedLicenses' => $selectedIds,
'preferredLicenses' => $preferredLicenses,
'outdatedLicenses' => $outdatedLicenses
]);
- $this->uiResponse($hook, $content);
+
+ $hook->setResponse(new DisplayHookResponse($this->getProviderArea(), $content));
}
/**
@@ -69,8 +89,12 @@ public function uiEdit(DisplayHook $hook)
*/
public function validateEdit(ValidationHook $hook)
{
+ include_once __DIR__ . '/../bootstrap.php';
+
+ // TODO migrate this to a FormAware hook provider
$licenseIds = $this->requestStack->getCurrentRequest()
->request->get('cmfcmfmediamodule[license]', [], true);
+ $licenseIds = isset($_POST['cmfcmfmediamodule']['license']) ? $_POST['cmfcmfmediamodule']['license'] : [];
$this->entities = [];
$validationResponse = new ValidationResponse('license', $licenseIds);
@@ -85,7 +109,7 @@ public function validateEdit(ValidationHook $hook)
}
}
- $hook->setValidator($this->getProvider(), $validationResponse);
+ $hook->setValidator($this->getProviderArea(), $validationResponse);
}
/**
@@ -103,4 +127,12 @@ public function processEdit(ProcessHook $hook)
$repository->saveOrDelete($hookedObject);
}
+
+ /**
+ * @return string
+ */
+ private function getProviderArea()
+ {
+ return 'provider.cmfcmfmediamodule.ui_hooks.licenses';
+ }
}
diff --git a/HookHandler/MediaHookHandler.php b/HookProvider/MediaUiHooksProvider.php
similarity index 71%
rename from HookHandler/MediaHookHandler.php
rename to HookProvider/MediaUiHooksProvider.php
index 33beeb54..e8d0bc79 100644
--- a/HookHandler/MediaHookHandler.php
+++ b/HookProvider/MediaUiHooksProvider.php
@@ -9,21 +9,23 @@
* file that was distributed with this source code.
*/
-namespace Cmfcmf\Module\MediaModule\HookHandler;
+namespace Cmfcmf\Module\MediaModule\HookProvider;
use Cmfcmf\Module\MediaModule\Entity\HookedObject\HookedObjectMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Bundle\HookBundle\Hook\DisplayHook;
+use Zikula\Bundle\HookBundle\Hook\DisplayHookResponse;
use Zikula\Bundle\HookBundle\Hook\ProcessHook;
use Zikula\Bundle\HookBundle\Hook\ValidationHook;
use Zikula\Bundle\HookBundle\Hook\ValidationResponse;
/**
- * Handles media hooks.
+ * Media ui hooks provider.
*/
-class MediaHookHandler extends AbstractHookHandler
+class MediaUiHooksProvider extends AbstractUiHooksProvider
{
/**
* @var AbstractMediaEntity[]
@@ -45,6 +47,22 @@ public function setMediaTypeCollection(MediaTypeCollection $mediaTypeCollection)
$this->mediaTypeCollection = $mediaTypeCollection;
}
+ public function getTitle()
+ {
+ return $this->translator->__('Media ui hooks provider');
+ }
+
+ public function getProviderTypes()
+ {
+ return [
+ UiHooksCategory::TYPE_DISPLAY_VIEW => 'uiView',
+ UiHooksCategory::TYPE_FORM_EDIT => 'uiEdit',
+ UiHooksCategory::TYPE_VALIDATE_EDIT => 'validateEdit',
+ UiHooksCategory::TYPE_PROCESS_EDIT => 'processEdit',
+ UiHooksCategory::TYPE_PROCESS_DELETE => 'processDelete'
+ ];
+ }
+
/**
* @param DisplayHook $hook
*/
@@ -53,12 +71,12 @@ public function uiView(DisplayHook $hook)
$repository = $this->entityManager->getRepository('CmfcmfMediaModule:HookedObject\HookedObjectEntity');
$hookedObject = $repository->getByHookOrCreate($hook);
- $content = $this->renderEngine->render('CmfcmfMediaModule:Media:hookView.html.twig', [
+ $content = $this->renderEngine->render('@CmfcmfMediaModule/Media/hookView.html.twig', [
'hookedObjectMedia' => $hookedObject->getHookedObjectMedia(),
'mediaTypeCollection' => $this->mediaTypeCollection
]);
- $this->uiResponse($hook, $content);
+ $hook->setResponse(new DisplayHookResponse($this->getProviderArea(), $content));
}
/**
@@ -74,11 +92,11 @@ public function uiEdit(DisplayHook $hook)
return $hookedObjectMediaEntity->getMedia()->toArrayForFinder($mediaTypeCollection);
}, $hookedObject->getHookedObjectMedia()->getValues());
- $content = $this->renderEngine->render('CmfcmfMediaModule:Media:hookEdit.html.twig', [
+ $content = $this->renderEngine->render('@CmfcmfMediaModule/Media/hookEdit.html.twig', [
'selectedMedia' => $selectedMedia,
]);
- $this->uiResponse($hook, $content);
+ $hook->setResponse(new DisplayHookResponse($this->getProviderArea(), $content));
}
/**
@@ -86,8 +104,12 @@ public function uiEdit(DisplayHook $hook)
*/
public function validateEdit(ValidationHook $hook)
{
+ include_once __DIR__ . '/../bootstrap.php';
+
+ // TODO migrate this to a FormAware hook provider
$mediaIds = $this->requestStack->getCurrentRequest()
->request->get('cmfcmfmediamodule[media]', [], true);
+ $mediaIds = isset($_POST['cmfcmfmediamodule']['media']) ? $_POST['cmfcmfmediamodule']['media'] : [];
$this->entities = [];
$validationResponse = new ValidationResponse('media', $mediaIds);
@@ -104,7 +126,7 @@ public function validateEdit(ValidationHook $hook)
}
}
- $hook->setValidator($this->getProvider(), $validationResponse);
+ $hook->setValidator($this->getProviderArea(), $validationResponse);
}
/**
@@ -122,4 +144,12 @@ public function processEdit(ProcessHook $hook)
$repository->saveOrDelete($hookedObject);
}
+
+ /**
+ * @return string
+ */
+ private function getProviderArea()
+ {
+ return 'provider.cmfcmfmediamodule.ui_hooks.media';
+ }
}
diff --git a/HookSubscriber/CollectionFilterHooksSubscriber.php b/HookSubscriber/CollectionFilterHooksSubscriber.php
new file mode 100644
index 00000000..67f4c3e5
--- /dev/null
+++ b/HookSubscriber/CollectionFilterHooksSubscriber.php
@@ -0,0 +1,69 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\HookSubscriber;
+
+use Zikula\Bundle\HookBundle\Category\FilterHooksCategory;
+use Zikula\Bundle\HookBundle\HookSubscriberInterface;
+use Zikula\Common\Translator\TranslatorInterface;
+
+/**
+ * Collection filter hooks subscriber.
+ */
+class CollectionFilterHooksSubscriber implements HookSubscriberInterface
+{
+ /**
+ * @var TranslatorInterface
+ */
+ private $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOwner()
+ {
+ return 'CmfcmfMediaModule';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return FilterHooksCategory::NAME;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Collection filter hooks subscriber');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEvents()
+ {
+ return [
+ FilterHooksCategory::TYPE_FILTER => 'cmfcmfmediamodule.filter_hooks.collections.filter'
+ ];
+ }
+}
diff --git a/HookSubscriber/CollectionFormAwareHookSubscriber.php b/HookSubscriber/CollectionFormAwareHookSubscriber.php
new file mode 100644
index 00000000..58201dc1
--- /dev/null
+++ b/HookSubscriber/CollectionFormAwareHookSubscriber.php
@@ -0,0 +1,72 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\HookSubscriber;
+
+use Zikula\Bundle\HookBundle\Category\FormAwareCategory;
+use Zikula\Bundle\HookBundle\HookSubscriberInterface;
+use Zikula\Common\Translator\TranslatorInterface;
+
+/**
+ * Collection form aware hook subscriber.
+ */
+class CollectionFormAwareHookSubscriber implements HookSubscriberInterface
+{
+ /**
+ * @var TranslatorInterface
+ */
+ protected $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOwner()
+ {
+ return 'CmfcmfMediaModule';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return FormAwareCategory::NAME;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Collection form aware subscriber');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEvents()
+ {
+ return [
+ // Display hook for create/edit forms.
+ FormAwareCategory::TYPE_EDIT => 'cmfcmfmediamodule.form_aware_hook.collections.edit',
+ // Process the results of the edit form after the main form is processed.
+ FormAwareCategory::TYPE_PROCESS_EDIT => 'cmfcmfmediamodule.form_aware_hook.collections.process_edit'
+ ];
+ }
+}
diff --git a/HookSubscriber/CollectionUiHooksSubscriber.php b/HookSubscriber/CollectionUiHooksSubscriber.php
new file mode 100644
index 00000000..bb8ba5ef
--- /dev/null
+++ b/HookSubscriber/CollectionUiHooksSubscriber.php
@@ -0,0 +1,80 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\HookSubscriber;
+
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
+use Zikula\Bundle\HookBundle\HookSubscriberInterface;
+use Zikula\Common\Translator\TranslatorInterface;
+
+/**
+ * Collection ui hooks subscriber.
+ */
+class CollectionUiHooksSubscriber implements HookSubscriberInterface
+{
+ /**
+ * @var TranslatorInterface
+ */
+ protected $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOwner()
+ {
+ return 'CmfcmfMediaModule';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return UiHooksCategory::NAME;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Collection ui hooks subscriber');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEvents()
+ {
+ return [
+ // Display hook for view/display templates.
+ UiHooksCategory::TYPE_DISPLAY_VIEW => 'cmfcmfmediamodule.ui_hooks.collections.display_view',
+ // Display hook for create/edit forms.
+ UiHooksCategory::TYPE_FORM_EDIT => 'cmfcmfmediamodule.ui_hooks.collections.form_edit',
+ // Validate input from an item to be edited.
+ UiHooksCategory::TYPE_VALIDATE_EDIT => 'cmfcmfmediamodule.ui_hooks.collections.validate_edit',
+ // Perform the final update actions for an edited item.
+ UiHooksCategory::TYPE_PROCESS_EDIT => 'cmfcmfmediamodule.ui_hooks.collections.process_edit',
+ // Validate input from an item to be deleted.
+ UiHooksCategory::TYPE_VALIDATE_DELETE => 'cmfcmfmediamodule.ui_hooks.collections.validate_delete',
+ // Perform the final delete actions for a deleted item.
+ UiHooksCategory::TYPE_PROCESS_DELETE => 'cmfcmfmediamodule.ui_hooks.collections.process_delete'
+ ];
+ }
+}
diff --git a/HookSubscriber/MediaFilterHooksSubscriber.php b/HookSubscriber/MediaFilterHooksSubscriber.php
new file mode 100644
index 00000000..966bfd2e
--- /dev/null
+++ b/HookSubscriber/MediaFilterHooksSubscriber.php
@@ -0,0 +1,69 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\HookSubscriber;
+
+use Zikula\Bundle\HookBundle\Category\FilterHooksCategory;
+use Zikula\Bundle\HookBundle\HookSubscriberInterface;
+use Zikula\Common\Translator\TranslatorInterface;
+
+/**
+ * Media filter hooks subscriber.
+ */
+class MediaFilterHooksSubscriber implements HookSubscriberInterface
+{
+ /**
+ * @var TranslatorInterface
+ */
+ private $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOwner()
+ {
+ return 'CmfcmfMediaModule';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return FilterHooksCategory::NAME;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Media filter hooks subscriber');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEvents()
+ {
+ return [
+ FilterHooksCategory::TYPE_FILTER => 'cmfcmfmediamodule.filter_hooks.media.filter'
+ ];
+ }
+}
diff --git a/HookSubscriber/MediaFormAwareHookSubscriber.php b/HookSubscriber/MediaFormAwareHookSubscriber.php
new file mode 100644
index 00000000..1aba193e
--- /dev/null
+++ b/HookSubscriber/MediaFormAwareHookSubscriber.php
@@ -0,0 +1,72 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\HookSubscriber;
+
+use Zikula\Bundle\HookBundle\Category\FormAwareCategory;
+use Zikula\Bundle\HookBundle\HookSubscriberInterface;
+use Zikula\Common\Translator\TranslatorInterface;
+
+/**
+ * Media form aware hook subscriber.
+ */
+class MediaFormAwareHookSubscriber implements HookSubscriberInterface
+{
+ /**
+ * @var TranslatorInterface
+ */
+ protected $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOwner()
+ {
+ return 'CmfcmfMediaModule';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return FormAwareCategory::NAME;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Media form aware subscriber');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEvents()
+ {
+ return [
+ // Display hook for create/edit forms.
+ FormAwareCategory::TYPE_EDIT => 'cmfcmfmediamodule.form_aware_hook.media.edit',
+ // Process the results of the edit form after the main form is processed.
+ FormAwareCategory::TYPE_PROCESS_EDIT => 'cmfcmfmediamodule.form_aware_hook.media.process_edit'
+ ];
+ }
+}
diff --git a/HookSubscriber/MediaUiHooksSubscriber.php b/HookSubscriber/MediaUiHooksSubscriber.php
new file mode 100644
index 00000000..5eb0936a
--- /dev/null
+++ b/HookSubscriber/MediaUiHooksSubscriber.php
@@ -0,0 +1,80 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\HookSubscriber;
+
+use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
+use Zikula\Bundle\HookBundle\HookSubscriberInterface;
+use Zikula\Common\Translator\TranslatorInterface;
+
+/**
+ * Media ui hooks subscriber.
+ */
+class MediaUiHooksSubscriber implements HookSubscriberInterface
+{
+ /**
+ * @var TranslatorInterface
+ */
+ protected $translator;
+
+ /**
+ * @param TranslatorInterface $translator
+ */
+ public function __construct(TranslatorInterface $translator)
+ {
+ $this->translator = $translator;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOwner()
+ {
+ return 'CmfcmfMediaModule';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCategory()
+ {
+ return UiHooksCategory::NAME;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getTitle()
+ {
+ return $this->translator->__('Media ui hooks subscriber');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getEvents()
+ {
+ return [
+ // Display hook for view/display templates.
+ UiHooksCategory::TYPE_DISPLAY_VIEW => 'cmfcmfmediamodule.ui_hooks.media.display_view',
+ // Display hook for create/edit forms.
+ UiHooksCategory::TYPE_FORM_EDIT => 'cmfcmfmediamodule.ui_hooks.media.form_edit',
+ // Validate input from an item to be edited.
+ UiHooksCategory::TYPE_VALIDATE_EDIT => 'cmfcmfmediamodule.ui_hooks.media.validate_edit',
+ // Perform the final update actions for an edited item.
+ UiHooksCategory::TYPE_PROCESS_EDIT => 'cmfcmfmediamodule.ui_hooks.media.process_edit',
+ // Validate input from an item to be deleted.
+ UiHooksCategory::TYPE_VALIDATE_DELETE => 'cmfcmfmediamodule.ui_hooks.media.validate_delete',
+ // Perform the final delete actions for a deleted item.
+ UiHooksCategory::TYPE_PROCESS_DELETE => 'cmfcmfmediamodule.ui_hooks.media.process_delete'
+ ];
+ }
+}
diff --git a/Imagine/Cache/DummySigner.php b/Imagine/Cache/DummySigner.php
new file mode 100644
index 00000000..de356058
--- /dev/null
+++ b/Imagine/Cache/DummySigner.php
@@ -0,0 +1,55 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\Imagine\Cache;
+
+use Liip\ImagineBundle\Imagine\Cache\SignerInterface;
+
+/**
+ * Temporary dummy signer until https://github.com/zikula/core/issues/3902 has been resolved.
+ */
+class DummySigner implements SignerInterface
+{
+ /**
+ * @var string
+ */
+ protected $secret;
+
+ /**
+ * @param string $secret
+ */
+ public function __construct($secret)
+ {
+ $this->secret = $secret;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function sign($path, array $runtimeConfig = null)
+ {
+ if ($runtimeConfig) {
+ array_walk_recursive($runtimeConfig, function (&$value) {
+ $value = (string) $value;
+ });
+ }
+
+ return substr(preg_replace('/[^a-zA-Z0-9-_]/', '', base64_encode(hash_hmac('sha256', ltrim($path, '/').(null === $runtimeConfig ?: serialize($runtimeConfig)), $this->secret, true))), 0, 8);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function check($hash, $path, array $runtimeConfig = null)
+ {
+ return true; //$hash === $this->sign($path, $runtimeConfig);
+ }
+}
diff --git a/Imagine/Filter/Loader/CustomImageFilter.php b/Imagine/Filter/Loader/CustomImageFilter.php
new file mode 100644
index 00000000..b11ce298
--- /dev/null
+++ b/Imagine/Filter/Loader/CustomImageFilter.php
@@ -0,0 +1,182 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\Imagine\Filter\Loader;
+
+use Cmfcmf\Module\MediaModule\Font\FontCollection;
+use Doctrine\ORM\EntityManagerInterface;
+use Imagine\Filter\Basic\Autorotate;
+use Imagine\Filter\Basic\Paste;
+use Imagine\Filter\Basic\WebOptimization;
+use Imagine\Filter\Transformation;
+use Imagine\Image\ImageInterface;
+use Imagine\Image\ImagineInterface;
+use Imagine\Image\Point;
+use Liip\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;
+
+class CustomImageFilter implements LoaderInterface
+{
+ /**
+ * @var ImagineInterface
+ */
+ private $imagine;
+
+ /**
+ * @var EntityManagerInterface
+ */
+ private $em;
+
+ /**
+ * @var FontCollection
+ */
+ private $fontCollection;
+
+ /**
+ * @param ImagineInterface $imagine
+ * @param EntityManagerInterface $em
+ * @param FontCollection $fontCollection
+ */
+ public function __construct(
+ ImagineInterface $imagine,
+ EntityManagerInterface $em,
+ FontCollection $fontCollection
+ ) {
+ $this->imagine = $imagine;
+ $this->em = $em;
+ $this->fontCollection = $fontCollection;
+ }
+
+ /**
+ * @param ImageInterface $image
+ * @param array $options
+ *
+ * @return ImageInterface
+ */
+ public function load(ImageInterface $image, array $options = [])
+ {
+ $transformation = $this->getTransformation();
+
+ return $transformation->apply($image);
+ }
+
+ /**
+ * @param array $options
+ *
+ * @return Transformation
+ */
+ protected function getTransformation(array $options = [])
+ {
+ $transformation = new Transformation();
+ if (isset($options['optimize']) && $options['optimize']) {
+ // Optimize for web and rotate the images (after thumbnail creation).
+ $transformation
+ ->add(new Autorotate(), 101)
+ ->add(new WebOptimization(), 2)
+ ;
+ }
+
+ if (!isset($options['watermark']) || null === $options['watermark'] || !is_array($options['watermark']) || !count($options['watermark'])) {
+ // The image shall not be watermarked.
+ return $transformation;
+ }
+ $watermark = $this->em->getRepository('CmfcmfMediaModule:Watermark\\AbstractWatermarkEntity')->find($options['watermark']);
+ if (null === $watermark) {
+ // watermark not found
+ return $transformation;
+ }
+
+ // TODO consider replacing custom watermark processing by existing watermark filter
+ // check http://symfony.com/doc/current/bundles/LiipImagineBundle/filters/general.html#watermark
+
+ // Generate the watermark image.
+ // It will already be correctly sized for the thumbnail.
+
+ $wWidth = $wHeight = 0;
+ if (isset($options['mode']) && ImageInterface::THUMBNAIL_OUTBOUND == $options['mode']) {
+ $wWidth = $options['width'];
+ $wHeight = $options['height'];
+ } elseif (!isset($options['mode']) || ImageInterface::THUMBNAIL_INSET == $options['mode']) {
+ $imageSize = getimagesize($options['file']);
+
+ $ratios = [
+ $options['width'] / $imageSize[0],
+ $options['height'] / $imageSize[1]
+ ];
+ $wWidth = min($ratios) * $imageSize[0];
+ $wHeight = min($ratios) * $imageSize[1];
+ } else {
+ throw new \LogicException();
+ }
+
+ // Check whether the image is big enough to be watermarked.
+ if (null !== $watermark['minSizeX'] && $wWidth < $watermark['minSizeX']) {
+ return $transformation;
+ }
+ if (null !== $watermark['minSizeY'] && $wHeight < $watermark['minSizeY']) {
+ return $transformation;
+ }
+
+ $watermarkImage = $watermark->getImagineImage($this->imagine, $this->fontCollection, $wWidth, $wHeight);
+ $watermarkSize = $watermarkImage->getSize();
+
+ // Calculate watermark position. If the position is negative, handle
+ // it as an offset from the bottom / the right side of the image.
+ $x = $watermark->getPositionX();
+ $y = $watermark->getPositionY();
+ if ($x < 0) {
+ $x += $wWidth - $watermarkSize->getWidth();
+ }
+ if ($y < 0) {
+ $y += $wHeight - $watermarkSize->getHeight();
+ }
+
+ // If the watermark still exceeds the image's width or height, resize the watermark.
+ if ($x < 0 || $y < 0 || $x + $watermarkSize->getWidth() > $wWidth || $y + $watermarkSize->getHeight() > $wHeight) {
+ $xOffset = 0;
+ if ($x < 0) {
+ $xOffset = $x * -1;
+ }
+ $yOffset = 0;
+ if ($y < 0) {
+ $yOffset = $y * -1;
+ }
+
+ $ratios = [
+ ($watermarkSize->getWidth() - $xOffset) / $watermarkSize->getWidth(),
+ ($watermarkSize->getHeight() - $yOffset) / $watermarkSize->getHeight()
+ ];
+ $watermarkSize = $watermarkSize->scale(min($ratios));
+ $watermarkImage->resize($watermarkSize);
+
+ $x = round($watermark->getPositionX() + $wWidth - $watermarkSize->getWidth());
+ $y = round($watermark->getPositionY() + $wHeight - $watermarkSize->getHeight());
+
+ $xOffset = 0;
+ if ($x + $watermarkSize->getWidth() > $wWidth) {
+ $xOffset = $x + $watermarkSize->getWidth() - $wWidth;
+ }
+ $yOffset = 0;
+ if ($y + $watermarkSize->getHeight() > $wHeight) {
+ $yOffset = $y + $watermarkSize->getHeight() - $wHeight;
+ }
+ $ratios = [
+ ($watermarkSize->getWidth() - $xOffset) / $watermarkSize->getWidth(),
+ ($watermarkSize->getHeight() - $yOffset) / $watermarkSize->getHeight()
+ ];
+ $watermarkImage->resize($watermarkSize->scale(min($ratios)));
+ }
+
+ $point = new Point($x, $y);
+ $transformation->add(new Paste($watermarkImage, $point), 100);
+
+ return $transformation;
+ }
+}
diff --git a/Importer/AbstractImporter.php b/Importer/AbstractImporter.php
index e0ffcbea..f557cdeb 100644
--- a/Importer/AbstractImporter.php
+++ b/Importer/AbstractImporter.php
@@ -13,7 +13,9 @@
use Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection;
use Doctrine\ORM\EntityManagerInterface;
+use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Form\FormFactory;
+use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\TranslatorInterface;
abstract class AbstractImporter implements ImporterInterface
@@ -23,6 +25,11 @@ abstract class AbstractImporter implements ImporterInterface
*/
protected $translator;
+ /**
+ * @var Filesystem
+ */
+ protected $filesystem;
+
/**
* @var FormFactory
*/
@@ -38,12 +45,41 @@ abstract class AbstractImporter implements ImporterInterface
*/
protected $em;
- public function __construct(TranslatorInterface $translator, FormFactory $formFactory, MediaTypeCollection $mediaTypeCollection, EntityManagerInterface $em)
- {
+ /**
+ * @var RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * @var string
+ */
+ protected $dataDirectory;
+
+ /**
+ * @param TranslatorInterface $translator
+ * @param Filesystem $filesystem
+ * @param FormFactory $formFactory
+ * @param MediaTypeCollection $mediaTypeCollection
+ * @param EntityManagerInterface $em
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
+ */
+ public function __construct(
+ TranslatorInterface $translator,
+ Filesystem $filesystem,
+ FormFactory $formFactory,
+ MediaTypeCollection $mediaTypeCollection,
+ EntityManagerInterface $em,
+ RequestStack $requestStack,
+ $dataDirectory
+ ) {
$this->translator = $translator;
+ $this->filesystem = $filesystem;
$this->formFactory = $formFactory;
$this->mediaTypeCollection = $mediaTypeCollection;
$this->em = $em;
+ $this->requestStack = $requestStack;
+ $this->dataDirectory = $dataDirectory;
}
public function getId()
@@ -51,14 +87,12 @@ public function getId()
$type = $this->getType();
$type = strtolower($type);
- return "cmfcmfmediamodule:$type";
+ return 'cmfcmfmediamodule:' . $type;
}
public function getSettingsForm()
{
- $form = 'Cmfcmf\\Module\\MediaModule\\Form\\Importer\\' . $this->getType() . 'Type';
-
- return new $form($this->translator);
+ return 'Cmfcmf\\Module\\MediaModule\\Form\\Importer\\' . $this->getType() . 'Type';
}
/**
diff --git a/Importer/DownloadsModuleImporter.php b/Importer/DownloadsModuleImporter.php
index a5f40d79..e5e16690 100644
--- a/Importer/DownloadsModuleImporter.php
+++ b/Importer/DownloadsModuleImporter.php
@@ -16,7 +16,6 @@
use Cmfcmf\Module\MediaModule\Entity\Media\UrlEntity;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Stof\DoctrineExtensionsBundle\Uploadable\UploadableManager;
-use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
@@ -27,11 +26,13 @@ class DownloadsModuleImporter extends AbstractImporter
FROM downloads_downloads
WHERE cid = ?
SQL;
+
const DOWNLOAD_CATEGORY_QUERY = <<<'SQL'
SELECT cid, pid, title, description
FROM downloads_categories
ORDER BY pid ASC
SQL;
+
/**
* @var UploadableManager
*/
@@ -40,7 +41,7 @@ class DownloadsModuleImporter extends AbstractImporter
/**
* @var string
*/
- private $fileDirectory;
+ private $fileDirectory = '/Downloads';
public function getTitle()
{
@@ -60,11 +61,11 @@ public function checkRequirements()
$conn->executeQuery('SELECT 1 FROM downloads_categories LIMIT 1');
$conn->executeQuery('SELECT 1 FROM downloads_downloads LIMIT 1');
} catch (TableNotFoundException $e) {
- return $this->translator->trans('Please install the Downloads Module or import it\'s tables into the database.');
+ return $this->translator->trans('Please install the Downloads Module or import it\'s tables into the database.', [], 'cmfcmfmediamodule');
}
- $fs = new Filesystem();
- if (!$fs->exists($this->fileDirectory)) {
- return $this->translator->trans('The uploaded files are missing. Make sure %path% contains the uploaded files.', ['%path%' => $this->fileDirectory], 'cmfcmfmediamodule');
+
+ if (!$this->filesystem->exists($this->dataDirectory . $this->fileDirectory)) {
+ return $this->translator->trans('The uploaded files are missing. Make sure %path% contains the uploaded files.', ['%path%' => $this->dataDirectory . $this->fileDirectory], 'cmfcmfmediamodule');
}
return true;
@@ -75,11 +76,6 @@ public function setUploadManager(UploadableManager $uploadManager)
$this->uploadManager = $uploadManager;
}
- public function setUserDataDirectory($userDataDir)
- {
- $this->fileDirectory = $userDataDir . '/Downloads';
- }
-
public function import($formData, FlashBagInterface $flashBag)
{
/** @var CollectionEntity $collection */
@@ -101,22 +97,22 @@ public function import($formData, FlashBagInterface $flashBag)
$downloadResult = $conn->executeQuery(self::DOWNLOADS_QUERY, [$downloadCollection['cid']]);
while ($download = $downloadResult->fetch(\PDO::FETCH_ASSOC)) {
if (!empty($download['filename'])) {
- $file = new File($this->fileDirectory . '/' . $download['filename']);
+ $file = new File($this->dataDirectory . $this->fileDirectory . '/' . $download['filename']);
$mediaType = $this->mediaTypeCollection->getBestUploadableMediaTypeForFile($file);
$entityClass = $mediaType->getEntityClass();
/** @var AbstractFileEntity $entity */
- $entity = new $entityClass();
+ $entity = new $entityClass($this->requestStack, $this->dataDirectory);
$this->uploadManager->markEntityToUpload($entity, ImportedFile::fromFile($file));
} else {
- $entity = new UrlEntity();
+ $entity = new UrlEntity($this->requestStack, $this->dataDirectory);
$entity->setUrl($download['url']);
}
$entity
->setTitle($download['title'])
->setDescription($download['description'])
->setCollection($collection)
- //->setCreatedUserId()
- //->setUpdatedUserId()
+ //->setCreatedBy()
+ //->setUpdatedBy()
->setCreatedDate(new \DateTime($download['ddate']))
->setUpdatedDate(new \DateTime($download['uupdate']))
;
diff --git a/Importer/ServerDirectoryImporter.php b/Importer/ServerDirectoryImporter.php
index f5a817df..0c0e4773 100644
--- a/Importer/ServerDirectoryImporter.php
+++ b/Importer/ServerDirectoryImporter.php
@@ -66,27 +66,27 @@ public function import($formData, FlashBagInterface $flashBag)
->depth($formData['importSettings']['includeSubDirectories'] ? '>=0' : '==0')
->files()
;
- $collectionMapping = ["" => $rootCollection];
+ $collectionMapping = ['' => $rootCollection];
$c = 0;
/** @var SplFileInfo $finderFile */
foreach ($finder as $finderFile) {
$file = new File($finderFile->getPathname(), false);
$selectedMediaType = $this->mediaTypeCollection->getBestUploadableMediaTypeForFile($file);
- if ($selectedMediaType === null) {
+ if (null === $selectedMediaType) {
$flashBag->add('warning', $this->translator->trans('Could not import file %file%, because this kind of media isn\'t yet supported by the MediaModule.', ['%file%' => $file->getPathname()], 'cmfcmfmediamodule'));
continue;
}
$entityClass = $selectedMediaType->getEntityClass();
/** @var AbstractFileEntity $entity */
- $entity = new $entityClass();
+ $entity = new $entityClass($this->requestStack, $this->dataDirectory);
$relativePath = $finderFile->getRelativePath();
- if ($formData['importSettings']['createSubCollectionsForSubDirectories'] && $relativePath != "") {
+ if ($formData['importSettings']['createSubCollectionsForSubDirectories'] && "" != $relativePath) {
if (!isset($collectionMapping[$relativePath])) {
$collection = new CollectionEntity();
$lastSeparator = strrpos($relativePath, DIRECTORY_SEPARATOR);
$collection->setParent($collectionMapping[substr($relativePath, 0, (int)$lastSeparator)]);
- $collection->setTitle(substr($relativePath, $lastSeparator === false ? 0 : $lastSeparator + 1));
+ $collection->setTitle(substr($relativePath, false === $lastSeparator ? 0 : $lastSeparator + 1));
$this->em->persist($collection);
$collectionMapping[$relativePath] = $collection;
}
@@ -100,7 +100,7 @@ public function import($formData, FlashBagInterface $flashBag)
$this->em->persist($entity);
$c++;
- if ($c % 50 == 0) {
+ if (0 == $c % 50) {
$this->em->flush();
}
}
diff --git a/Importer/VerySimpleDownloadsModuleImporter.php b/Importer/VerySimpleDownloadsModuleImporter.php
index 796b6d47..36542c2e 100644
--- a/Importer/VerySimpleDownloadsModuleImporter.php
+++ b/Importer/VerySimpleDownloadsModuleImporter.php
@@ -17,9 +17,9 @@
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Stof\DoctrineExtensionsBundle\Uploadable\UploadableManager;
-use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
+use Zikula\CategoriesModule\Entity\RepositoryInterface\CategoryRegistryRepositoryInterface;
class VerySimpleDownloadsModuleImporter extends AbstractImporter
{
@@ -28,10 +28,15 @@ class VerySimpleDownloadsModuleImporter extends AbstractImporter
*/
private $uploadManager;
+ /**
+ * @var CategoryRegistryRepositoryInterface
+ */
+ private $categoryRegistryRepository;
+
/**
* @var string
*/
- private $fileDirectory;
+ private $fileDirectory = '/VerySimpleDownload/downloads/fileupload';
public function getTitle()
{
@@ -59,9 +64,8 @@ public function checkRequirements()
return $this->translator->trans('Please install the VerySimpleDownloads Module or import it\'s tables into the database.', [], 'cmfcmfmediamodule');
}
- $fs = new Filesystem();
- if (!$fs->exists($this->fileDirectory)) {
- return $this->translator->trans('The uploaded files are missing. Make sure %path% contains the uploaded files.', ['%path%' => $this->fileDirectory], 'cmfcmfmediamodule');
+ if (!$this->filesystem->exists($this->dataDirectory . $this->fileDirectory)) {
+ return $this->translator->trans('The uploaded files are missing. Make sure %path% contains the uploaded files.', ['%path%' => $this->dataDirectory . $this->fileDirectory], 'cmfcmfmediamodule');
}
return true;
@@ -72,20 +76,24 @@ public function setUploadManager(UploadableManager $uploadManager)
$this->uploadManager = $uploadManager;
}
- public function setUserDataDirectory($userDataDir)
+ public function setCategoryRegistryRepository(CategoryRegistryRepositoryInterface $categoryRegistryRepository)
{
- $this->fileDirectory = $userDataDir . '/VerySimpleDownload/downloads/fileupload';
+ $this->categoryRegistryRepository = $categoryRegistryRepository;
}
public function import($formData, FlashBagInterface $flashBag)
{
/** @var CollectionEntity $collection */
$collection = $formData['collection'];
- $categoryRegistry = \CategoryRegistryUtil::getRegisteredModuleCategory('CmfcmfMediaModule', 'AbstractMediaEntity', 'Main');
+ $categoryRegistry = $this->categoryRegistryRepository->findOneBy([
+ 'modname' => 'CmfcmfMediaModule',
+ 'entityname' => 'AbstractMediaEntity',
+ 'property' => 'Main'
+ ]);
$conn = $this->em->getConnection();
$result = $conn->executeQuery(<<<'SQL'
-SELECT d.id, d.downloadTitle, d.downloadDescription, d.fileUpload, d.createdUserId, d.updatedUserId, d.createdDate, d.updatedDate, c.categoryId
+SELECT d.id, d.downloadTitle, d.downloadDescription, d.fileUpload, d.createdBy, d.updatedBy, d.createdDate, d.updatedDate, c.categoryId
FROM vesido_download d
LEFT JOIN vesido_download_category c ON c.entityId = d.id
SQL
@@ -95,17 +103,17 @@ public function import($formData, FlashBagInterface $flashBag)
if ($lastId != $download['id']) {
$lastId = $download['id'];
- $file = new File($this->fileDirectory . '/' . $download['fileUpload']);
+ $file = new File($this->dataDirectory . $this->fileDirectory . '/' . $download['fileUpload']);
$mediaType = $this->mediaTypeCollection->getBestUploadableMediaTypeForFile($file);
$entityClass = $mediaType->getEntityClass();
/** @var AbstractFileEntity $entity */
- $entity = new $entityClass();
+ $entity = new $entityClass($this->requestStack, $this->dataDirectory);
$entity
->setTitle($download['downloadTitle'])
->setDescription($download['downloadDescription'])
->setCollection($collection)
- ->setCreatedUserId($download['createdUserId'])
- ->setUpdatedUserId($download['updatedUserId'])
+ ->setCreatedBy($download['createdBy'])
+ ->setUpdatedBy($download['updatedBy'])
->setCreatedDate(new \DateTime($download['createdDate']))
->setUpdatedDate(new \DateTime($download['updatedDate']))
;
diff --git a/Listener/DoctrineListener.php b/Listener/DoctrineListener.php
index fc2193a5..bed124b9 100644
--- a/Listener/DoctrineListener.php
+++ b/Listener/DoctrineListener.php
@@ -33,20 +33,26 @@ public function getSubscribedEvents()
public function uploadablePostFileProcess(UploadablePostFileProcessEventArgs $args)
{
$entity = $args->getEntity();
- if ($entity instanceof AudioEntity) {
- /** @var AudioEntity $entity */
- if ($entity->getMimeType() == 'application/octet-stream') {
- if (pathinfo($args->getFileInfo()->getName(), PATHINFO_EXTENSION) == 'mp3') {
- $om = $args->getEntityManager();
- $uow = $om->getUnitOfWork();
- $meta = $om->getClassMetadata(get_class($entity));
- $config = $args->getListener()->getConfiguration($om, $meta->name);
+ if (!($entity instanceof AudioEntity)) {
+ return;
+ }
+
+ /** @var AudioEntity $entity */
+ if ('application/octet-stream' != $entity->getMimeType()) {
+ return;
+ }
- $this->updateField($entity, $uow, $meta, $config['fileMimeTypeField'], 'audio/mp3');
- $uow->recomputeSingleEntityChangeSet($meta, $entity);
- }
- }
+ if ('mp3' != pathinfo($args->getFileInfo()->getName(), PATHINFO_EXTENSION)) {
+ return;
}
+
+ $om = $args->getEntityManager();
+ $uow = $om->getUnitOfWork();
+ $meta = $om->getClassMetadata(get_class($entity));
+ $config = $args->getListener()->getConfiguration($om, $meta->name);
+
+ $this->updateField($entity, $uow, $meta, $config['fileMimeTypeField'], 'audio/mp3');
+ $uow->recomputeSingleEntityChangeSet($meta, $entity);
}
/**
diff --git a/Listener/EntityLifecycleListener.php b/Listener/EntityLifecycleListener.php
new file mode 100644
index 00000000..1b47ee8a
--- /dev/null
+++ b/Listener/EntityLifecycleListener.php
@@ -0,0 +1,80 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Cmfcmf\Module\MediaModule\Listener;
+
+use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
+use Cmfcmf\Module\MediaModule\Entity\Watermark\AbstractWatermarkEntity;
+use Doctrine\Common\EventSubscriber;
+use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
+use Doctrine\ORM\Events;
+use Symfony\Component\DependencyInjection\ContainerAwareInterface;
+use Symfony\Component\DependencyInjection\ContainerAwareTrait;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Event subscriber class for entity lifecycle events.
+ */
+class EntityLifecycleListener implements EventSubscriber, ContainerAwareInterface
+{
+ use ContainerAwareTrait;
+
+ /**
+ * @param ContainerInterface $container
+ */
+ public function __construct(ContainerInterface $container)
+ {
+ $this->setContainer($container);
+ }
+
+ /**
+ * Returns list of events to subscribe.
+ *
+ * @return string[] List of events
+ */
+ public function getSubscribedEvents()
+ {
+ return [
+ Events::postLoad
+ ];
+ }
+
+ /**
+ * @param LifecycleEventArgs $args Event arguments
+ */
+ public function postLoad(LifecycleEventArgs $args)
+ {
+ $entity = $args->getObject();
+ if (!$this->isEntityManagedByThisBundle($entity)) {
+ return;
+ }
+
+ // TODO refactor these dependencies out of the entities
+ if ($entity instanceof AbstractMediaEntity || $entity instanceof AbstractWatermarkEntity) {
+ $entity->setRequestStack($this->container->get('request_stack'));
+ $entity->setDataDirectory($this->container->getParameter('datadir'));
+ }
+ }
+
+ /**
+ * Checks whether this listener is responsible for the given entity or not.
+ *
+ * @param EntityAccess $entity The given entity
+ *
+ * @return boolean True if entity is managed by this listener, false otherwise
+ */
+ protected function isEntityManagedByThisBundle($entity)
+ {
+ $entityClassParts = explode('\\', get_class($entity));
+
+ return 'Cmfcmf' == $entityClassParts[0] && 'MediaModule' == $entityClassParts[2];
+ }
+}
diff --git a/Listener/ModuleListener.php b/Listener/ModuleListener.php
index 32b1b75b..16d86a49 100644
--- a/Listener/ModuleListener.php
+++ b/Listener/ModuleListener.php
@@ -40,7 +40,7 @@ public function __construct(EntityManagerInterface $em)
public static function getSubscribedEvents()
{
return [
- CoreEvents::MODULE_REMOVE => 'moduleRemoved',
+ CoreEvents::MODULE_REMOVE => 'moduleRemoved'
];
}
diff --git a/Listener/ThirdPartyListener.php b/Listener/ThirdPartyListener.php
index 4b8a685a..e4c975da 100644
--- a/Listener/ThirdPartyListener.php
+++ b/Listener/ThirdPartyListener.php
@@ -13,89 +13,176 @@
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
-use Zikula_Event;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Zikula\Core\Event\GenericEvent;
+use Zikula\ScribiteModule\Event\EditorHelperEvent;
/**
* Listens to Scribite events.
*/
class ThirdPartyListener implements EventSubscriberInterface
{
- /**
- * @var string
- */
- private $zikulaRoot;
-
/**
* @var Filesystem
*/
- private $fs;
+ protected $filesystem;
/**
- * @var string
+ * @var RequestStack
*/
- private $resourceRoot;
+ protected $requestStack;
/**
- * @param string $kernelRootDir The kernel root directory.
+ * @param Filesystem $filesystem
+ * @param RequestStack $requestStack
*/
- public function __construct($kernelRootDir)
+ public function __construct(Filesystem $filesystem, RequestStack $requestStack)
{
- $this->zikulaRoot = realpath($kernelRootDir . '/..');
- $this->resourceRoot = realpath(__DIR__ . '/../Resources');
- $this->fs = new Filesystem();
+ $this->filesystem = $filesystem;
+ $this->requestStack = $requestStack;
}
/**
- * {@inheritdoc}
+ * Makes our handlers known to the event system.
*/
public static function getSubscribedEvents()
{
return [
- 'moduleplugin.ckeditor.externalplugins' => 'getCKEditorPlugins',
- 'module.scribite.editorhelpers' => 'getScribiteEditorHelpers'
+ 'module.scribite.editorhelpers' => ['getEditorHelpers', 5],
+ 'moduleplugin.ckeditor.externalplugins' => ['getCKEditorPlugins', 5],
+ 'moduleplugin.quill.externalplugins' => ['getQuillPlugins', 5],
+ 'moduleplugin.summernote.externalplugins' => ['getSummernotePlugins', 5],
+ 'moduleplugin.tinymce.externalplugins' => ['getTinyMcePlugins', 5]
];
}
/**
- * Adds external plugin to CKEditor.
+ * Listener for the `module.scribite.editorhelpers` event.
*
- * @param Zikula_Event $event The event instance.
- */
- public function getCKEditorPlugins(Zikula_Event $event)
- {
- $plugins = $event->getSubject();
- $plugins->add([
- 'name' => 'cmfcmfmediamodule',
- 'path' => $this->fs->makePathRelative($this->resourceRoot . '/public/js/CKEditorPlugin', $this->zikulaRoot),
- 'file' => 'plugin.js',
- 'img' => $this->fs->makePathRelative($this->resourceRoot . '/public/images', $this->zikulaRoot) . 'admin.png'
- ]);
- }
-
- /**
- * Adds extra JS to load on pages using the Scribite editor.
+ * This occurs when Scribite adds pagevars to the editor page.
+ * CmfcmfMediaModule will use this to add a javascript helper to add custom items.
*
- * @param Zikula_Event $event
+ * You can access general data available in the event.
+ *
+ * The event name:
+ * `echo 'Event: ' . $event->getName();`
+ *
+ * @param EditorHelperEvent $event The event instance
*/
- public function getScribiteEditorHelpers(Zikula_Event $event)
+ public function getEditorHelpers(EditorHelperEvent $event)
{
- // intended is using the add() method to add a helper like below
- $helpers = $event->getSubject();
+ // install assets for Scribite plugins
+ $targetDir = 'web/modules/cmfcmfmedia';
+ if (!$this->filesystem->exists($targetDir)) {
+ $moduleDirectory = str_replace('Listener', '', __DIR__);
+ if (is_dir($originDir = $moduleDirectory . 'Resources/public')) {
+ $this->filesystem->symlink($originDir, $targetDir, true);
+ }
+ }
+ $basePath = $this->requestStack->getCurrentRequest()->getBasePath();
+ $helpers = $event->getHelperCollection();
$helpers->add([
'module' => 'CmfcmfMediaModule',
'type' => 'javascript',
- 'path' => $this->fs->makePathRelative($this->resourceRoot . '/public/js/vendor', $this->zikulaRoot) . 'toastr.min.js'
+ 'path' => $basePath . '/web/modules/cmfcmfmedia/js/vendor/toastr.min.js'
]);
$helpers->add([
'module' => 'CmfcmfMediaModule',
'type' => 'stylesheet',
- 'path' => $this->fs->makePathRelative($this->resourceRoot . '/public/css/vendor', $this->zikulaRoot) . 'toastr.min.css'
+ 'path' => $basePath . '/web/modules/cmfcmfmedia/css/vendor/toastr.min.css'
+ ]);
+ $helpers->add([
+ 'module' => 'CmfcmfMediaModule',
+ 'type' => 'javascript',
+ 'path' => $basePath . '/web/modules/cmfcmfmedia/js/util.js'
]);
$helpers->add([
'module' => 'CmfcmfMediaModule',
'type' => 'javascript',
- 'path' => $this->fs->makePathRelative($this->resourceRoot . '/public/js', $this->zikulaRoot) . 'util.js'
+ 'path' => $basePath . '/web/modules/cmfcmfmedia/js/Finder/opener.js'
+ ]);
+ }
+
+ /**
+ * Listener for the `moduleplugin.ckeditor.externalplugins` event.
+ *
+ * Adds external plugin to CKEditor.
+ *
+ * You can access general data available in the event.
+ *
+ * The event name:
+ * `echo 'Event: ' . $event->getName();`
+ *
+ * @param GenericEvent $event The event instance
+ */
+ public function getCKEditorPlugins(GenericEvent $event)
+ {
+ $event->getSubject()->add([
+ 'name' => 'cmfcmfmediamodule',
+ 'path' => $this->requestStack->getCurrentRequest()->getBasePath() . '/web/modules/cmfcmfmedia/scribite/CKEditor/cmfcmfmediamodule/',
+ 'file' => 'plugin.js',
+ 'img' => 'ed_cmfcmfmediamodule.gif'
+ ]);
+ }
+
+ /**
+ * Listener for the `moduleplugin.quill.externalplugins` event.
+ *
+ * Adds external plugin to Quill.
+ *
+ * You can access general data available in the event.
+ *
+ * The event name:
+ * `echo 'Event: ' . $event->getName();`
+ *
+ * @param GenericEvent $event The event instance
+ */
+ public function getQuillPlugins(GenericEvent $event)
+ {
+ $event->getSubject()->add([
+ 'name' => 'cmfcmfmediamodule',
+ 'path' => $this->requestStack->getCurrentRequest()->getBasePath() . '/web/modules/cmfcmfmedia/scribite/Quill/cmfcmfmediamodule/plugin.js'
+ ]);
+ }
+
+ /**
+ * Listener for the `moduleplugin.summernote.externalplugins` event.
+ *
+ * Adds external plugin to Summernote.
+ *
+ * You can access general data available in the event.
+ *
+ * The event name:
+ * `echo 'Event: ' . $event->getName();`
+ *
+ * @param GenericEvent $event The event instance
+ */
+ public function getSummernotePlugins(GenericEvent $event)
+ {
+ $event->getSubject()->add([
+ 'name' => 'cmfcmfmediamodule',
+ 'path' => $this->requestStack->getCurrentRequest()->getBasePath() . '/web/modules/cmfcmfmedia/scribite/Summernote/cmfcmfmediamodule/plugin.js'
+ ]);
+ }
+
+ /**
+ * Listener for the `moduleplugin.tinymce.externalplugins` event.
+ *
+ * Adds external plugin to TinyMce.
+ *
+ * You can access general data available in the event.
+ *
+ * The event name:
+ * `echo 'Event: ' . $event->getName();`
+ *
+ * @param GenericEvent $event The event instance
+ */
+ public function getTinyMcePlugins(GenericEvent $event)
+ {
+ $event->getSubject()->add([
+ 'name' => 'cmfcmfmediamodule',
+ 'path' => $this->requestStack->getCurrentRequest()->getBasePath() . '/web/modules/cmfcmfmedia/scribite/TinyMce/cmfcmfmediamodule/plugin.js'
]);
}
}
diff --git a/MediaModuleInstaller.php b/MediaModuleInstaller.php
index e4154995..c64e64dd 100644
--- a/MediaModuleInstaller.php
+++ b/MediaModuleInstaller.php
@@ -12,10 +12,20 @@
namespace Cmfcmf\Module\MediaModule;
use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity;
+use Cmfcmf\Module\MediaModule\Entity\Collection\CollectionCategoryAssignmentEntity;
+use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
+use Cmfcmf\Module\MediaModule\Entity\Media\MediaCategoryAssignmentEntity;
+use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\AbstractPermissionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\GroupPermissionEntity;
use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\OwnerPermissionEntity;
+use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\UserPermissionEntity;
+use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\Restriction\PasswordPermissionRestrictionEntity;
+use Cmfcmf\Module\MediaModule\Entity\Collection\Permission\Restriction\AbstractPermissionRestrictionEntity;
use Cmfcmf\Module\MediaModule\Entity\License\LicenseEntity;
+use Cmfcmf\Module\MediaModule\Entity\Watermark\AbstractWatermarkEntity;
+use Cmfcmf\Module\MediaModule\Entity\Watermark\TextWatermarkEntity;
use Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionSecurityTree;
+use Zikula\CategoriesModule\Entity\CategoryRegistryEntity;
use Zikula\Core\AbstractExtensionInstaller;
class MediaModuleInstaller extends AbstractExtensionInstaller
@@ -39,7 +49,7 @@ public function install()
// We need to create and flush the upload collection first, because it has to has the ID 1.
$this->entityManager->flush();
- if ($temporaryUploadCollection->getId() != CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID) {
+ if (CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID != $temporaryUploadCollection->getId()) {
throw new \Exception($this->__f('The id of the generated "temporary upload collection" must be %s, but has a different value. This should not have happened. Please report this error.', ['%s' => CollectionEntity::TEMPORARY_UPLOAD_COLLECTION_ID]));
}
@@ -62,9 +72,6 @@ public function install()
$this->createPermissions($temporaryUploadCollection, $rootCollection);
- $this->hookApi->installSubscriberHooks($this->bundle->getMetaData());
- $this->hookApi->installProviderHooks($this->bundle->getMetaData());
-
$this->setVar('descriptionEscapingStrategyForCollection', 'text');
$this->setVar('descriptionEscapingStrategyForMedia', 'text');
$this->setVar('defaultCollectionTemplate', 'cards');
@@ -104,16 +111,16 @@ public function upgrade($oldversion)
/** @noinspection PhpMissingBreakStatementInspection */
case '1.0.6':
$this->schemaTool->create([
- 'Cmfcmf\Module\MediaModule\Entity\Collection\Permission\AbstractPermissionEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Collection\Permission\GroupPermissionEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Collection\Permission\UserPermissionEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Collection\Permission\OwnerPermissionEntity',
+ AbstractPermissionEntity::class,
+ GroupPermissionEntity::class,
+ OwnerPermissionEntity::class,
+ UserPermissionEntity::class,
- 'Cmfcmf\Module\MediaModule\Entity\Collection\Permission\Restriction\PasswordPermissionRestrictionEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Collection\Permission\Restriction\AbstractPermissionRestrictionEntity',
+ AbstractPermissionRestrictionEntity::class,
+ PasswordPermissionRestrictionEntity::class
]);
$this->schemaTool->update([
- 'Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity'
+ CollectionEntity::class
]);
// Create root collection.
@@ -126,10 +133,10 @@ public function upgrade($oldversion)
$this->entityManager->persist($rootCollection);
$allCollections = $this->entityManager
- ->getRepository('Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity')
+ ->getRepository(CollectionEntity::class)
->findAll();
foreach ($allCollections as $collection) {
- if ($collection->getParent() === null && $collection->getId() != null) {
+ if (null === $collection->getParent() && null != $collection->getId()) {
// Collection has no parent and isn't the to-be-created root collection.
$collection->setParent($rootCollection);
$this->entityManager->merge($collection);
@@ -138,28 +145,52 @@ public function upgrade($oldversion)
$this->entityManager->flush();
$this->createPermissions(
- $this->entityManager->find('Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity', 1),
+ $this->entityManager->find(CollectionEntity::class, 1),
$rootCollection
);
case '1.1.0':
case '1.1.1':
case '1.1.2':
$this->schemaTool->update([
- 'Cmfcmf\Module\MediaModule\Entity\Watermark\TextWatermarkEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Watermark\AbstractWatermarkEntity'
+ AbstractWatermarkEntity::class,
+ TextWatermarkEntity::class
]);
- $this->entityManager->getConnection()->executeUpdate("UPDATE `cmfcmfmedia_watermarks` SET `fontColor`='#000000ff',`backgroundColor`='#00000000' WHERE `discr`='text'");
+ $this->entityManager->getConnection()->executeUpdate("
+ UPDATE `cmfcmfmedia_watermarks`
+ SET `fontColor`='#000000ff', `backgroundColor`='#00000000'
+ WHERE `discr`='text'
+ ");
$this->schemaTool->update([
- 'Cmfcmf\Module\MediaModule\Entity\Collection\CollectionEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Collection\CollectionCategoryAssignmentEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity',
- 'Cmfcmf\Module\MediaModule\Entity\Media\MediaCategoryAssignmentEntity',
+ CollectionEntity::class,
+ CollectionCategoryAssignmentEntity::class,
+ AbstractMediaEntity::class,
+ MediaCategoryAssignmentEntity::class
]);
$this->createCategoryRegistries();
case '1.2.0':
case '1.2.1':
+ case '1.2.2':
+ // fields have changed: createdUserId becomes createdBy, updatedUserId becomes updatedBy
+ $connection = $this->entityManager->getConnection();
+ foreach (['collection', 'media', 'watermarks', 'permission'] as $tableName) {
+ $sql = '
+ ALTER TABLE `cmfcmfmedia_' . $tableName . '`
+ CHANGE `createdUserId` `createdBy` INT(11) DEFAULT NULL
+ ';
+ $stmt = $connection->prepare($sql);
+ $stmt->execute();
+
+ $sql = '
+ ALTER TABLE `cmfcmfmedia_' . $tableName . '`
+ CHANGE `updatedUserId` `updatedBy` INT(11) DEFAULT NULL
+ ';
+ $stmt = $connection->prepare($sql);
+ $stmt->execute();
+ }
+ case '1.3.0':
+ case '2.0.0':
return true;
default:
return false;
@@ -174,13 +205,14 @@ public function uninstall()
// @todo Also delete media files?
$this->schemaTool->drop(static::getEntities());
- $this->hookApi->uninstallSubscriberHooks($this->bundle->getMetaData());
- $this->hookApi->uninstallProviderHooks($this->bundle->getMetaData());
-
$this->delVars();
- \CategoryRegistryUtil::deleteEntry('CmfcmfMediaModule');
- \CategoryRegistryUtil::deleteEntry('CmfcmfMediaModule');
+ // remove category registry entries
+ $registries = $this->container->get('zikula_categories_module.category_registry_repository')->findBy(['modname' => 'CmfcmfMediaModule']);
+ foreach ($registries as $registry) {
+ $this->entityManager->remove($registry);
+ }
+ $this->entityManager->flush();
return true;
}
@@ -269,7 +301,7 @@ private function createLicenses()
foreach ($ccVersions as $version) {
foreach ($ccNames as $id => $name) {
- if ($id == 'CC-BY-NC-ND' && $version == '1.0') {
+ if ('CC-BY-NC-ND' == $id && '1.0' == $version) {
// The license image somehow does not exist.
continue;
}
@@ -281,7 +313,7 @@ private function createLicenses()
->setImageUrl("https://i.creativecommons.org/l/$urlId/$version/80x15.png")
->setEnabledForWeb(true)
->setEnabledForUpload(true)
- ->setOutdated($version != '4.0')
+ ->setOutdated('4.0' != $version)
;
$this->entityManager->persist($license);
}
@@ -294,7 +326,8 @@ private function createLicenses()
*/
private function createUploadDir()
{
- $uploadDirectory = \FileUtil::getDataDirectory() . '/cmfcmf-media-module/media';
+ $dataDirectory = $this->container->getParameter('datadir');
+ $uploadDirectory = $dataDirectory . '/cmfcmf-media-module/media';
if (!is_dir($uploadDirectory)) {
mkdir($uploadDirectory, 0777, true);
@@ -372,8 +405,21 @@ private function createPermissions(CollectionEntity $temporaryUploadCollection,
private function createCategoryRegistries()
{
- $categoryID = \CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global')['id'];
- \CategoryRegistryUtil::insertEntry('CmfcmfMediaModule', 'AbstractMediaEntity', 'Main', $categoryID);
- \CategoryRegistryUtil::insertEntry('CmfcmfMediaModule', 'CollectionEntity', 'Main', $categoryID);
+ $categoryGlobal = $this->container->get('zikula_categories_module.category_repository')->findOneBy(['name' => 'Global']);
+ if (!$categoryGlobal) {
+ return;
+ }
+
+ $entityManager = $this->container->get('doctrine.orm.default_entity_manager');
+ foreach (['AbstractMediaEntity', 'CollectionEntity'] as $entityName) {
+ $registry = new CategoryRegistryEntity();
+ $registry->setModname('CmfcmfMediaModule');
+ $registry->setEntityname($entityName);
+ $registry->setProperty('Main');
+ $registry->setCategory($categoryGlobal);
+
+ $entityManager->persist($registry);
+ }
+ $entityManager->flush();
}
}
diff --git a/MediaType/AbstractFileMediaType.php b/MediaType/AbstractFileMediaType.php
index aca2ad7c..01656b89 100644
--- a/MediaType/AbstractFileMediaType.php
+++ b/MediaType/AbstractFileMediaType.php
@@ -12,7 +12,8 @@
namespace Cmfcmf\Module\MediaModule\MediaType;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractFileEntity;
-use Cmfcmf\Module\MediaModule\Font\FontCollection;
+use Imagine\Image\ImageInterface;
+use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -34,27 +35,21 @@ abstract class AbstractFileMediaType extends AbstractMediaType
private $zikulaRoot;
/**
- * @var \SystemPlugin_Imagine_Manager
+ * @var CacheManager
*/
- protected $imagineManager;
+ protected $imagineCacheManager;
- /**
- * @var FontCollection
- */
- private $fontCollection;
-
- public function injectThings(ContainerInterface $container, FileLocatorInterface $fileLocator, FontCollection $fontCollection, $kernelRootDir)
- {
+ public function injectThings(
+ ContainerInterface $container,
+ FileLocatorInterface $fileLocator,
+ $kernelRootDir
+ ) {
$this->container = $container;
$this->fileLocator = $fileLocator;
- $this->fontCollection = $fontCollection;
$this->zikulaRoot = realpath($kernelRootDir . '/..');
- /** @var \SystemPlugin_Imagine_Manager $imagineManager */
- $imagineManager = $this->container->get('systemplugin.imagine.manager');
- $imagineManager->setModule('CmfcmfMediaModule');
- $this->imagineManager = $imagineManager;
+ $this->imagineCacheManager = $this->container->get('liip_imagine.cache.manager');
}
public function getPathToFile($identifier)
@@ -66,173 +61,73 @@ public function getPathToFile($identifier)
public function getUrlToFile($identifier)
{
- return \System::getBaseUri() . '/' . $this->getPathToFile($identifier);
+ return $this->getBaseUri() . '/' . $this->getPathToFile($identifier);
}
- protected function getPreset(AbstractFileEntity $entity, $file, $width, $height, $mode, $optimize)
+ protected function getImagineRuntimeOptions(AbstractFileEntity $entity, $file, $width, $height, $mode, $optimize)
{
- $watermarkId = '';
- $watermark = $entity->getCollection()->getWatermark();
- if ($watermark !== null) {
- $watermarkId = ', w ' . $watermark->getId();
- }
-
- if ($height == 'original' || $width == 'original') {
+ if ('original' == $height || 'original' == $width) {
$size = getimagesize($entity->getPath());
- if ($width == 'original') {
+ if ('original' == $width) {
$width = $size[0];
}
- if ($height == 'original') {
+ if ('original' == $height) {
$height = $size[1];
}
}
- $preset = new \SystemPlugin_Imagine_Preset("CmfcmfMediaModule " . (string)$optimize . 'x' . substr($mode, 0, 1) . "x{$width}x{$height}x" . $watermarkId, [
- 'mode' => $mode,
- 'width' => $width,
- 'height' => $height,
- '__module' => 'CmfcmfMediaModule',
- '__transformation' => $this->getTransformation($entity, $file, $width, $height, $mode, $optimize)
- ]);
-
- return $preset;
- }
-
- protected function getTransformation(AbstractFileEntity $entity, $file, $width, $height, $mode, $optimize)
- {
- $transformation = new \Imagine\Filter\Transformation();
- if ($optimize) {
- // Optimize for web and rotate the images (after thumbnail creation).
- $transformation
- ->add(new \Imagine\Filter\Basic\Autorotate(), 101)
- ->add(new \Imagine\Filter\Basic\WebOptimization(), 2)
- ;
- }
-
$watermark = $entity->getCollection()->getWatermark();
- if ($watermark === null) {
- // The image shall not be watermarked.
- return $transformation;
- }
-
- $imagine = $this->imagineManager->getImagine();
-
- // Generate the watermark image. It will already be correctly sized
- // for the thumbnail.
- if ($mode == 'outbound') {
- $wWidth = $width;
- $wHeight = $height;
- } elseif ($mode == 'inset') {
- $imageSize = getimagesize($file);
-
- $ratios = [
- $width / $imageSize[0],
- $height / $imageSize[1]
- ];
- $wWidth = min($ratios) * $imageSize[0];
- $wHeight = min($ratios) * $imageSize[1];
- } else {
- throw new \LogicException();
- }
-
- // Check whether the image is big enough to be watermarked.
- if ($watermark->getMinSizeX() !== null && $wWidth < $watermark->getMinSizeX()) {
- return $transformation;
- }
- if ($watermark->getMinSizeY() !== null && $wHeight < $watermark->getMinSizeY()) {
- return $transformation;
- }
-
- $watermarkImage = $watermark->getImagineImage($imagine, $this->fontCollection, $wWidth, $wHeight);
- $watermarkSize = $watermarkImage->getSize();
-
- // Calculate watermark position. If the position is negative, handle
- // it as an offset from the bottom / the right side of the image.
- $x = $watermark->getPositionX();
- $y = $watermark->getPositionY();
- if ($x < 0) {
- $x += $wWidth - $watermarkSize->getWidth();
- }
- if ($y < 0) {
- $y += $wHeight - $watermarkSize->getHeight();
- }
-
- // If the watermark still exceeds the image's width or height, resize the watermark.
- if ($x < 0 || $y < 0 || $x + $watermarkSize->getWidth() > $wWidth || $y + $watermarkSize->getHeight() > $wHeight) {
- $xOffset = 0;
- if ($x < 0) {
- $xOffset = $x * -1;
- }
- $yOffset = 0;
- if ($y < 0) {
- $yOffset = $y * -1;
- }
-
- $ratios = [
- ($watermarkSize->getWidth() - $xOffset) / $watermarkSize->getWidth(),
- ($watermarkSize->getHeight() - $yOffset) / $watermarkSize->getHeight()
- ];
- $watermarkSize = $watermarkSize->scale(min($ratios));
- $watermarkImage->resize($watermarkSize);
-
- $x = round($watermark->getPositionX() + $wWidth - $watermarkSize->getWidth());
- $y = round($watermark->getPositionY() + $wHeight - $watermarkSize->getHeight());
-
- $xOffset = 0;
- if ($x + $watermarkSize->getWidth() > $wWidth) {
- $xOffset = $x + $watermarkSize->getWidth() - $wWidth;
- }
- $yOffset = 0;
- if ($y + $watermarkSize->getHeight() > $wHeight) {
- $yOffset = $y + $watermarkSize->getHeight() - $wHeight;
- }
- $ratios = [
- ($watermarkSize->getWidth() - $xOffset) / $watermarkSize->getWidth(),
- ($watermarkSize->getHeight() - $yOffset) / $watermarkSize->getHeight()
- ];
- $watermarkImage->resize($watermarkSize->scale(min($ratios)));
- }
-
- $point = new \Imagine\Image\Point($x, $y);
- $transformation
- ->add(new \Imagine\Filter\Basic\Paste($watermarkImage, $point), 100)
- ;
-
- return $transformation;
+ $watermarkId = null !== $watermark ? $watermark->getId() : null;
+
+ $options = [
+ 'thumbnail' => [
+ 'size' => [$width, $height],
+ 'mode' => ($mode ? $mode : ImageInterface::THUMBNAIL_OUTBOUND),
+ 'extension' => null // file extension for thumbnails (jpg, png, gif; null for original file type)
+ ],
+ 'cmfcmfmediamodule.custom_image_filter' => [
+ 'watermark' => $watermarkId,
+ 'file' => $file,
+ 'width' => $width,
+ 'height' => $height,
+ 'mode' => $mode,
+ 'optimize' => $optimize
+ ]
+ ];
+
+ return $options;
}
- protected function getIconThumbnailByFileExtension(AbstractFileEntity $entity, $width, $height, $format = 'html', $mode = 'outbound', $optimize = true, $forceExtension = false)
+ protected function getIconThumbnailByFileExtension(AbstractFileEntity $entity, $width, $height, $format = 'html', $mode = ImageInterface::THUMBNAIL_OUTBOUND, $optimize = true, $forceExtension = false)
{
return false;
// @todo Re-enable?
- if (!in_array($mode, ['inset', 'outbound'])) {
- throw new \InvalidArgumentException('Invalid mode requested.');
+ if (!in_array($mode, [ImageInterface::THUMBNAIL_INSET, ImageInterface::THUMBNAIL_OUTBOUND])) {
+ $mode = ImageInterface::THUMBNAIL_INSET;
}
- $mode = 'inset';
$availableSizes = [16, 32, 48, 512];
+ $chosenSize = 0;
foreach ($availableSizes as $size) {
if ($width <= $size && $height <= $size) {
break;
}
+ $chosenSize = $size;
}
$extension = $forceExtension ? $forceExtension : pathinfo($entity->getFileName(), PATHINFO_EXTENSION);
- $icon = '@CmfcmfMediaModule/Resources/public/images/file-icons/' . $size . 'px/' . $extension . '.png';
+ $icon = '@CmfcmfMediaModule/Resources/public/images/file-icons/' . $chosenSize . 'px/' . $extension . '.png';
try {
$path = $this->getPathToFile($icon);
} catch (\InvalidArgumentException $e) {
- $icon = '@CmfcmfMediaModule/Resources/public/images/file-icons/' . $size . 'px/_blank.png';
+ $icon = '@CmfcmfMediaModule/Resources/public/images/file-icons/' . $chosenSize . 'px/_blank.png';
$path = $this->getPathToFile($icon);
}
- $this->imagineManager->setPreset(
- $this->getPreset($entity, $path, $width, $height, $mode, $optimize)
- );
-
- $path = $this->imagineManager->getThumb($path, $entity->getImagineId());
+ $imagineOptions = $this->getImagineRuntimeOptions($entity, $path, $width, $height, $mode, $optimize);
+ $path = $this->imagineCacheManager->getBrowserPath($path, 'zkroot', $imagineOptions);
- $url = \System::getBaseUri() . '/' . $path;
+ $url = $this->getBaseUri() . '/' . $path;
switch ($format) {
case 'url':
return $url;
@@ -255,4 +150,9 @@ public function getOriginalWithWatermark(AbstractFileEntity $entity, $mode, $opt
throw new \LogicException();
}
}
+
+ protected function getBaseUri()
+ {
+ return $this->requestStack->getCurrentRequest()->getBasePath();
+ }
}
diff --git a/MediaType/AbstractMediaType.php b/MediaType/AbstractMediaType.php
index edc3db92..8865f336 100644
--- a/MediaType/AbstractMediaType.php
+++ b/MediaType/AbstractMediaType.php
@@ -13,9 +13,9 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
-use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\TranslatorInterface;
-use Zikula\ExtensionsModule\Api\VariableApi;
+use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
abstract class AbstractMediaType implements MediaTypeInterface
{
@@ -30,15 +30,39 @@ abstract class AbstractMediaType implements MediaTypeInterface
protected $translator;
/**
- * @var VariableApi
+ * @var VariableApiInterface
*/
- private $variableApi;
+ protected $variableApi;
- public function __construct(EngineInterface $renderEngine, TranslatorInterface $translator, VariableApi $variableApi)
- {
+ /**
+ * @var RequestStack
+ */
+ protected $requestStack;
+
+ /**
+ * @var string
+ */
+ protected $dataDirectory;
+
+ /**
+ * @param EngineInterface $renderEngine
+ * @param TranslatorInterface $translator
+ * @param VariableApiInterface $variableApi
+ * @param RequestStack $requestStack
+ * @param string $dataDirectory
+ */
+ public function __construct(
+ EngineInterface $renderEngine,
+ TranslatorInterface $translator,
+ VariableApiInterface $variableApi,
+ RequestStack $requestStack,
+ $dataDirectory
+ ) {
$this->renderEngine = $renderEngine;
$this->translator = $translator;
$this->variableApi = $variableApi;
+ $this->requestStack = $requestStack;
+ $this->dataDirectory = $dataDirectory;
}
public function getVar($name, $default)
@@ -100,7 +124,12 @@ public function isEmbeddable()
public function getEmbedCode(AbstractMediaEntity $entity, $size = 'full')
{
- return $this->renderFullpage($entity) . $entity->getAttribution();
+ $attribution = '';
+ if (null !== $entity->getAttribution()) {
+ $attribution = '' . $this->__f('By %s', ['%s' => $entity->getAttribution()], 'cmfcmfmediamodule') . '
';
+ }
+
+ return $this->renderFullpage($entity) . $attribution;
}
public function getExtendedMetaInformation(AbstractMediaEntity $entity)
@@ -139,12 +168,12 @@ public function doJsonGetRequest($url)
return $result;
}
- public function getEntityFromWeb(Request $request)
+ public function getEntityFromWeb()
{
$entity = $this->getEntityClass();
- $entity = new $entity();
+ $entity = new $entity($this->requestStack, $this->dataDirectory);
- $settings = json_decode($request->request->get('settings'), true);
+ $settings = json_decode($this->requestStack->getCurrentRequest()->request->get('settings'), true);
foreach ($settings as $name => $value) {
$setter = 'set' . ucfirst($name);
$entity->$setter($value);
diff --git a/MediaType/Deezer.php b/MediaType/Deezer.php
index a493db91..a45bf2c4 100644
--- a/MediaType/Deezer.php
+++ b/MediaType/Deezer.php
@@ -13,7 +13,6 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\DeezerEntity;
-use Symfony\Component\HttpFoundation\Request;
class Deezer extends AbstractMediaType implements WebMediaTypeInterface, PasteMediaTypeInterface
{
@@ -38,7 +37,7 @@ public function getIcon()
*/
public function matchesPaste($pastedText)
{
- return $this->getParametersFromPastedText($pastedText) !== false ? 10 : 0;
+ return false !== $this->getParametersFromPastedText($pastedText) ? 10 : 0;
}
/**
@@ -47,15 +46,15 @@ public function matchesPaste($pastedText)
public function getEntityFromPaste($pastedText)
{
$parameters = $this->getParametersFromPastedText($pastedText);
- if ($parameters === false) {
+ if (false === $parameters) {
throw new \RuntimeException();
}
- $entity = new DeezerEntity();
+ $entity = new DeezerEntity($this->requestStack, $this->dataDirectory);
if (isset($parameters['title'])) {
$entity->setTitle($parameters['title']);
}
- $entity->setUrl('http://www.deezer.com');
+ $entity->setUrl('https://www.deezer.com');
$entity->setMusicId($parameters['musicId']);
$entity->setMusicType($parameters['musicType']);
@@ -70,14 +69,14 @@ private function getParametersFromPastedText($pastedText)
$parameters = [];
$regex = '#deezer\.com/(.*?)/(\d+)#';
preg_match($regex, $pastedText, $matches);
- if (count($matches) == 3) {
+ if (3 == count($matches)) {
$parameters['musicId'] = $matches[2];
$parameters['musicType'] = $matches[1];
$parameters['showPlaylist'] = false;
} else {
$regex = '#src=(?:"|\')((?:.*?)deezer\.com/plugins/player(?:.*?))(?:"|\')#';
preg_match($regex, $pastedText, $matches);
- if (count($matches) != 2) {
+ if (2 != count($matches)) {
return false;
}
$url = htmlspecialchars_decode($matches[1]);
@@ -88,7 +87,7 @@ private function getParametersFromPastedText($pastedText)
}
$parameters['musicId'] = $queryParams['id'];
$parameters['musicType'] = $queryParams['type'];
- if ($parameters['musicType'] == 'tracks') {
+ if ('tracks' == $parameters['musicType']) {
$parameters['musicType'] = 'track';
}
if (isset($queryParams['title'])) {
@@ -117,7 +116,7 @@ public function renderFullpage(AbstractMediaEntity $entity)
$title = urldecode($entity->getTitle());
$id = $entity->getMusicId();
$type = $entity->getMusicType();
- if ($type == 'track') {
+ if ('track' == $type) {
$type = 'tracks';
}
$url = "http://www.deezer.com/plugins/player?format=classic&autoplay=false&playlist=$playlist&width=700&height=$height&color=$color&layout=dark&size=medium&type=$type&id=$id&title=$title&app_id=1";
@@ -128,10 +127,10 @@ public function renderFullpage(AbstractMediaEntity $entity)
]);
}
- public function getEntityFromWeb(Request $request)
+ public function getEntityFromWeb()
{
/** @var DeezerEntity $entity */
- $entity = parent::getEntityFromWeb($request);
+ $entity = parent::getEntityFromWeb();
$this->addExtraData($entity);
@@ -143,7 +142,7 @@ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $form
/** @var DeezerEntity $entity */
$type = $entity->getMusicType();
$id = $entity->getMusicId();
- if ($type == 'track') {
+ if ('track' == $type) {
$type = 'album';
$id = $entity->getExtraData()['album']['id'];
}
@@ -151,7 +150,7 @@ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $form
//if ($mode == 'inset') {
// $size = max($width, $height);
//} else if ($mode == 'outbound') {
- $size = min($width, $height);
+ $size = min($width, $height);
//}
// @todo Ask Deezer whether it is allowed to crop the images.
$url = "http://api.deezer.com/$type/$id/image?size=" . $size;
@@ -170,9 +169,9 @@ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $form
*/
public function addExtraData(DeezerEntity $entity)
{
- if ($entity->getMusicType() == 'track' || $entity->getMusicType() == 'album') {
+ if ('track' == $entity->getMusicType() || 'album' == $entity->getMusicType()) {
$track = $this->doJsonGetRequest('http://api.deezer.com/' . $entity->getMusicType() . '/' . $entity->getMusicId());
- if ($entity->getMusicType() == 'track') {
+ if ('track' == $entity->getMusicType()) {
$entity->addExtraData(['album' => $track['album']]);
}
$entity->addExtraData(['artist' => $track['artist']]);
@@ -183,11 +182,11 @@ public function getFormOptions(AbstractMediaEntity $entity)
{
/** @var DeezerEntity $entity */
return [
- 'showPlaylistCheckbox' => $entity->getMusicType() == 'playlist'
+ 'showPlaylistCheckbox' => 'playlist' == $entity->getMusicType()
];
}
- public function getSearchResults(Request $request, $q, $dropdownValue = null)
+ public function getSearchResults($q, $dropdownValue = null)
{
// TODO: Implement getSearchResults() method.
}
diff --git a/MediaType/Flickr.php b/MediaType/Flickr.php
index 632713fd..cab6bc97 100644
--- a/MediaType/Flickr.php
+++ b/MediaType/Flickr.php
@@ -13,7 +13,6 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\FlickrEntity;
-use Symfony\Component\HttpFoundation\Request;
class Flickr extends AbstractMediaType implements WebMediaTypeInterface
{
@@ -27,7 +26,7 @@ public function getDisplayName()
public function isEnabled()
{
- return \ModUtil::getVar('CmfcmfMediaModule', 'flickrApiKey', '') != "";
+ return "" != $this->variableApi->get('CmfcmfMediaModule', 'flickrApiKey', '');
}
/**
@@ -53,7 +52,7 @@ public function renderFullpage(AbstractMediaEntity $entity)
protected function getWebCreationTemplateArguments()
{
return [
- 'flickrId' => \ModUtil::getVar('CmfcmfMediaModule', 'flickrApiKey')
+ 'flickrId' => $this->variableApi->get('CmfcmfMediaModule', 'flickrApiKey')
];
}
@@ -63,7 +62,7 @@ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $form
return false;
}
- public function getSearchResults(Request $request, $q, $dropdownValue = null)
+ public function getSearchResults($q, $dropdownValue = null)
{
// TODO: Implement getSearchResults() method.
}
diff --git a/MediaType/Image.php b/MediaType/Image.php
index 81103a10..0f239c52 100644
--- a/MediaType/Image.php
+++ b/MediaType/Image.php
@@ -14,6 +14,7 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractFileEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\ImageEntity;
+use Imagine\Image\ImageInterface;
use Symfony\Component\HttpFoundation\File\File;
class Image extends AbstractFileMediaType implements UploadableMediaTypeInterface
@@ -124,7 +125,7 @@ private function didFlashFire($flash)
// 32: NoFlashFunction
// 64: RedEyeReductionMode
- return ($flash & 1) != 0;
+ return 0 != ($flash & 1);
}
private function convertMeteringMode($meteringMode)
@@ -152,7 +153,7 @@ public function canUpload(File $file)
}
/**
- * @return array A list of supported mime types.
+ * @return array a list of supported mime types
*/
private function getSupportedMimeTypes()
{
@@ -171,20 +172,17 @@ public function mightUpload($mimeType, $size, $name)
return in_array($mimeType, $this->getSupportedMimeTypes()) ? 5 : 0;
}
- public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $format = 'html', $mode = 'outbound', $optimize = true)
+ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $format = 'html', $mode = ImageInterface::THUMBNAIL_OUTBOUND, $optimize = true)
{
- /** @var ImageEntity $entity */
- if (!in_array($mode, ['inset', 'outbound'])) {
- throw new \InvalidArgumentException('Invalid mode requested.');
+ if (!in_array($mode, [ImageInterface::THUMBNAIL_INSET, ImageInterface::THUMBNAIL_OUTBOUND])) {
+ $mode = ImageInterface::THUMBNAIL_INSET;
}
- $this->imagineManager->setPreset(
- $this->getPreset($entity, $entity->getPath(), $width, $height, $mode, $optimize)
- );
-
- $path = $this->imagineManager->getThumb($entity->getPath(), $entity->getImagineId());
+ /** @var ImageEntity $entity */
+ $path = $entity->getPath();
+ $imagineOptions = $this->getImagineRuntimeOptions($entity, $path, $width, $height, $mode, $optimize);
+ $url = $this->imagineCacheManager->getBrowserPath($path, 'zkroot', $imagineOptions);
- $url = \System::getBaseUri() . '/' . $path;
switch ($format) {
case 'url':
return $url;
@@ -211,8 +209,8 @@ public function getEmbedCode(AbstractMediaEntity $entity, $size = 'full')
$code = $this->getThumbnail($entity, 250, 150, 'html', 'inset');
break;
}
- if ($entity->getAttribution() != null) {
- $code .= '' . $entity->getAttribution() . '
';
+ if (null !== $entity->getAttribution()) {
+ $code .= '' . $this->translator->__f('By %s', ['%s' => $entity->getAttribution()], 'cmfcmfmediamodule') . '
';
}
return $code;
diff --git a/MediaType/Pdf.php b/MediaType/Pdf.php
index b354769b..e1952097 100644
--- a/MediaType/Pdf.php
+++ b/MediaType/Pdf.php
@@ -82,9 +82,4 @@ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $form
//throw new \LogicException();
//}
}
-
- public function isEmbeddable()
- {
- return false;
- }
}
diff --git a/MediaType/SoundCloud.php b/MediaType/SoundCloud.php
index b3b0620c..23f84f84 100644
--- a/MediaType/SoundCloud.php
+++ b/MediaType/SoundCloud.php
@@ -13,7 +13,6 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\SoundCloudEntity;
-use Symfony\Component\HttpFoundation\Request;
class SoundCloud extends AbstractMediaType implements WebMediaTypeInterface, PasteMediaTypeInterface
{
@@ -27,7 +26,7 @@ public function getDisplayName()
public function isEnabled()
{
- return \ModUtil::getVar('CmfcmfMediaModule', 'soundCloudApiKey', '') != "";
+ return '' != $this->variableApi->get('CmfcmfMediaModule', 'soundCloudApiKey', '');
}
/**
@@ -43,7 +42,7 @@ public function getIcon()
*/
public function matchesPaste($pastedText)
{
- return $this->getTrackFromPastedText($pastedText) !== false ? 10 : 0;
+ return false !== $this->getTrackFromPastedText($pastedText) ? 10 : 0;
}
/**
@@ -52,12 +51,12 @@ public function matchesPaste($pastedText)
public function getEntityFromPaste($pastedText)
{
$trackId = $this->getTrackFromPastedText($pastedText);
- if ($trackId === false) {
+ if (false === $trackId) {
throw new \RuntimeException();
}
- $entity = new SoundCloudEntity();
- $entity->setUrl('http://www.soundcloud.com');
+ $entity = new SoundCloudEntity($this->requestStack, $this->dataDirectory);
+ $entity->setUrl('https://soundcloud.com/');
$entity->setMusicId($trackId);
return $entity;
@@ -87,7 +86,7 @@ private function getTrackFromPastedText($pastedText)
public function getWebCreationTemplateArguments()
{
return [
- 'clientId' => \ModUtil::getVar('CmfcmfMediaModule', 'soundCloudApiKey')
+ 'clientId' => $this->variableApi->get('CmfcmfMediaModule', 'soundCloudApiKey')
];
}
@@ -114,7 +113,7 @@ public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $form
return false;
}
- public function getSearchResults(Request $request, $q, $dropdownValue = null)
+ public function getSearchResults($q, $dropdownValue = null)
{
// TODO: Implement getSearchResults() method.
}
diff --git a/MediaType/Twitter.php b/MediaType/Twitter.php
index fc8dc9a7..c6f4859e 100644
--- a/MediaType/Twitter.php
+++ b/MediaType/Twitter.php
@@ -13,7 +13,6 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\TwitterEntity;
-use Symfony\Component\HttpFoundation\Request;
class Twitter extends AbstractMediaType implements WebMediaTypeInterface, PasteMediaTypeInterface
{
@@ -28,10 +27,10 @@ public function getDisplayName()
public function isEnabled()
{
return
- \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiKey') != "" &&
- \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiSecret') != "" &&
- \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiAccessToken') != "" &&
- \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiAccessTokenSecret') != ""
+ '' != $this->variableApi->get('CmfcmfMediaModule', 'twitterApiKey') &&
+ '' != $this->variableApi->get('CmfcmfMediaModule', 'twitterApiSecret') &&
+ '' != $this->variableApi->get('CmfcmfMediaModule', 'twitterApiAccessToken') &&
+ '' != $this->variableApi->get('CmfcmfMediaModule', 'twitterApiAccessTokenSecret')
;
}
@@ -48,7 +47,7 @@ public function getIcon()
*/
public function matchesPaste($pastedText)
{
- return $this->extractTweetIdFromPaste($pastedText) !== false ? 10 : 0;
+ return false !== $this->extractTweetIdFromPaste($pastedText) ? 10 : 0;
}
/**
@@ -56,10 +55,10 @@ public function matchesPaste($pastedText)
*/
public function getEntityFromPaste($pastedText)
{
- $entity = new TwitterEntity();
+ $entity = new TwitterEntity($this->requestStack, $this->dataDirectory);
$tweetId = $this->extractTweetIdFromPaste($pastedText);
- if ($tweetId === false) {
+ if (false === $tweetId) {
throw new \RuntimeException();
}
$tweetInfo = $this->getTweetInfo($tweetId);
@@ -79,7 +78,7 @@ public function getEntityFromPaste($pastedText)
private function extractTweetIdFromPaste($pastedText)
{
preg_match('#twitter\.com/[A-z]+/status/(\d+)#', $pastedText, $results);
- if (count($results) == 2) {
+ if (2 == count($results)) {
return $results[1];
} else {
return false;
@@ -117,7 +116,7 @@ public function getEmbedCode(AbstractMediaEntity $entity, $size = 'full')
]) . '
';
}
- public function getSearchResults(Request $request, $q, $dropdownValue = null)
+ public function getSearchResults($q, $dropdownValue = null)
{
$q = str_replace('&', '', $q);
$q = str_replace('?', '', $q);
@@ -130,7 +129,7 @@ public function getSearchResults(Request $request, $q, $dropdownValue = null)
// 'results' => [],
// 'more' => false
//];
- if ($dropdownValue === null || $dropdownValue == 'tweets') {
+ if (null === $dropdownValue || 'tweets' == $dropdownValue) {
$tweetResults = $this->getTweetSearchResults($q);
}
//if ($dropdownValue === null || $dropdownValue == 'users') {
@@ -194,13 +193,11 @@ private function getTweetInfo($tweetId)
*/
private function getTwitterApi()
{
- require_once __DIR__ . '/../vendor/autoload.php';
-
$api = new \TwitterAPIExchange([
- 'oauth_access_token' => \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiAccessToken'),
- 'oauth_access_token_secret' => \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiAccessTokenSecret'),
- 'consumer_key' => \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiKey'),
- 'consumer_secret' => \ModUtil::getVar('CmfcmfMediaModule', 'twitterApiSecret')
+ 'oauth_access_token' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiAccessToken'),
+ 'oauth_access_token_secret' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiAccessTokenSecret'),
+ 'consumer_key' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiKey'),
+ 'consumer_secret' => $this->variableApi->get('CmfcmfMediaModule', 'twitterApiSecret')
]);
return $api;
diff --git a/MediaType/Url.php b/MediaType/Url.php
index aa389143..ac79cc71 100644
--- a/MediaType/Url.php
+++ b/MediaType/Url.php
@@ -39,7 +39,7 @@ public function getIcon()
*/
public function matchesPaste($pastedText)
{
- return filter_var($pastedText, FILTER_VALIDATE_URL) !== false ? 1 : 0;
+ return false !== filter_var($pastedText, FILTER_VALIDATE_URL) ? 1 : 0;
}
/**
@@ -47,7 +47,7 @@ public function matchesPaste($pastedText)
*/
public function getEntityFromPaste($pastedText)
{
- $entity = new UrlEntity();
+ $entity = new UrlEntity($this->requestStack, $this->dataDirectory);
$entity->setUrl($pastedText);
return $entity;
diff --git a/MediaType/Video.php b/MediaType/Video.php
index d400e42d..4ccfd954 100644
--- a/MediaType/Video.php
+++ b/MediaType/Video.php
@@ -35,8 +35,8 @@ public function getIcon()
public function renderFullpage(AbstractMediaEntity $entity)
{
- $clientID = \ModUtil::getVar('CmfcmfMediaModule', 'googleApiOAuthClientID');
- $clientSecret = \ModUtil::getVar('CmfcmfMediaModule', 'googleApiOAuthClientSecret');
+ $clientID = $this->variableApi->get('CmfcmfMediaModule', 'googleApiOAuthClientID');
+ $clientSecret = $this->variableApi->get('CmfcmfMediaModule', 'googleApiOAuthClientSecret');
return $this->renderEngine->render('CmfcmfMediaModule:MediaType/Video:fullpage.html.twig', [
'entity' => $entity,
@@ -131,7 +131,7 @@ public function canUpload(File $file)
if (in_array($mimeType, $this->getSupportedMimeTypes())) {
return 5;
}
- if ($file->getMimeType() == 'application/ogg') {
+ if ('application/ogg' == $file->getMimeType()) {
// This could be a video or audio file.
$meta = GenericMetadataReader::readMetadata($file->getPathname());
if (isset($meta['video']['dataformat'])) {
@@ -143,7 +143,7 @@ public function canUpload(File $file)
}
/**
- * @return array A list of supported mime types.
+ * @return array a list of supported mime types
*/
private function getSupportedMimeTypes()
{
diff --git a/MediaType/WebMediaTypeInterface.php b/MediaType/WebMediaTypeInterface.php
index bc505de6..436edf2b 100644
--- a/MediaType/WebMediaTypeInterface.php
+++ b/MediaType/WebMediaTypeInterface.php
@@ -11,11 +11,9 @@
namespace Cmfcmf\Module\MediaModule\MediaType;
-use Symfony\Component\HttpFoundation\Request;
-
interface WebMediaTypeInterface
{
- public function getEntityFromWeb(Request $request);
+ public function getEntityFromWeb();
- public function getSearchResults(Request $request, $q, $dropdownValue = null);
+ public function getSearchResults($q, $dropdownValue = null);
}
diff --git a/MediaType/YouTube.php b/MediaType/YouTube.php
index d5e9c91d..aea89448 100644
--- a/MediaType/YouTube.php
+++ b/MediaType/YouTube.php
@@ -13,7 +13,6 @@
use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity;
use Cmfcmf\Module\MediaModule\Entity\Media\YouTubeEntity;
-use Symfony\Component\HttpFoundation\Request;
class YouTube extends AbstractMediaType implements WebMediaTypeInterface, PasteMediaTypeInterface
{
@@ -27,7 +26,7 @@ public function getDisplayName()
public function isEnabled()
{
- return \ModUtil::getVar('CmfcmfMediaModule', 'googleApiKey') != "";
+ return '' != $this->variableApi->get('CmfcmfMediaModule', 'googleApiKey');
}
/**
@@ -43,7 +42,7 @@ public function getIcon()
*/
public function matchesPaste($pastedText)
{
- return $this->extractYouTubeIdAndTypeFromPaste($pastedText) !== false ? 10 : 0;
+ return false !== $this->extractYouTubeIdAndTypeFromPaste($pastedText) ? 10 : 0;
}
/**
@@ -51,10 +50,10 @@ public function matchesPaste($pastedText)
*/
public function getEntityFromPaste($pastedText)
{
- $entity = new YouTubeEntity();
+ $entity = new YouTubeEntity($this->requestStack, $this->dataDirectory);
list($type, $id) = $this->extractYouTubeIdAndTypeFromPaste($pastedText);
- if ($id === false || !in_array($type, ['playlist', 'video', 'channel', true])) {
+ if (false === $id || !in_array($type, ['playlist', 'video', 'channel', true])) {
throw new \RuntimeException();
}
@@ -66,17 +65,17 @@ public function getEntityFromPaste($pastedText)
private function extractYouTubeIdAndTypeFromPaste($pastedText)
{
preg_match('#youtube\.com\/channel\/([a-zA-Z0-9_-]+)#', $pastedText, $results);
- if (count($results) == 2) {
+ if (2 == count($results)) {
return ['channel', $results[1]];
}
preg_match('#youtube(?:-nocookie)?\.com\/[a-zA-Z0-9_\-\/\=\?\&]+list=([a-zA-Z0-9_-]+)#', $pastedText, $results);
- if (count($results) == 2) {
+ if (2 == count($results)) {
return ['playlist', $results[1]];
}
preg_match('#(?:youtube(?:-nocookie)?\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})#', $pastedText, $results);
- if (count($results) == 2) {
+ if (2 == count($results)) {
return ['video', $results[1]];
}
@@ -118,7 +117,7 @@ public function getEmbedCode(AbstractMediaEntity $entity, $size = 'full')
]);
}
- public function getSearchResults(Request $request, $q, $dropdownValue = null)
+ public function getSearchResults($q, $dropdownValue = null)
{
$youtube = $this->getYouTubeApi();
@@ -234,11 +233,9 @@ private function setYouTubeDataByIdAndType(YouTubeEntity &$entity, $type, $id)
*/
private function getYouTubeApi()
{
- require_once __DIR__ . '/../vendor/autoload.php';
-
$client = new \Google_Client();
$client->setApplicationName('Zikula Media Module by @cmfcmf');
- $client->setDeveloperKey(\ModUtil::getVar('CmfcmfMediaModule', 'googleApiKey'));
+ $client->setDeveloperKey($this->variableApi->get('CmfcmfMediaModule', 'googleApiKey'));
return new \Google_Service_YouTube($client);
}
diff --git a/Metadata/GenericMetadataReader.php b/Metadata/GenericMetadataReader.php
index f928cef0..785c803e 100644
--- a/Metadata/GenericMetadataReader.php
+++ b/Metadata/GenericMetadataReader.php
@@ -21,11 +21,10 @@ class GenericMetadataReader
*
* @param string $file
*
- * @return array The metadata.
+ * @return array the metadata
*/
public static function readMetadata($file)
{
- require_once __DIR__ . '/../vendor/autoload.php';
$getID3 = new \getID3();
$meta = $getID3->analyze($file);
\getid3_lib::CopyTagsToComments($meta);
diff --git a/README.md b/README.md
index fb5b7f6c..aa8debb0 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
-Zikula 1.4.3+ MediaModule by @cmfcmf
-====================================
+Zikula 2.0.11+ MediaModule by @cmfcmf
+=====================================
[](https://styleci.io/repos/43518681)
[](https://travis-ci.org/cmfcmf/MediaModule)
@@ -16,7 +16,7 @@ If you want to test the current version (potentially unstable!), download it fro
**Downloading directly from master would require you to execute `composer install --no-dev`.**
## Information
-Read all about the module [at it's website](http://cmfcmf.github.io/MediaModule).
+Read all about the module [at it's website](https://cmfcmf.github.io/MediaModule).
The module supports many media types natively (images, plaintext, MarkDown, videos, audio, pdf, …)
and further types can be added with ease!
@@ -44,10 +44,9 @@ If you do so, it's going to break URLs.
If you find a bug or have problems, please [create an issue](https://github.com/cmfcmf/MediaModule/issues/new)!
## Extracting translations
-Add `require_once __DIR__ . '/../modules/cmfcmf/media-module/vendor/autoload.php;` to `src/app/autoload.php` and then run
-```
-php app/console translation:extract --enable-extractor=jms_i18n_routing --dir ./modules/cmfcmf/media-module --exclude-dir vendor --output-dir ./modules/cmfcmf/media-module/Resources/translations --keep --output-format=pot de
-```
+Add `require_once __DIR__ . '/../modules/cmfcmf/media-module/vendor/autoload.php';` to `src/app/autoload.php` and then run
+
+`php -dmemory_limit=2G bin/console translation:extract en --bundle=CmfcmfMediaModule --enable-extractor=jms_i18n_routing --output-format=po --exclude-dir=vendor`
## License and module development
diff --git a/Resources/config/collectionpermissions.yml b/Resources/config/collectionpermissions.yml
index 3c52d6f2..8cf7db03 100644
--- a/Resources/config/collectionpermissions.yml
+++ b/Resources/config/collectionpermissions.yml
@@ -1,21 +1,26 @@
services:
- cmfcmf_media_module.collection_permission.container:
- class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionContainer
+ cmfcmf_media_module.collection_permission.container:
+ class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\CollectionPermissionContainer
- cmfcmf_media_module.collection_permission.user:
- class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\UserCollectionPermission
- arguments: [@translator]
- tags:
- - { name: cmfcmf_media_module.collection_permission }
+ cmfcmf_media_module.collection_permission.group:
+ class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\GroupCollectionPermission
+ arguments:
+ - '@translator'
+ - '@zikula_users_module.current_user'
+ - '@zikula_groups_module.group_repository'
+ tags: ['cmfcmf_media_module.collection_permission']
- cmfcmf_media_module.collection_permission.group:
- class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\GroupCollectionPermission
- arguments: [@translator]
- tags:
- - { name: cmfcmf_media_module.collection_permission }
+ cmfcmf_media_module.collection_permission.owner:
+ class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\OwnerCollectionPermission
+ arguments:
+ - '@translator'
+ - '@zikula_users_module.current_user'
+ tags: ['cmfcmf_media_module.collection_permission']
- cmfcmf_media_module.collection_permission.owner:
- class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\OwnerCollectionPermission
- arguments: [@translator]
- tags:
- - { name: cmfcmf_media_module.collection_permission }
+ cmfcmf_media_module.collection_permission.user:
+ class: Cmfcmf\Module\MediaModule\Security\CollectionPermission\UserCollectionPermission
+ arguments:
+ - '@translator'
+ - '@zikula_users_module.current_user'
+ - '@zikula_users_module.user_repository'
+ tags: ['cmfcmf_media_module.collection_permission']
diff --git a/Resources/config/collectiontemplates.yml b/Resources/config/collectiontemplates.yml
index 5f71fa87..afbd474c 100644
--- a/Resources/config/collectiontemplates.yml
+++ b/Resources/config/collectiontemplates.yml
@@ -1,40 +1,36 @@
services:
- cmfcmf_media_module.collection_template.abstract_service:
- abstract: true
- arguments: [@templating, @translator]
+ cmfcmf_media_module.collection_template.abstract_service:
+ abstract: true
+ arguments:
+ - '@templating'
+ - '@translator'
- cmfcmf_media_module.collection_template.cards:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\CardsTemplate
- parent: cmfcmf_media_module.collection_template.abstract_service
- tags:
- - { name: cmfcmf_media_module.collection_template }
+ cmfcmf_media_module.collection_template.cards:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\CardsTemplate
+ parent: cmfcmf_media_module.collection_template.abstract_service
+ tags: ['cmfcmf_media_module.collection_template']
- cmfcmf_media_module.collection_template.slider:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\SliderTemplate
- parent: cmfcmf_media_module.collection_template.abstract_service
- tags:
- - { name: cmfcmf_media_module.collection_template }
+ cmfcmf_media_module.collection_template.slider:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\SliderTemplate
+ parent: cmfcmf_media_module.collection_template.abstract_service
+ tags: ['cmfcmf_media_module.collection_template']
- cmfcmf_media_module.collection_template.grid:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\GridTemplate
- parent: cmfcmf_media_module.collection_template.abstract_service
- tags:
- - { name: cmfcmf_media_module.collection_template }
+ cmfcmf_media_module.collection_template.grid:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\GridTemplate
+ parent: cmfcmf_media_module.collection_template.abstract_service
+ tags: ['cmfcmf_media_module.collection_template']
- cmfcmf_media_module.collection_template.table:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\TableTemplate
- parent: cmfcmf_media_module.collection_template.abstract_service
- tags:
- - { name: cmfcmf_media_module.collection_template }
+ cmfcmf_media_module.collection_template.table:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\TableTemplate
+ parent: cmfcmf_media_module.collection_template.abstract_service
+ tags: ['cmfcmf_media_module.collection_template']
- cmfcmf_media_module.collection_template.galleria:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\GalleriaTemplate
- parent: cmfcmf_media_module.collection_template.abstract_service
- tags:
- - { name: cmfcmf_media_module.collection_template }
+ cmfcmf_media_module.collection_template.galleria:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\GalleriaTemplate
+ parent: cmfcmf_media_module.collection_template.abstract_service
+ tags: ['cmfcmf_media_module.collection_template']
- cmfcmf_media_module.collection_template.lightgallery:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\LightGalleryTemplate
- parent: cmfcmf_media_module.collection_template.abstract_service
- tags:
- - { name: cmfcmf_media_module.collection_template }
+ cmfcmf_media_module.collection_template.lightgallery:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\LightGalleryTemplate
+ parent: cmfcmf_media_module.collection_template.abstract_service
+ tags: ['cmfcmf_media_module.collection_template']
diff --git a/Resources/config/contenttypes.yml b/Resources/config/contenttypes.yml
new file mode 100644
index 00000000..60a72ca7
--- /dev/null
+++ b/Resources/config/contenttypes.yml
@@ -0,0 +1,32 @@
+services:
+ # Content types
+ Cmfcmf\Module\MediaModule\ContentType\CollectionType:
+ parent: zikula.content_type.base
+ shared: false
+ calls:
+ - [setEntityManager, ['@doctrine.orm.entity_manager']]
+ - [setSecurityManager, ['@cmfcmf_media_module.security_manager']]
+ - [setSelectedTemplateFactory, ['@cmfcmf_media_module.collection_template.selected_factory']]
+ - [setMediaTypeCollection, ['@cmfcmf_media_module.media_type_collection']]
+ tags: ['zikula.content_type']
+ Cmfcmf\Module\MediaModule\ContentType\Form\Type\CollectionType:
+ parent: zikula.content_type.form.base
+ arguments:
+ - '@cmfcmf_media_module.security_manager'
+ - '@doctrine.orm.entity_manager'
+ tags: ['form.type']
+ Cmfcmf\Module\MediaModule\ContentType\MediaType:
+ parent: zikula.content_type.base
+ shared: false
+ calls:
+ - [setEntityManager, ['@doctrine.orm.entity_manager']]
+ - [setSecurityManager, ['@cmfcmf_media_module.security_manager']]
+ - [setMediaTypeCollection, ['@cmfcmf_media_module.media_type_collection']]
+ - [setEnableMediaViewCounter, ["@=service('zikula_extensions_module.api.variable').get('CmfcmfMediaModule', 'enableMediaViewCounter', false)"]]
+ tags: ['zikula.content_type']
+ Cmfcmf\Module\MediaModule\ContentType\Form\Type\MediaType:
+ parent: zikula.content_type.form.base
+ arguments:
+ - '@cmfcmf_media_module.security_manager'
+ - '@doctrine.orm.entity_manager'
+ tags: ['form.type']
diff --git a/Resources/config/formtypes.yml b/Resources/config/formtypes.yml
new file mode 100644
index 00000000..3a8ff580
--- /dev/null
+++ b/Resources/config/formtypes.yml
@@ -0,0 +1,196 @@
+services:
+ cmfcmf_media_module.form.type.color:
+ class: Cmfcmf\Module\MediaModule\Form\Type\ColorType
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.font:
+ class: Cmfcmf\Module\MediaModule\Form\Type\FontType
+ arguments:
+ - '@cmfcmf_media_module.font_collection'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.permission_level:
+ class: Cmfcmf\Module\MediaModule\Form\Type\PermissionLevelType
+ arguments:
+ - '@cmfcmf_media_module.security_manager'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.collection:
+ class: Cmfcmf\Module\MediaModule\Form\Collection\CollectionType
+ arguments:
+ - '@translator'
+ - '@cmfcmf_media_module.collection_template_collection'
+ - '@cmfcmf_media_module.security_manager'
+ - '@zikula_extensions_module.api.variable'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.collection_block:
+ class: Cmfcmf\Module\MediaModule\Form\Collection\CollectionBlockType
+ arguments:
+ - '@translator'
+ - '@cmfcmf_media_module.security_manager'
+ - '@doctrine.orm.entity_manager'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.collection_template:
+ class: Cmfcmf\Module\MediaModule\Form\CollectionTemplate\TemplateType
+ arguments:
+ - '@translator'
+ - '@cmfcmf_media_module.collection_template_collection'
+ - '@cmfcmf_media_module.collection_template.selected_factory'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.collection_template.galleria:
+ class: Cmfcmf\Module\MediaModule\Form\CollectionTemplate\GalleriaType
+ arguments:
+ - '@translator'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.collection_template.light_gallery:
+ class: Cmfcmf\Module\MediaModule\Form\CollectionTemplate\LightGalleryType
+ arguments:
+ - '@translator'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.media.base:
+ abstract: true
+ arguments:
+ - '@translator'
+ - '@cmfcmf_media_module.security_manager'
+ - '@zikula_extensions_module.api.variable'
+ - '@doctrine.orm.entity_manager'
+ cmfcmf_media_module.form.type.media.archive:
+ class: Cmfcmf\Module\MediaModule\Form\Media\ArchiveType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.audio:
+ class: Cmfcmf\Module\MediaModule\Form\Media\AudioType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.deezer:
+ class: Cmfcmf\Module\MediaModule\Form\Media\DeezerType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.flickr:
+ class: Cmfcmf\Module\MediaModule\Form\Media\FlickrType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.image:
+ class: Cmfcmf\Module\MediaModule\Form\Media\ImageType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.markdown:
+ class: Cmfcmf\Module\MediaModule\Form\Media\MarkdownType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.pdf:
+ class: Cmfcmf\Module\MediaModule\Form\Media\PdfType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.plaintext:
+ class: Cmfcmf\Module\MediaModule\Form\Media\PlaintextType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.sound_cloud:
+ class: Cmfcmf\Module\MediaModule\Form\Media\SoundCloudType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.twitter:
+ class: Cmfcmf\Module\MediaModule\Form\Media\TwitterType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.unknown:
+ class: Cmfcmf\Module\MediaModule\Form\Media\UnknownType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.url:
+ class: Cmfcmf\Module\MediaModule\Form\Media\UrlType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.video:
+ class: Cmfcmf\Module\MediaModule\Form\Media\VideoType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.web:
+ class: Cmfcmf\Module\MediaModule\Form\Media\WebType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.media.you_tube:
+ class: Cmfcmf\Module\MediaModule\Form\Media\YouTubeType
+ parent: cmfcmf_media_module.form.type.media.base
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.collection.permission.base:
+ abstract: true
+ arguments:
+ - '@translator'
+ - '@cmfcmf_media_module.security_manager'
+ - '@zikula_groups_module.group_repository'
+ - '@zikula_users_module.user_repository'
+ cmfcmf_media_module.form.type.collection.permission.group:
+ class: Cmfcmf\Module\MediaModule\Form\Collection\Permission\GroupPermissionType
+ parent: cmfcmf_media_module.form.type.collection.permission.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.collection.permission.owner:
+ class: Cmfcmf\Module\MediaModule\Form\Collection\Permission\OwnerPermissionType
+ parent: cmfcmf_media_module.form.type.collection.permission.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.collection.permission.password:
+ class: Cmfcmf\Module\MediaModule\Form\Collection\Permission\PasswordPermissionType
+ parent: cmfcmf_media_module.form.type.collection.permission.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.collection.permission.user:
+ class: Cmfcmf\Module\MediaModule\Form\Collection\Permission\UserPermissionType
+ parent: cmfcmf_media_module.form.type.collection.permission.base
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.import:
+ class: Cmfcmf\Module\MediaModule\Form\ImportType
+ arguments:
+ - '@translator'
+ - '@cmfcmf_media_module.security_manager'
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.importer.base:
+ class: Cmfcmf\Module\MediaModule\Form\Importer\AbstractImporterType
+ abstract: true
+ arguments:
+ - '@translator'
+ cmfcmf_media_module.form.type.importer.downloads:
+ class: Cmfcmf\Module\MediaModule\Form\Importer\DownloadsModuleType
+ parent: cmfcmf_media_module.form.type.importer.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.importer.server_directory:
+ class: Cmfcmf\Module\MediaModule\Form\Importer\ServerDirectoryType
+ parent: cmfcmf_media_module.form.type.importer.base
+ tags: ['form.type']
+ cmfcmf_media_module.form.type.importer.very_simple_downloads:
+ class: Cmfcmf\Module\MediaModule\Form\Importer\VerySimpleDownloadsModuleType
+ parent: cmfcmf_media_module.form.type.importer.base
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.license:
+ class: Cmfcmf\Module\MediaModule\Form\License\LicenseType
+ arguments:
+ - '@translator'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.settings:
+ class: Cmfcmf\Module\MediaModule\Form\SettingsType
+ arguments:
+ - '@translator'
+ - '@zikula_extensions_module.api.variable'
+ - '@doctrine.orm.entity_manager'
+ - '@cmfcmf_media_module.collection_template_collection'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.watermark.image:
+ class: Cmfcmf\Module\MediaModule\Form\Watermark\ImageWatermarkType
+ arguments:
+ - '@translator'
+ tags: ['form.type']
+
+ cmfcmf_media_module.form.type.watermark.text:
+ class: Cmfcmf\Module\MediaModule\Form\Watermark\TextWatermarkType
+ arguments:
+ - '@translator'
+ tags: ['form.type']
diff --git a/Resources/config/hooks.yml b/Resources/config/hooks.yml
new file mode 100644
index 00000000..ccb34bef
--- /dev/null
+++ b/Resources/config/hooks.yml
@@ -0,0 +1,76 @@
+services:
+ # Subscribers
+ cmfcmf_media_module.hook_subscriber.filter_hooks.collections:
+ class: Cmfcmf\Module\MediaModule\HookSubscriber\CollectionFilterHooksSubscriber
+ arguments:
+ - '@translator.default'
+ tags:
+ - { name: zikula.hook_subscriber, areaName: 'subscriber.cmfcmfmediamodule.filter_hooks.collections' }
+
+ cmfcmf_media_module.hook_subscriber.filter_hooks.media:
+ class: Cmfcmf\Module\MediaModule\HookSubscriber\MediaFilterHooksSubscriber
+ arguments:
+ - '@translator.default'
+ tags:
+ - { name: zikula.hook_subscriber, areaName: 'subscriber.cmfcmfmediamodule.filter_hooks.media' }
+
+ cmfcmf_media_module.hook_subscriber.form_aware_hook.collections:
+ class: Cmfcmf\Module\MediaModule\HookSubscriber\CollectionFormAwareHookSubscriber
+ arguments:
+ - "@translator.default"
+ tags:
+ - { name: zikula.hook_subscriber, areaName: 'subscriber.cmfcmfmediamodule.form_aware_hook.collections' }
+
+ cmfcmf_media_module.hook_subscriber.form_aware_hook.media:
+ class: Cmfcmf\Module\MediaModule\HookSubscriber\MediaFormAwareHookSubscriber
+ arguments:
+ - "@translator.default"
+ tags:
+ - { name: zikula.hook_subscriber, areaName: 'subscriber.cmfcmfmediamodule.form_aware_hook.media' }
+
+ cmfcmf_media_module.hook_subscriber.ui_hooks.collections:
+ class: Cmfcmf\Module\MediaModule\HookSubscriber\CollectionUiHooksSubscriber
+ arguments:
+ - '@translator.default'
+ tags:
+ - { name: zikula.hook_subscriber, areaName: 'subscriber.cmfcmfmediamodule.ui_hooks.collections' }
+
+ cmfcmf_media_module.hook_subscriber.ui_hooks.media:
+ class: Cmfcmf\Module\MediaModule\HookSubscriber\MediaUiHooksSubscriber
+ arguments:
+ - '@translator.default'
+ tags:
+ - { name: zikula.hook_subscriber, areaName: 'subscriber.cmfcmfmediamodule.ui_hooks.media' }
+
+
+ # Providers
+ cmfcmf_media_module.hook_provider.ui_hooks.base:
+ abstract: true
+ arguments:
+ - '@translator'
+ - '@doctrine.orm.default_entity_manager'
+ - '@request_stack'
+ - '@templating'
+ - '@cmfcmf_media_module.security_manager'
+
+ cmfcmf_media_module.hook_provider.ui_hooks.collections:
+ class: Cmfcmf\Module\MediaModule\HookProvider\CollectionUiHooksProvider
+ parent: cmfcmf_media_module.hook_provider.ui_hooks.base
+ calls:
+ - [setMediaTypeCollection, ['@cmfcmf_media_module.media_type_collection']]
+ tags:
+ - { name: zikula.hook_provider, areaName: 'provider.cmfcmfmediamodule.ui_hooks.collections' }
+
+ cmfcmf_media_module.hook_provider.ui_hooks.media:
+ class: Cmfcmf\Module\MediaModule\HookProvider\MediaUiHooksProvider
+ parent: cmfcmf_media_module.hook_provider.ui_hooks.base
+ calls:
+ - [setMediaTypeCollection, ['@cmfcmf_media_module.media_type_collection']]
+ tags:
+ - { name: zikula.hook_provider, areaName: 'provider.cmfcmfmediamodule.ui_hooks.media' }
+
+ cmfcmf_media_module.hook_provider.ui_hooks.licenses:
+ class: Cmfcmf\Module\MediaModule\HookProvider\LicenseUiHooksProvider
+ parent: cmfcmf_media_module.hook_provider.ui_hooks.base
+ tags:
+ - { name: zikula.hook_provider, areaName: 'provider.cmfcmfmediamodule.ui_hooks.licenses' }
diff --git a/Resources/config/importers.yml b/Resources/config/importers.yml
index 18369264..3d4cb9ff 100644
--- a/Resources/config/importers.yml
+++ b/Resources/config/importers.yml
@@ -1,33 +1,36 @@
services:
- cmfcmf_media_module.importer_collection:
- class: Cmfcmf\Module\MediaModule\Importer\ImporterCollection
+ cmfcmf_media_module.importer_collection:
+ class: Cmfcmf\Module\MediaModule\Importer\ImporterCollection
- cmfcmf_media_module.importer.abstract_service:
- abstract: true
- arguments: [@translator, @form.factory, @cmfcmf_media_module.media_type_collection, "@doctrine.orm.entity_manager"]
+ cmfcmf_media_module.importer.abstract_service:
+ abstract: true
+ arguments:
+ - '@translator'
+ - '@filesystem'
+ - '@form.factory'
+ - '@cmfcmf_media_module.media_type_collection'
+ - '@doctrine.orm.entity_manager'
+ - '@request_stack'
+ - '%datadir%'
- cmfcmf_media_module.importer.server_directory:
- parent: cmfcmf_media_module.importer.abstract_service
- class: Cmfcmf\Module\MediaModule\Importer\ServerDirectoryImporter
- calls:
- - [setUploadManager, [@stof_doctrine_extensions.uploadable.manager]]
- tags:
- - { name: 'cmfcmf_media_module.importer' }
+ cmfcmf_media_module.importer.server_directory:
+ parent: cmfcmf_media_module.importer.abstract_service
+ class: Cmfcmf\Module\MediaModule\Importer\ServerDirectoryImporter
+ calls:
+ - [setUploadManager, ['@stof_doctrine_extensions.uploadable.manager']]
+ tags: ['cmfcmf_media_module.importer']
- cmfcmf_media_module.importer.downloads_module:
- parent: cmfcmf_media_module.importer.abstract_service
- class: Cmfcmf\Module\MediaModule\Importer\DownloadsModuleImporter
- calls:
- - [setUploadManager, ["@stof_doctrine_extensions.uploadable.manager"]]
- - [setUserDataDirectory, ["%datadir%"]]
- tags:
- - { name: 'cmfcmf_media_module.importer' }
+ cmfcmf_media_module.importer.downloads_module:
+ parent: cmfcmf_media_module.importer.abstract_service
+ class: Cmfcmf\Module\MediaModule\Importer\DownloadsModuleImporter
+ calls:
+ - [setUploadManager, ['@stof_doctrine_extensions.uploadable.manager']]
+ tags: ['cmfcmf_media_module.importer']
- cmfcmf_media_module.importer.very_simple_downloads_module:
- parent: cmfcmf_media_module.importer.abstract_service
- class: Cmfcmf\Module\MediaModule\Importer\VerySimpleDownloadsModuleImporter
- calls:
- - [setUploadManager, ["@stof_doctrine_extensions.uploadable.manager"]]
- - [setUserDataDirectory, ["%datadir%"]]
- tags:
- - { name: 'cmfcmf_media_module.importer' }
+ cmfcmf_media_module.importer.very_simple_downloads_module:
+ parent: cmfcmf_media_module.importer.abstract_service
+ class: Cmfcmf\Module\MediaModule\Importer\VerySimpleDownloadsModuleImporter
+ calls:
+ - [setUploadManager, ['@stof_doctrine_extensions.uploadable.manager']]
+ - [setCategoryRegistryRepository, ['@zikula_categories_module.category_registry_repository']]
+ tags: ['cmfcmf_media_module.importer']
diff --git a/Resources/config/mediatypes.yml b/Resources/config/mediatypes.yml
index 467a4ddf..d7c8c888 100644
--- a/Resources/config/mediatypes.yml
+++ b/Resources/config/mediatypes.yml
@@ -1,96 +1,87 @@
services:
- cmfcmf_media_module.media_type.abstract_media:
- abstract: true
- arguments: ["@templating", "@translator", "@zikula_extensions_module.api.variable"]
+ cmfcmf_media_module.media_type.abstract_media:
+ abstract: true
+ arguments:
+ - '@templating'
+ - '@translator'
+ - '@zikula_extensions_module.api.variable'
+ - '@request_stack'
+ - '%datadir%'
- cmfcmf_media_module.media_type.abstract_file:
- parent: cmfcmf_media_module.media_type.abstract_media
- abstract: true
- calls:
- - [injectThings, [@service_container, @file_locator, @cmfcmf_media_module.font_collection, %kernel.root_dir%]]
+ cmfcmf_media_module.media_type.abstract_file:
+ parent: cmfcmf_media_module.media_type.abstract_media
+ abstract: true
+ calls:
+ - [injectThings, ['@service_container', '@file_locator', '%kernel.root_dir%']]
- cmfcmf_media_module.media_type.url:
- class: Cmfcmf\Module\MediaModule\MediaType\Url
- parent: cmfcmf_media_module.media_type.abstract_media
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.url:
+ class: Cmfcmf\Module\MediaModule\MediaType\Url
+ parent: cmfcmf_media_module.media_type.abstract_media
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.deezer:
- class: Cmfcmf\Module\MediaModule\MediaType\Deezer
- parent: cmfcmf_media_module.media_type.abstract_media
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.deezer:
+ class: Cmfcmf\Module\MediaModule\MediaType\Deezer
+ parent: cmfcmf_media_module.media_type.abstract_media
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.sound_cloud:
- class: Cmfcmf\Module\MediaModule\MediaType\SoundCloud
- parent: cmfcmf_media_module.media_type.abstract_media
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.sound_cloud:
+ class: Cmfcmf\Module\MediaModule\MediaType\SoundCloud
+ parent: cmfcmf_media_module.media_type.abstract_media
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.flickr:
- class: Cmfcmf\Module\MediaModule\MediaType\Flickr
- parent: cmfcmf_media_module.media_type.abstract_media
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.flickr:
+ class: Cmfcmf\Module\MediaModule\MediaType\Flickr
+ parent: cmfcmf_media_module.media_type.abstract_media
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.you_tube:
- class: Cmfcmf\Module\MediaModule\MediaType\YouTube
- parent: cmfcmf_media_module.media_type.abstract_media
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.you_tube:
+ class: Cmfcmf\Module\MediaModule\MediaType\YouTube
+ parent: cmfcmf_media_module.media_type.abstract_media
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.twitter:
- class: Cmfcmf\Module\MediaModule\MediaType\Twitter
- parent: cmfcmf_media_module.media_type.abstract_media
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.twitter:
+ class: Cmfcmf\Module\MediaModule\MediaType\Twitter
+ parent: cmfcmf_media_module.media_type.abstract_media
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.image:
- class: Cmfcmf\Module\MediaModule\MediaType\Image
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.image:
+ class: Cmfcmf\Module\MediaModule\MediaType\Image
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.pdf:
- class: Cmfcmf\Module\MediaModule\MediaType\Pdf
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.pdf:
+ class: Cmfcmf\Module\MediaModule\MediaType\Pdf
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.plaintext:
- class: Cmfcmf\Module\MediaModule\MediaType\Plaintext
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.plaintext:
+ class: Cmfcmf\Module\MediaModule\MediaType\Plaintext
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.audio:
- class: Cmfcmf\Module\MediaModule\MediaType\Audio
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.audio:
+ class: Cmfcmf\Module\MediaModule\MediaType\Audio
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.video:
- class: Cmfcmf\Module\MediaModule\MediaType\Video
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.video:
+ class: Cmfcmf\Module\MediaModule\MediaType\Video
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.markdown:
- class: Cmfcmf\Module\MediaModule\MediaType\Markdown
- parent: cmfcmf_media_module.media_type.abstract_file
- calls:
- - [setMarkdownParser, [@markdown_extra_parser]]
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.markdown:
+ class: Cmfcmf\Module\MediaModule\MediaType\Markdown
+ parent: cmfcmf_media_module.media_type.abstract_file
+ calls:
+ - [setMarkdownParser, ['@zikula_core.common.markdown_extra_parser']]
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.archive:
- class: Cmfcmf\Module\MediaModule\MediaType\Archive
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.archive:
+ class: Cmfcmf\Module\MediaModule\MediaType\Archive
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
- cmfcmf_media_module.media_type.unknown:
- class: Cmfcmf\Module\MediaModule\MediaType\Unknown
- parent: cmfcmf_media_module.media_type.abstract_file
- tags:
- - { name: cmfcmf_media_module.media_type }
+ cmfcmf_media_module.media_type.unknown:
+ class: Cmfcmf\Module\MediaModule\MediaType\Unknown
+ parent: cmfcmf_media_module.media_type.abstract_file
+ tags: ['cmfcmf_media_module.media_type']
diff --git a/Resources/config/routing.yml b/Resources/config/routing.yml
index ee6426b7..1e6604af 100644
--- a/Resources/config/routing.yml
+++ b/Resources/config/routing.yml
@@ -1,43 +1,43 @@
# We need to manually add all the controllers, because the media controller must come
-# before the collection controller, so that all slugs containing "/f/" will be matched
+# before the collection controller, so that all slugs containing '/f/' will be matched
# first.
cmfcmfmediamodule_controller_finder:
- resource: "@CmfcmfMediaModule/Controller/FinderController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/FinderController.php'
+ type: annotation
cmfcmfmediamodule_controller_mediaType:
- resource: "@CmfcmfMediaModule/Controller/MediaTypeController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/MediaTypeController.php'
+ type: annotation
cmfcmfmediamodule_controller_license:
- resource: "@CmfcmfMediaModule/Controller/LicenseController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/LicenseController.php'
+ type: annotation
cmfcmfmediamodule_controller_settings:
- resource: "@CmfcmfMediaModule/Controller/SettingsController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/SettingsController.php'
+ type: annotation
cmfcmfmediamodule_controller_upgrade:
- resource: "@CmfcmfMediaModule/Controller/UpgradeController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/UpgradeController.php'
+ type: annotation
cmfcmfmediamodule_controller_import:
- resource: "@CmfcmfMediaModule/Controller/ImportController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/ImportController.php'
+ type: annotation
cmfcmfmediamodule_controller_watermark:
- resource: "@CmfcmfMediaModule/Controller/WatermarkController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/WatermarkController.php'
+ type: annotation
cmfcmfmediamodule_controller_permission:
- resource: "@CmfcmfMediaModule/Controller/PermissionController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/PermissionController.php'
+ type: annotation
cmfcmfmediamodule_controller_media:
- resource: "@CmfcmfMediaModule/Controller/MediaController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/MediaController.php'
+ type: annotation
cmfcmfmediamodule_controller_collection:
- resource: "@CmfcmfMediaModule/Controller/CollectionController.php"
- type: annotation
+ resource: '@CmfcmfMediaModule/Controller/CollectionController.php'
+ type: annotation
diff --git a/Resources/config/services.yml b/Resources/config/services.yml
index fdd69e67..2643b7a2 100644
--- a/Resources/config/services.yml
+++ b/Resources/config/services.yml
@@ -2,134 +2,134 @@ imports:
- { resource: 'mediatypes.yml' }
- { resource: 'collectiontemplates.yml' }
- { resource: 'collectionpermissions.yml' }
+ - { resource: 'formtypes.yml' }
+ - { resource: 'hooks.yml' }
- { resource: 'importers.yml' }
+ - { resource: 'contenttypes.yml' }
services:
- # Security management
- cmfcmf_media_module.security_manager:
- class: Cmfcmf\Module\MediaModule\Security\SecurityManager
- arguments: [@translator, @zikula_permissions_module.api.permission, @doctrine.orm.default_entity_manager, @cmfcmf_media_module.collection_permission.container]
-
-
- # Module upgrader and version checker
- cmfcmf_media_module.upgrade.module_upgrader:
- class: Cmfcmf\Module\MediaModule\Upgrade\ModuleUpgrader
- arguments: [@translator, @zikula.cache_clearer, %kernel.cache_dir%, %kernel.root_dir%]
-
- cmfcmf_media_module.upgrade.version_checker:
- class: Cmfcmf\Module\MediaModule\Upgrade\VersionChecker
- arguments: [%kernel.cache_dir%]
-
-
- # Form types
- cmfcmf_media_module.form.type.font:
- class: Cmfcmf\Module\MediaModule\Form\Type\FontType
- arguments: [@cmfcmf_media_module.font_collection]
- tags:
- - { name: form.type, alias: cmfcmfmediamodule_font_choice }
-
- cmfcmf_media_module.form.type.color:
- class: Cmfcmf\Module\MediaModule\Form\Type\ColorType
- tags:
- - { name: form.type, alias: cmfcmfmediamodule_color }
-
- cmfcmf_media_module.form.type.permission_level:
- class: Cmfcmf\Module\MediaModule\Form\Type\PermissionLevelType
- arguments:
- - @cmfcmf_media_module.security_manager
- tags:
- - { name: form.type, alias: cmfcmfmediamodule_permission }
-
- cmfcmf_media_module.form.type.collection_template:
- class: Cmfcmf\Module\MediaModule\Form\CollectionTemplate\TemplateType
- arguments:
- - "@translator"
- - "@cmfcmf_media_module.collection_template_collection"
- - "@cmfcmf_media_module.collection_template.selected_factory"
- tags:
- - { name: form.type, alias: cmfcmfmediamodule_collectiontemplate }
-
-
- # Listeners
- cmfcmf_media_module.listener.module:
- class: Cmfcmf\Module\MediaModule\Listener\ModuleListener
- arguments: [@doctrine.orm.default_entity_manager]
- tags:
- - { name: kernel.event_subscriber }
-
- cmfcmf_media_module.listener.thirdparty:
- class: Cmfcmf\Module\MediaModule\Listener\ThirdPartyListener
- arguments: [%kernel.root_dir%]
- tags:
- - { name: kernel.event_subscriber }
-
- cmfcmf_media_module.listener.doctrine:
- class: Cmfcmf\Module\MediaModule\Listener\DoctrineListener
- tags:
- - { name: doctrine.event_subscriber }
-
-
- # Link container
- cmfcmf_media_module.container.links:
- class: Cmfcmf\Module\MediaModule\Container\LinkContainer
- arguments: [@router, @cmfcmf_media_module.security_manager, @translator, @doctrine.orm.default_entity_manager]
- tags:
- - { name: zikula.link_container }
-
-
- # Collection of media types
- cmfcmf_media_module.media_type_collection:
- class: Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection
- lazy: true
-
-
- # Collection of "Collection" templates
- cmfcmf_media_module.collection_template_collection:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\TemplateCollection
- lazy: true
-
-
- # Selected collection template factory
- cmfcmf_media_module.collection_template.selected_factory:
- class: Cmfcmf\Module\MediaModule\CollectionTemplate\SelectedTemplateFactory
- arguments: ["@cmfcmf_media_module.collection_template_collection"]
-
- # Twig extension
- cmfcmf_media_module.twig_extension:
- class: Cmfcmf\Module\MediaModule\Twig\TwigExtension
- arguments: [@markdown_extra_parser, @hook_dispatcher, @cmfcmf_media_module.security_manager, @cmfcmf_media_module.upgrade.version_checker, @translator]
- public: false
- tags:
- - { name: twig.extension }
-
-
- # Hook handlers
- cmfcmf_media_module.hook_handler.base:
- abstract: true
- arguments: [@doctrine.orm.default_entity_manager, @request_stack, @templating, @cmfcmf_media_module.security_manager, @translator]
-
- cmfcmf_media_module.hook_handler.license:
- class: Cmfcmf\Module\MediaModule\HookHandler\LicenseHookHandler
- parent: cmfcmf_media_module.hook_handler.base
-
- cmfcmf_media_module.hook_handler.media:
- class: Cmfcmf\Module\MediaModule\HookHandler\MediaHookHandler
- parent: cmfcmf_media_module.hook_handler.base
- calls:
- - [setMediaTypeCollection, [@cmfcmf_media_module.media_type_collection]]
-
- cmfcmf_media_module.hook_handler.collection:
- class: Cmfcmf\Module\MediaModule\HookHandler\CollectionHookHandler
- parent: cmfcmf_media_module.hook_handler.base
- calls:
- - [setMediaTypeCollection, [@cmfcmf_media_module.media_type_collection]]
-
-
- # Fonts
- cmfcmf_media_module.font.font_loader:
- class: Cmfcmf\Module\MediaModule\Font\FontLoader
- tags:
- - { name: cmfcmf_media_module.font }
-
- cmfcmf_media_module.font_collection:
- class: Cmfcmf\Module\MediaModule\Font\FontCollection
+ # Imagine filter
+ cmfcmf_media_module.filter.custom_image_filter:
+ class: Cmfcmf\Module\MediaModule\Imagine\Filter\Loader\CustomImageFilter
+ arguments:
+ - '@liip_imagine'
+ - '@doctrine.orm.default_entity_manager'
+ - '@cmfcmf_media_module.font_collection'
+ tags:
+ - { name: 'liip_imagine.filter.loader', loader: cmfcmfmediamodule.custom_image_filter }
+
+ # Security management
+ cmfcmf_media_module.security_manager:
+ class: Cmfcmf\Module\MediaModule\Security\SecurityManager
+ arguments:
+ - '@translator'
+ - '@zikula_permissions_module.api.permission'
+ - '@doctrine.orm.default_entity_manager'
+ - '@cmfcmf_media_module.collection_permission.container'
+
+ # Module upgrader and version checker
+ cmfcmf_media_module.upgrade.module_upgrader:
+ class: Cmfcmf\Module\MediaModule\Upgrade\ModuleUpgrader
+ arguments:
+ - '@translator'
+ - '@filesystem'
+ - '@event_dispatcher'
+ - '@zikula_extensions_module.extension_repository'
+ - '@zikula_extensions_module.bundle_sync_helper'
+ - '@zikula_extensions_module.extension_helper'
+ - '@zikula.cache_clearer'
+ - '%kernel.cache_dir%'
+ - '%kernel.root_dir%'
+
+ cmfcmf_media_module.upgrade.version_checker:
+ class: Cmfcmf\Module\MediaModule\Upgrade\VersionChecker
+ arguments:
+ - '%kernel.cache_dir%'
+
+ # Helpers
+ cmfcmf_media_module.search_helper:
+ class: Cmfcmf\Module\MediaModule\Helper\SearchHelper
+ arguments:
+ - '@request_stack'
+ - '@cmfcmf_media_module.security_manager'
+ tags:
+ - { name: zikula.searchable_module, bundleName: CmfcmfMediaModule }
+
+ # Listeners
+ cmfcmf_media_module.listener.doctrine:
+ class: Cmfcmf\Module\MediaModule\Listener\DoctrineListener
+ tags: ['doctrine.event_subscriber']
+
+ cmfcmf_media_module.listener.entity_lifecycle:
+ class: Cmfcmf\Module\MediaModule\Listener\EntityLifecycleListener
+ arguments:
+ - '@service_container'
+ tags: ['doctrine.event_subscriber']
+
+ cmfcmf_media_module.listener.module:
+ class: Cmfcmf\Module\MediaModule\Listener\ModuleListener
+ arguments:
+ - '@doctrine.orm.default_entity_manager'
+ tags: ['kernel.event_subscriber']
+
+ cmfcmf_media_module.listener.thirdparty:
+ class: Cmfcmf\Module\MediaModule\Listener\ThirdPartyListener
+ arguments:
+ - '@filesystem'
+ - '@request_stack'
+ tags: ['kernel.event_subscriber']
+
+ # Link container
+ cmfcmf_media_module.container.links:
+ class: Cmfcmf\Module\MediaModule\Container\LinkContainer
+ arguments:
+ - '@router'
+ - '@cmfcmf_media_module.security_manager'
+ - '@translator'
+ - '@doctrine.orm.default_entity_manager'
+ tags: ['zikula.link_container']
+
+
+ # Collection of media types
+ cmfcmf_media_module.media_type_collection:
+ class: Cmfcmf\Module\MediaModule\MediaType\MediaTypeCollection
+ lazy: true
+
+
+ # Collection of "Collection" templates
+ cmfcmf_media_module.collection_template_collection:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\TemplateCollection
+ lazy: true
+
+
+ # Selected collection template factory
+ cmfcmf_media_module.collection_template.selected_factory:
+ class: Cmfcmf\Module\MediaModule\CollectionTemplate\SelectedTemplateFactory
+ arguments:
+ - '@cmfcmf_media_module.collection_template_collection'
+ - "@=service('zikula_extensions_module.api.variable').get('CmfcmfMediaModule', 'defaultCollectionTemplate')"
+
+ # Twig extension
+ cmfcmf_media_module.twig_extension:
+ class: Cmfcmf\Module\MediaModule\Twig\TwigExtension
+ arguments:
+ - '@translator'
+ - '@zikula_core.common.markdown_extra_parser'
+ - '@hook_dispatcher'
+ - '@cmfcmf_media_module.security_manager'
+ - '@cmfcmf_media_module.upgrade.version_checker'
+ - '@zikula_extensions_module.extension_repository'
+ - '@zikula_extensions_module.api.variable'
+ public: false
+ tags: ['twig.extension']
+
+ # Fonts
+ cmfcmf_media_module.font.font_loader:
+ class: Cmfcmf\Module\MediaModule\Font\FontLoader
+ tags: ['cmfcmf_media_module.font']
+
+ cmfcmf_media_module.font_collection:
+ class: Cmfcmf\Module\MediaModule\Font\FontCollection
+
+parameters:
+ liip_imagine.cache.signer.class: Cmfcmf\Module\MediaModule\Imagine\Cache\DummySigner
diff --git a/Resources/public/css/vendor/select2.min.css b/Resources/public/css/vendor/select2.min.css
index 1c723442..60d59904 100644
--- a/Resources/public/css/vendor/select2.min.css
+++ b/Resources/public/css/vendor/select2.min.css
@@ -1 +1 @@
-.select2-container{box-sizing:border-box;display:inline-block;margin:0;position:relative;vertical-align:middle;}.select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;height:28px;user-select:none;-webkit-user-select:none;}.select2-container .select2-selection--single .select2-selection__rendered{display:block;padding-left:8px;padding-right:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.select2-container[dir="rtl"] .select2-selection--single .select2-selection__rendered{padding-right:8px;padding-left:20px;}.select2-container .select2-selection--multiple{box-sizing:border-box;cursor:pointer;display:block;min-height:32px;user-select:none;-webkit-user-select:none;}.select2-container .select2-selection--multiple .select2-selection__rendered{display:inline-block;overflow:hidden;padding-left:8px;text-overflow:ellipsis;white-space:nowrap;}.select2-container .select2-search--inline{float:left;}.select2-container .select2-search--inline .select2-search__field{box-sizing:border-box;border:none;font-size:100%;margin-top:5px;}.select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none;}.select2-dropdown{background-color:white;border:1px solid #aaa;border-radius:4px;box-sizing:border-box;display:block;position:absolute;left:-100000px;width:100%;z-index:1051;}.select2-results{display:block;}.select2-results__options{list-style:none;margin:0;padding:0;}.select2-results__option{padding:6px;user-select:none;-webkit-user-select:none;}.select2-results__option[aria-selected]{cursor:pointer;}.select2-container--open .select2-dropdown{left:0;}.select2-container--open .select2-dropdown--above{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--open .select2-dropdown--below{border-top:none;border-top-left-radius:0;border-top-right-radius:0;}.select2-search--dropdown{display:block;padding:4px;}.select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box;}.select2-search--dropdown .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none;}.select2-search--dropdown.select2-search--hide{display:none;}.select2-close-mask{border:0;margin:0;padding:0;display:block;position:fixed;left:0;top:0;min-height:100%;min-width:100%;height:auto;width:auto;opacity:0;z-index:99;background-color:#fff;filter:alpha(opacity=0);}.select2-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;}.select2-container--default .select2-selection--single{background-color:#fff;border:1px solid #aaa;border-radius:4px;}.select2-container--default .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;}.select2-container--default .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;}.select2-container--default .select2-selection--single .select2-selection__placeholder{color:#999;}.select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:1px;right:1px;width:20px;}.select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0;}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left;}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__arrow{left:1px;right:auto;}.select2-container--default.select2-container--disabled .select2-selection--single{background-color:#eee;cursor:default;}.select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear{display:none;}.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px;}.select2-container--default .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;}.select2-container--default .select2-selection--multiple .select2-selection__rendered{box-sizing:border-box;list-style:none;margin:0;padding:0 5px;width:100%;}.select2-container--default .select2-selection--multiple .select2-selection__placeholder{color:#999;margin-top:5px;float:left;}.select2-container--default .select2-selection--multiple .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-top:5px;margin-right:10px;}.select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px;}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove{color:#999;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px;}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover{color:#333;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice,.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder{float:right;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto;}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto;}.select2-container--default.select2-container--focus .select2-selection--multiple{border:solid black 1px;outline:0;}.select2-container--default.select2-container--disabled .select2-selection--multiple{background-color:#eee;cursor:default;}.select2-container--default.select2-container--disabled .select2-selection__choice__remove{display:none;}.select2-container--default.select2-container--open.select2-container--above .select2-selection--single,.select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple{border-top-left-radius:0;border-top-right-radius:0;}.select2-container--default.select2-container--open.select2-container--below .select2-selection--single,.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--default .select2-search--dropdown .select2-search__field{border:1px solid #aaa;}.select2-container--default .select2-search--inline .select2-search__field{background:transparent;border:none;outline:0;}.select2-container--default .select2-results>.select2-results__options{max-height:200px;overflow-y:auto;}.select2-container--default .select2-results__option[role=group]{padding:0;}.select2-container--default .select2-results__option[aria-disabled=true]{color:#999;}.select2-container--default .select2-results__option[aria-selected=true]{background-color:#ddd;}.select2-container--default .select2-results__option .select2-results__option{padding-left:1em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__group{padding-left:0;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option{margin-left:-1em;padding-left:2em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-2em;padding-left:3em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-3em;padding-left:4em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-4em;padding-left:5em;}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-5em;padding-left:6em;}.select2-container--default .select2-results__option--highlighted[aria-selected]{background-color:#5897fb;color:white;}.select2-container--default .select2-results__group{cursor:default;display:block;padding:6px;}.select2-container--classic .select2-selection--single{background-color:#f6f6f6;border:1px solid #aaa;border-radius:4px;outline:0;background-image:-webkit-linear-gradient(top, #ffffff 50%, #eeeeee 100%);background-image:-o-linear-gradient(top, #ffffff 50%, #eeeeee 100%);background-image:linear-gradient(to bottom, #ffffff 50%, #eeeeee 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);}.select2-container--classic .select2-selection--single:focus{border:1px solid #5897fb;}.select2-container--classic .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;}.select2-container--classic .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-right:10px;}.select2-container--classic .select2-selection--single .select2-selection__placeholder{color:#999;}.select2-container--classic .select2-selection--single .select2-selection__arrow{background-color:#ddd;border:none;border-left:1px solid #aaa;border-top-right-radius:4px;border-bottom-right-radius:4px;height:26px;position:absolute;top:1px;right:1px;width:20px;background-image:-webkit-linear-gradient(top, #eeeeee 50%, #cccccc 100%);background-image:-o-linear-gradient(top, #eeeeee 50%, #cccccc 100%);background-image:linear-gradient(to bottom, #eeeeee 50%, #cccccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#cccccc', GradientType=0);}.select2-container--classic .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0;}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left;}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__arrow{border:none;border-right:1px solid #aaa;border-radius:0;border-top-left-radius:4px;border-bottom-left-radius:4px;left:1px;right:auto;}.select2-container--classic.select2-container--open .select2-selection--single{border:1px solid #5897fb;}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow{background:transparent;border:none;}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px;}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single{border-top:none;border-top-left-radius:0;border-top-right-radius:0;background-image:-webkit-linear-gradient(top, #ffffff 0%, #eeeeee 50%);background-image:-o-linear-gradient(top, #ffffff 0%, #eeeeee 50%);background-image:linear-gradient(to bottom, #ffffff 0%, #eeeeee 50%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;background-image:-webkit-linear-gradient(top, #eeeeee 50%, #ffffff 100%);background-image:-o-linear-gradient(top, #eeeeee 50%, #ffffff 100%);background-image:linear-gradient(to bottom, #eeeeee 50%, #ffffff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#ffffff', GradientType=0);}.select2-container--classic .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;outline:0;}.select2-container--classic .select2-selection--multiple:focus{border:1px solid #5897fb;}.select2-container--classic .select2-selection--multiple .select2-selection__rendered{list-style:none;margin:0;padding:0 5px;}.select2-container--classic .select2-selection--multiple .select2-selection__clear{display:none;}.select2-container--classic .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px;}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove{color:#888;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px;}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover{color:#555;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{float:right;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto;}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto;}.select2-container--classic.select2-container--open .select2-selection--multiple{border:1px solid #5897fb;}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple{border-top:none;border-top-left-radius:0;border-top-right-radius:0;}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;}.select2-container--classic .select2-search--dropdown .select2-search__field{border:1px solid #aaa;outline:0;}.select2-container--classic .select2-search--inline .select2-search__field{outline:0;}.select2-container--classic .select2-dropdown{background-color:white;border:1px solid transparent;}.select2-container--classic .select2-dropdown--above{border-bottom:none;}.select2-container--classic .select2-dropdown--below{border-top:none;}.select2-container--classic .select2-results>.select2-results__options{max-height:200px;overflow-y:auto;}.select2-container--classic .select2-results__option[role=group]{padding:0;}.select2-container--classic .select2-results__option[aria-disabled=true]{color:grey;}.select2-container--classic .select2-results__option--highlighted[aria-selected]{background-color:#3875d7;color:white;}.select2-container--classic .select2-results__group{cursor:default;display:block;padding:6px;}.select2-container--classic.select2-container--open .select2-dropdown{border-color:#5897fb;}
\ No newline at end of file
+.select2-container{box-sizing:border-box;display:inline-block;margin:0;position:relative;vertical-align:middle}.select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;height:28px;user-select:none;-webkit-user-select:none}.select2-container .select2-selection--single .select2-selection__rendered{display:block;padding-left:8px;padding-right:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.select2-container .select2-selection--single .select2-selection__clear{position:relative}.select2-container[dir="rtl"] .select2-selection--single .select2-selection__rendered{padding-right:8px;padding-left:20px}.select2-container .select2-selection--multiple{box-sizing:border-box;cursor:pointer;display:block;min-height:32px;user-select:none;-webkit-user-select:none}.select2-container .select2-selection--multiple .select2-selection__rendered{display:inline-block;overflow:hidden;padding-left:8px;text-overflow:ellipsis;white-space:nowrap}.select2-container .select2-search--inline{float:left}.select2-container .select2-search--inline .select2-search__field{box-sizing:border-box;border:none;font-size:100%;margin-top:5px;padding:0}.select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none}.select2-dropdown{background-color:white;border:1px solid #aaa;border-radius:4px;box-sizing:border-box;display:block;position:absolute;left:-100000px;width:100%;z-index:1051}.select2-results{display:block}.select2-results__options{list-style:none;margin:0;padding:0}.select2-results__option{padding:6px;user-select:none;-webkit-user-select:none}.select2-results__option[aria-selected]{cursor:pointer}.select2-container--open .select2-dropdown{left:0}.select2-container--open .select2-dropdown--above{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--open .select2-dropdown--below{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.select2-search--dropdown{display:block;padding:4px}.select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box}.select2-search--dropdown .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none}.select2-search--dropdown.select2-search--hide{display:none}.select2-close-mask{border:0;margin:0;padding:0;display:block;position:fixed;left:0;top:0;min-height:100%;min-width:100%;height:auto;width:auto;opacity:0;z-index:99;background-color:#fff;filter:alpha(opacity=0)}.select2-hidden-accessible{border:0 !important;clip:rect(0 0 0 0) !important;-webkit-clip-path:inset(50%) !important;clip-path:inset(50%) !important;height:1px !important;overflow:hidden !important;padding:0 !important;position:absolute !important;width:1px !important;white-space:nowrap !important}.select2-container--default .select2-selection--single{background-color:#fff;border:1px solid #aaa;border-radius:4px}.select2-container--default .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px}.select2-container--default .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold}.select2-container--default .select2-selection--single .select2-selection__placeholder{color:#999}.select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:1px;right:1px;width:20px}.select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__arrow{left:1px;right:auto}.select2-container--default.select2-container--disabled .select2-selection--single{background-color:#eee;cursor:default}.select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear{display:none}.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px}.select2-container--default .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text}.select2-container--default .select2-selection--multiple .select2-selection__rendered{box-sizing:border-box;list-style:none;margin:0;padding:0 5px;width:100%}.select2-container--default .select2-selection--multiple .select2-selection__rendered li{list-style:none}.select2-container--default .select2-selection--multiple .select2-selection__placeholder{color:#999;margin-top:5px;float:left}.select2-container--default .select2-selection--multiple .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-top:5px;margin-right:10px}.select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove{color:#999;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover{color:#333}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice,.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder,.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-search--inline{float:right}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto}.select2-container--default.select2-container--focus .select2-selection--multiple{border:solid black 1px;outline:0}.select2-container--default.select2-container--disabled .select2-selection--multiple{background-color:#eee;cursor:default}.select2-container--default.select2-container--disabled .select2-selection__choice__remove{display:none}.select2-container--default.select2-container--open.select2-container--above .select2-selection--single,.select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple{border-top-left-radius:0;border-top-right-radius:0}.select2-container--default.select2-container--open.select2-container--below .select2-selection--single,.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--default .select2-search--dropdown .select2-search__field{border:1px solid #aaa}.select2-container--default .select2-search--inline .select2-search__field{background:transparent;border:none;outline:0;box-shadow:none;-webkit-appearance:textfield}.select2-container--default .select2-results>.select2-results__options{max-height:200px;overflow-y:auto}.select2-container--default .select2-results__option[role=group]{padding:0}.select2-container--default .select2-results__option[aria-disabled=true]{color:#999}.select2-container--default .select2-results__option[aria-selected=true]{background-color:#ddd}.select2-container--default .select2-results__option .select2-results__option{padding-left:1em}.select2-container--default .select2-results__option .select2-results__option .select2-results__group{padding-left:0}.select2-container--default .select2-results__option .select2-results__option .select2-results__option{margin-left:-1em;padding-left:2em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-2em;padding-left:3em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-3em;padding-left:4em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-4em;padding-left:5em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-5em;padding-left:6em}.select2-container--default .select2-results__option--highlighted[aria-selected]{background-color:#5897fb;color:white}.select2-container--default .select2-results__group{cursor:default;display:block;padding:6px}.select2-container--classic .select2-selection--single{background-color:#f7f7f7;border:1px solid #aaa;border-radius:4px;outline:0;background-image:-webkit-linear-gradient(top, #fff 50%, #eee 100%);background-image:-o-linear-gradient(top, #fff 50%, #eee 100%);background-image:linear-gradient(to bottom, #fff 50%, #eee 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFFFF', endColorstr='#FFEEEEEE', GradientType=0)}.select2-container--classic .select2-selection--single:focus{border:1px solid #5897fb}.select2-container--classic .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px}.select2-container--classic .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-right:10px}.select2-container--classic .select2-selection--single .select2-selection__placeholder{color:#999}.select2-container--classic .select2-selection--single .select2-selection__arrow{background-color:#ddd;border:none;border-left:1px solid #aaa;border-top-right-radius:4px;border-bottom-right-radius:4px;height:26px;position:absolute;top:1px;right:1px;width:20px;background-image:-webkit-linear-gradient(top, #eee 50%, #ccc 100%);background-image:-o-linear-gradient(top, #eee 50%, #ccc 100%);background-image:linear-gradient(to bottom, #eee 50%, #ccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFEEEEEE', endColorstr='#FFCCCCCC', GradientType=0)}.select2-container--classic .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__arrow{border:none;border-right:1px solid #aaa;border-radius:0;border-top-left-radius:4px;border-bottom-left-radius:4px;left:1px;right:auto}.select2-container--classic.select2-container--open .select2-selection--single{border:1px solid #5897fb}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow{background:transparent;border:none}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single{border-top:none;border-top-left-radius:0;border-top-right-radius:0;background-image:-webkit-linear-gradient(top, #fff 0%, #eee 50%);background-image:-o-linear-gradient(top, #fff 0%, #eee 50%);background-image:linear-gradient(to bottom, #fff 0%, #eee 50%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFFFF', endColorstr='#FFEEEEEE', GradientType=0)}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;background-image:-webkit-linear-gradient(top, #eee 50%, #fff 100%);background-image:-o-linear-gradient(top, #eee 50%, #fff 100%);background-image:linear-gradient(to bottom, #eee 50%, #fff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFEEEEEE', endColorstr='#FFFFFFFF', GradientType=0)}.select2-container--classic .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;outline:0}.select2-container--classic .select2-selection--multiple:focus{border:1px solid #5897fb}.select2-container--classic .select2-selection--multiple .select2-selection__rendered{list-style:none;margin:0;padding:0 5px}.select2-container--classic .select2-selection--multiple .select2-selection__clear{display:none}.select2-container--classic .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove{color:#888;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover{color:#555}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{float:right;margin-left:5px;margin-right:auto}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto}.select2-container--classic.select2-container--open .select2-selection--multiple{border:1px solid #5897fb}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--classic .select2-search--dropdown .select2-search__field{border:1px solid #aaa;outline:0}.select2-container--classic .select2-search--inline .select2-search__field{outline:0;box-shadow:none}.select2-container--classic .select2-dropdown{background-color:#fff;border:1px solid transparent}.select2-container--classic .select2-dropdown--above{border-bottom:none}.select2-container--classic .select2-dropdown--below{border-top:none}.select2-container--classic .select2-results>.select2-results__options{max-height:200px;overflow-y:auto}.select2-container--classic .select2-results__option[role=group]{padding:0}.select2-container--classic .select2-results__option[aria-disabled=true]{color:grey}.select2-container--classic .select2-results__option--highlighted[aria-selected]{background-color:#3875d7;color:#fff}.select2-container--classic .select2-results__group{cursor:default;display:block;padding:6px}.select2-container--classic.select2-container--open .select2-dropdown{border-color:#5897fb}
diff --git a/Resources/public/css/vendor/toastr.min.css b/Resources/public/css/vendor/toastr.min.css
index 64adc420..643135ea 100644
--- a/Resources/public/css/vendor/toastr.min.css
+++ b/Resources/public/css/vendor/toastr.min.css
@@ -1 +1 @@
-.toast-title{font-weight:700}.toast-message{-ms-word-wrap:break-word;word-wrap:break-word}.toast-message a,.toast-message label{color:#fff}.toast-message a:hover{color:#ccc;text-decoration:none}.toast-close-button{position:relative;right:-.3em;top:-.3em;float:right;font-size:20px;font-weight:700;color:#fff;-webkit-text-shadow:0 1px 0 #fff;text-shadow:0 1px 0 #fff;opacity:.8;-ms-filter:alpha(Opacity=80);filter:alpha(opacity=80)}.toast-close-button:focus,.toast-close-button:hover{color:#000;text-decoration:none;cursor:pointer;opacity:.4;-ms-filter:alpha(Opacity=40);filter:alpha(opacity=40)}button.toast-close-button{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.toast-top-center{top:0;right:0;width:100%}.toast-bottom-center{bottom:0;right:0;width:100%}.toast-top-full-width{top:0;right:0;width:100%}.toast-bottom-full-width{bottom:0;right:0;width:100%}.toast-top-left{top:12px;left:12px}.toast-top-right{top:12px;right:12px}.toast-bottom-right{right:12px;bottom:12px}.toast-bottom-left{bottom:12px;left:12px}#toast-container{position:fixed;z-index:999999}#toast-container *{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}#toast-container>div{position:relative;overflow:hidden;margin:0 0 6px;padding:15px 15px 15px 50px;width:300px;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;background-position:15px center;background-repeat:no-repeat;-moz-box-shadow:0 0 12px #999;-webkit-box-shadow:0 0 12px #999;box-shadow:0 0 12px #999;color:#fff;opacity:.8;-ms-filter:alpha(Opacity=80);filter:alpha(opacity=80)}#toast-container>:hover{-moz-box-shadow:0 0 12px #000;-webkit-box-shadow:0 0 12px #000;box-shadow:0 0 12px #000;opacity:1;-ms-filter:alpha(Opacity=100);filter:alpha(opacity=100);cursor:pointer}#toast-container>.toast-info{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII=)!important}#toast-container>.toast-error{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=)!important}#toast-container>.toast-success{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==)!important}#toast-container>.toast-warning{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=)!important}#toast-container.toast-bottom-center>div,#toast-container.toast-top-center>div{width:300px;margin:auto}#toast-container.toast-bottom-full-width>div,#toast-container.toast-top-full-width>div{width:96%;margin:auto}.toast{background-color:#030303}.toast-success{background-color:#51a351}.toast-error{background-color:#bd362f}.toast-info{background-color:#2f96b4}.toast-warning{background-color:#f89406}.toast-progress{position:absolute;left:0;bottom:0;height:4px;background-color:#000;opacity:.4;-ms-filter:alpha(Opacity=40);filter:alpha(opacity=40)}@media all and (max-width:240px){#toast-container>div{padding:8px 8px 8px 50px;width:11em}#toast-container .toast-close-button{right:-.2em;top:-.2em}}@media all and (min-width:241px) and (max-width:480px){#toast-container>div{padding:8px 8px 8px 50px;width:18em}#toast-container .toast-close-button{right:-.2em;top:-.2em}}@media all and (min-width:481px) and (max-width:768px){#toast-container>div{padding:15px 15px 15px 50px;width:25em}}
+/*
* Note that this is toastr v2.1.3, the "latest" version in url has no more maintenance,
* please go to https://cdnjs.com/libraries/toastr.js and pick a certain version you want to use,
* make sure you copy the url from the website since the url may change between versions.
* */
.toast-title{font-weight:700}.toast-message{-ms-word-wrap:break-word;word-wrap:break-word}.toast-message a,.toast-message label{color:#FFF}.toast-message a:hover{color:#CCC;text-decoration:none}.toast-close-button{position:relative;right:-.3em;top:-.3em;float:right;font-size:20px;font-weight:700;color:#FFF;-webkit-text-shadow:0 1px 0 #fff;text-shadow:0 1px 0 #fff;opacity:.8;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=80);filter:alpha(opacity=80);line-height:1}.toast-close-button:focus,.toast-close-button:hover{color:#000;text-decoration:none;cursor:pointer;opacity:.4;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=40);filter:alpha(opacity=40)}.rtl .toast-close-button{left:-.3em;float:left;right:.3em}button.toast-close-button{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.toast-top-center{top:0;right:0;width:100%}.toast-bottom-center{bottom:0;right:0;width:100%}.toast-top-full-width{top:0;right:0;width:100%}.toast-bottom-full-width{bottom:0;right:0;width:100%}.toast-top-left{top:12px;left:12px}.toast-top-right{top:12px;right:12px}.toast-bottom-right{right:12px;bottom:12px}.toast-bottom-left{bottom:12px;left:12px}#toast-container{position:fixed;z-index:999999;pointer-events:none}#toast-container *{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}#toast-container>div{position:relative;pointer-events:auto;overflow:hidden;margin:0 0 6px;padding:15px 15px 15px 50px;width:300px;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;background-position:15px center;background-repeat:no-repeat;-moz-box-shadow:0 0 12px #999;-webkit-box-shadow:0 0 12px #999;box-shadow:0 0 12px #999;color:#FFF;opacity:.8;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=80);filter:alpha(opacity=80)}#toast-container>div.rtl{direction:rtl;padding:15px 50px 15px 15px;background-position:right 15px center}#toast-container>div:hover{-moz-box-shadow:0 0 12px #000;-webkit-box-shadow:0 0 12px #000;box-shadow:0 0 12px #000;opacity:1;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100);filter:alpha(opacity=100);cursor:pointer}#toast-container>.toast-info{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII=)!important}#toast-container>.toast-error{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=)!important}#toast-container>.toast-success{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==)!important}#toast-container>.toast-warning{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=)!important}#toast-container.toast-bottom-center>div,#toast-container.toast-top-center>div{width:300px;margin-left:auto;margin-right:auto}#toast-container.toast-bottom-full-width>div,#toast-container.toast-top-full-width>div{width:96%;margin-left:auto;margin-right:auto}.toast{background-color:#030303}.toast-success{background-color:#51A351}.toast-error{background-color:#BD362F}.toast-info{background-color:#2F96B4}.toast-warning{background-color:#F89406}.toast-progress{position:absolute;left:0;bottom:0;height:4px;background-color:#000;opacity:.4;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=40);filter:alpha(opacity=40)}@media all and (max-width:240px){#toast-container>div{padding:8px 8px 8px 50px;width:11em}#toast-container>div.rtl{padding:8px 50px 8px 8px}#toast-container .toast-close-button{right:-.2em;top:-.2em}#toast-container .rtl .toast-close-button{left:-.2em;right:.2em}}@media all and (min-width:241px) and (max-width:480px){#toast-container>div{padding:8px 8px 8px 50px;width:18em}#toast-container>div.rtl{padding:8px 50px 8px 8px}#toast-container .toast-close-button{right:-.2em;top:-.2em}#toast-container .rtl .toast-close-button{left:-.2em;right:.2em}}@media all and (min-width:481px) and (max-width:768px){#toast-container>div{padding:15px 15px 15px 50px;width:25em}#toast-container>div.rtl{padding:15px 50px 15px 15px}}
\ No newline at end of file
diff --git a/Resources/public/js/CKEditorPlugin/plugin.js b/Resources/public/js/CKEditorPlugin/plugin.js
deleted file mode 100644
index 79bdb8ab..00000000
--- a/Resources/public/js/CKEditorPlugin/plugin.js
+++ /dev/null
@@ -1,26 +0,0 @@
-window.CmfcmfMediaModule = window.CmfcmfMediaModule || {};
-window.CmfcmfMediaModule.currentEditor = window.CmfcmfMediaModule.currentEditor || null;
-window.CmfcmfMediaModule.currentEditorInstance = window.CmfcmfMediaModule.currentEditorInstance || null;
-
-CKEDITOR.plugins.add('cmfcmfmediamodule', {
- requires: 'popup',
- lang: 'en,de',
- init: function (editor) {
- editor.addCommand('insertMediaObject', {
- exec: function (editor) {
- window.CmfcmfMediaModule.currentEditor = 'ckeditor';
- window.CmfcmfMediaModule.currentEditorInstance = editor;
- editor.popup(
- Routing.generate('cmfcmfmediamodule_finder_choosemethod'),
- /*width*/ '80%', /*height*/ '70%',
- 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes'
- );
- }
- });
- editor.ui.addButton('cmfcmfmediamodule', {
- label: editor.lang.cmfcmfmediamodule.title,
- command: 'insertMediaObject',
- icon: this.path + '/../../../images/admin.png'
- });
- }
-});
diff --git a/Resources/public/js/CmfcmfMediaModule.ContentType.Media.js b/Resources/public/js/CmfcmfMediaModule.ContentType.Media.js
new file mode 100644
index 00000000..3851e8ed
--- /dev/null
+++ b/Resources/public/js/CmfcmfMediaModule.ContentType.Media.js
@@ -0,0 +1,60 @@
+'use strict';
+
+/**
+ * Loads and displays the preview for a selected medium.
+ */
+function getMediaPreview(id) {
+ var result;
+
+ result = '';
+ if (!id) {
+ return result;
+ }
+
+ jQuery.ajax({
+ url: Routing.generate('cmfcmfmediamodule_media_getembeddata', {id: id}),
+ method: 'GET',
+ async: false
+ }).done(function (data) {
+ result = data.preview;
+ });
+
+ return result;
+}
+
+/**
+ * Initialises the media edit view.
+ */
+function contentInitMediaEdit() {
+ var mediaSelector;
+
+ mediaSelector = jQuery('#zikulacontentmodule_contentitem_contentData_id');
+ mediaSelector.parent().append('' + getMediaPreview(mediaSelector.val()) + '
');
+ mediaSelector.change(function () {
+ mediaSelector.parent().find('.help-block').first().html('');
+ mediaSelector.parent().find('.help-block').first().html(getMediaPreview(mediaSelector.val()));
+ });
+}
+
+/**
+ * Initialises the media translation view.
+ */
+function contentInitMediaTranslation() {
+ jQuery('.source-section .field-id').each(function (index) {
+ var fieldContainer;
+
+ fieldContainer = jQuery(this).find('.form-control-static');
+ zikulacontentmodule_translate_contentData_id
+ fieldContainer.append('' + getMediaPreview(fieldContainer.text()) + '
');
+ });
+ jQuery('#contentTranslateTarget .tab-content').find("select[id$='_id']").each(function (index) {
+ var mediaSelector;
+
+ mediaSelector = jQuery(this);
+ mediaSelector.parents('.col-sm-9').first().append('' + getMediaPreview(mediaSelector.val()) + '
');
+ mediaSelector.change(function () {
+ mediaSelector.parents('.col-sm-9').first().find('.help-block').first().html('');
+ mediaSelector.parents('.col-sm-9').first().find('.help-block').first().html(getMediaPreview(mediaSelector.val()));
+ });
+ });
+}
diff --git a/Resources/public/js/Collection/Permission/View.js b/Resources/public/js/Collection/Permission/View.js
index 0a788163..d87a66f3 100644
--- a/Resources/public/js/Collection/Permission/View.js
+++ b/Resources/public/js/Collection/Permission/View.js
@@ -20,7 +20,7 @@
});
// Element is before the lowest locked element.
if (evt.newIndex < highestLockedIndex) {
- window.toastr['error']('You cannot move a permission with goOn = no above a locked permission.', 'Problem detected!');
+ window.toastr['error'](Translator.__('You cannot move a permission with goOn = no above a locked permission.'), Translator.__('Problem detected!'));
$table.find('tr:nth-child(' + parseInt(evt.oldIndex + 1) + ')').after($item);
return;
@@ -32,7 +32,7 @@
newIndex: parseInt(evt.newIndex)
})).success(function (data) {
$item.data('version', data.newVersion);
- window.toastr['success']('', 'Saved new position.');
+ window.toastr['success']('', Translator.__('Saved new position.'));
}).fail(window.CmfcmfMediaModule.Util.Ajax.fail);
}
});
diff --git a/Resources/public/js/Collection/cards.js b/Resources/public/js/Collection/cards.js
index 4d44556f..86e1210e 100644
--- a/Resources/public/js/Collection/cards.js
+++ b/Resources/public/js/Collection/cards.js
@@ -39,11 +39,11 @@
position: evt.newIndex,
'new-position': evt.newIndex,
'old-position': evt.oldIndex
- }).success(function () {
- window.toastr['success']('', 'Saved new position.');
+ }).done(function () {
+ window.toastr['success']('', Translator.__('Saved new position.'));
}).fail(window.CmfcmfMediaModule.Util.Ajax.fail);
}
});
}
});
-})(jQuery);
\ No newline at end of file
+})(jQuery);
diff --git a/Resources/public/js/Finder/base.js b/Resources/public/js/Finder/base.js
index 5af71c31..e96c334f 100644
--- a/Resources/public/js/Finder/base.js
+++ b/Resources/public/js/Finder/base.js
@@ -23,7 +23,7 @@
return;
}
- $.getJSON(Routing.generate('cmfcmfmediamodule_finder_ajaxfind'), {q: $searchInput.val()}).success(function (results) {
+ $.getJSON(Routing.generate('cmfcmfmediamodule_finder_ajaxfind'), {q: $searchInput.val()}, function (results) {
$cog.addClass('hidden');
var $table = $('#cmfcmfmedia-finder-table-body');
@@ -36,6 +36,7 @@
tr += '' + window.CmfcmfMediaModule.Util.htmlEncode(results[i].type) + ' ';
tr += '' + window.CmfcmfMediaModule.Util.htmlEncode(results[i].title) + ' ';
+ tr += '' + results[i].preview + ' ';
if (results[i].license) {
tr += '';
if (results[i].license.url) {
@@ -49,7 +50,7 @@
} else {
tr += ' -- ';
}
- tr += 'view ';
+ tr += '' + Translator.__('view') + ' ';
tr += '';
diff --git a/Resources/public/js/Finder/opener.js b/Resources/public/js/Finder/opener.js
new file mode 100644
index 00000000..a20d9290
--- /dev/null
+++ b/Resources/public/js/Finder/opener.js
@@ -0,0 +1,35 @@
+window.CmfcmfMediaModule = window.CmfcmfMediaModule || {};
+window.CmfcmfMediaModule.currentEditor = window.CmfcmfMediaModule.currentEditor || null;
+window.CmfcmfMediaModule.currentEditorInstance = window.CmfcmfMediaModule.currentEditorInstance || null;
+
+/**
+ * Returns the attributes used for the popup window.
+ * @return {String}
+ */
+function getCmfcmfMediaModulePopupAttributes() {
+ var pWidth, pHeight;
+
+ pWidth = screen.width * 0.75;
+ pHeight = screen.height * 0.66;
+
+ return 'width=' + pWidth + ',height=' + pHeight + ',location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes';
+}
+
+/**
+ * Open a popup window with the finder triggered by an editor button.
+ */
+function CmfcmfMediaModuleFinderOpenPopup(editor, editorName) {
+ var popupUrl;
+
+ // Save editor for access in selector window
+ window.CmfcmfMediaModule.currentEditor = editorName;
+ window.CmfcmfMediaModule.currentEditorInstance = editor;
+
+ popupUrl = Routing.generate('cmfcmfmediamodule_finder_choosemethod');
+
+ if (editorName == 'ckeditor') {
+ editor.popup(popupUrl, /*width*/ '80%', /*height*/ '70%', getCmfcmfMediaModulePopupAttributes());
+ } else {
+ window.open(popupUrl, '_blank', getCmfcmfMediaModulePopupAttributes());
+ }
+}
diff --git a/Resources/public/js/Finder/popup.js b/Resources/public/js/Finder/popup.js
index 73b659a4..9c78fe65 100644
--- a/Resources/public/js/Finder/popup.js
+++ b/Resources/public/js/Finder/popup.js
@@ -3,15 +3,19 @@
$(document).on('cmfcmfmediamodule:media:finder:getbuttons', function (event) {
event.tableResult += '' +
- 'Full size '
+ Translator.__('Full size') + ''
;
event.tableResult += '' +
- 'Medium size '
+ Translator.__('Medium size') + ''
;
event.tableResult += '' +
- 'Small size '
+ Translator.__('Small size') + ''
+ ;
+ event.tableResult += '' + event.entity.title + '') + '">' +
+ Translator.__('Link') + ' '
;
});
@@ -21,8 +25,18 @@
case 'ckeditor':
window.opener.CmfcmfMediaModule.currentEditorInstance.insertHtml(html);
break;
+ case 'quill':
+ window.opener.CmfcmfMediaModule.currentEditorInstance.clipboard.dangerouslyPasteHTML(window.opener.CmfcmfMediaModule.currentEditorInstance.getLength(), html);
+ break;
+ case 'summernote':
+ html = jQuery(html).get(0);
+ window.opener.CmfcmfMediaModule.currentEditorInstance.invoke('insertNode', html);
+ break;
+ case 'tinymce':
+ window.opener.CmfcmfMediaModule.currentEditorInstance.insertContent(html);
+ break;
}
- window.opener.toastr['success']('The media object has been successfully inserted.', 'Media object inserted');
+ window.opener.toastr['success'](Translator.__('The medium has been successfully inserted.'), Translator.__('Medium inserted'));
window.opener.focus();
window.close();
});
diff --git a/Resources/public/js/Media/Display/slider.js b/Resources/public/js/Media/Display/slider.js
index 308b2373..e749bcae 100644
--- a/Resources/public/js/Media/Display/slider.js
+++ b/Resources/public/js/Media/Display/slider.js
@@ -1,9 +1,9 @@
(function ($) {
$(function () {
- var $slider = $('#cmfcmfmedia-display-slider');
+ var $slider = $('.cmfcmfmedia-display-slider');
$slider.slick({
autoplay: true,
- dots: $slider.children().size() <= 10,
+ dots: $slider.children().length <= 10,
slidesToShow: 1,
centerMode: true,
variableWidth: true,
diff --git a/Resources/public/js/Media/New/paste.js b/Resources/public/js/Media/New/paste.js
index 21129809..0b29ca0b 100644
--- a/Resources/public/js/Media/New/paste.js
+++ b/Resources/public/js/Media/New/paste.js
@@ -17,10 +17,10 @@
$.ajax({
url: Routing.generate('cmfcmfmediamodule_media_matchespaste'),
data: {pastedText: pastedText},
- method: "POST"
- }).success(function (mediaTypes) {
+ method: 'POST'
+ }).done(function (mediaTypes) {
if (mediaTypes.length == 0) {
- window.toastr["warning"](
+ window.toastr['warning'](
"It seems like it isn't supported (yet) or simply an unknown way of embedding. " +
"Please consider to open an issue.",
"Pasted url or embed code could not be parsed."
diff --git a/Resources/public/js/Media/New/upload.js b/Resources/public/js/Media/New/upload.js
index eee77911..01748dc9 100644
--- a/Resources/public/js/Media/New/upload.js
+++ b/Resources/public/js/Media/New/upload.js
@@ -9,7 +9,7 @@
function onOneFileUpload (file) {
getMediaTypeFromFiles([fileToArray(file)], function (response) {
if (!response.result[0]) {
- window.toastr['error']('This media type is currently not supported', "We're sorry!");
+ window.toastr['error'](Translator.__('This media type is currently not supported'), Translator.__("We're sorry!"));
$('#cmfcmfmedia-tab-content').spin(false);
return;
}
@@ -37,14 +37,14 @@
}
if (response.notFound > 0) {
if (!canUpload) {
- window.toastr['error']('Your files are not supported.', 'Cannot upload files!');
+ window.toastr['error'](Translator.__('These files are not supported.'), Translator.__('Cannot upload files!'));
return;
}
- window.toastr['warning']('Some of your files will not be uploaded.', 'Cannot upload everything!');
+ window.toastr['warning'](Translator.__('Some of these files will not be uploaded.'), Translator.__('Cannot upload everything!'));
}
openCollectionSelectModal(function (collection) {
- console.log('Selected collection', collection);
+ //console.log('Selected collection', collection);
formDataToAdd.collection = collection;
myDropzone.enqueueFiles(files);
@@ -115,32 +115,32 @@
previewsContainer: "#cmfcmfmedia-upload-previews", // Define the container to display the previews
clickable: "#cmfcmfmedia-upload-fileinput-btn",
dragover: function (event) {
- console.log('OVER');
- console.log(event);
+ //console.log('OVER');
+ //console.log(event);
},
dragleave: function (event) {
- console.log('LEAVE');
- console.log(event);
+ //console.log('LEAVE');
+ //console.log(event);
}
});
// Update the total progress bar
- myDropzone.on("totaluploadprogress", function(progress) {
- document.querySelector("#cmfcmfmedia-upload-total-progress .progress-bar").style.width = progress + "%";
+ myDropzone.on('totaluploadprogress', function(progress) {
+ document.querySelector("#cmfcmfmedia-upload-total-progress .progress-bar").style.width = progress + '%';
});
// Hide the total progress bar when nothing's uploading anymore
- myDropzone.on("queuecomplete", function(progress) {
- document.querySelector("#cmfcmfmedia-upload-total-progress").style.opacity = "0";
+ myDropzone.on('queuecomplete', function(progress) {
+ document.querySelector("#cmfcmfmedia-upload-total-progress").style.opacity = '0';
- window.toastr["success"]('', "Files have been uploaded");
+ window.toastr["success"]('', Translator.__('Files have been uploaded'));
});
- myDropzone.on("sending", function(file, xhr, formData) {
+ myDropzone.on('sending', function(file, xhr, formData) {
// Show the total progress bar when upload starts
- document.querySelector("#cmfcmfmedia-upload-total-progress").style.opacity = "1";
+ document.querySelector("#cmfcmfmedia-upload-total-progress").style.opacity = '1';
// And disable the start button
- file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
+ file.previewElement.querySelector('.start').setAttribute('disabled', 'disabled');
Object.keys(formDataToAdd).forEach(function (key) {
if (formDataToAdd[key] != null) {
@@ -149,14 +149,14 @@
});
});
- myDropzone.on("addedfile", function(file) {
+ myDropzone.on('addedfile', function(file) {
// Hookup the start button
- file.previewElement.querySelector(".start").onclick = function () {
+ file.previewElement.querySelector('.start').onclick = function () {
onOneFileUpload(file);
};
});
- myDropzone.on("success", function (file, response) {
+ myDropzone.on('success', function (file, response) {
if (response.openNewTabAndEdit) {
var parent = $('#cmfcmfmedia-upload-form-modal-collection-select').data('parent');
var parameters = '';
@@ -182,7 +182,7 @@
// Setup the buttons for all transfers
// The "add files" button doesn't need to be setup because the config
// `clickable` has already been specified.
- $("#cmfcmfmedia-upload-actions").find(".start").click(onAllFilesUpload);
+ $('#cmfcmfmedia-upload-actions').find('.start').click(onAllFilesUpload);
return myDropzone;
}
diff --git a/Resources/public/js/Media/New/web.js b/Resources/public/js/Media/New/web.js
index a908cd7b..02dca3f0 100644
--- a/Resources/public/js/Media/New/web.js
+++ b/Resources/public/js/Media/New/web.js
@@ -133,7 +133,7 @@
return;
}
$results.empty();
- $results.append(' Searching... ');
+ $results.append('' + Translator.__('Searching...') + ' ');
var dropdownValue = $btn.val();
if (typeof onSearch === "function") {
@@ -156,7 +156,7 @@
$results.empty();
if (resultSet.results.length == 0) {
$results.append(
- 'No results found '
+ '' + Translator.__('No results found.') + ' '
);
return;
}
@@ -171,7 +171,7 @@
var settings = window.CmfcmfMediaModule.Util.htmlAttrEncode(JSON.stringify(resultSet.results[i][0]));
resultTable += '' +
'Choose ' +
+ '-submit-btn" data-settings="' + settings + '">' + Translator.__('Choose') + ' ' +
' ';
resultTable += '';
}
@@ -180,14 +180,13 @@
};
$input.blur(actualCallback);
$btn.change(actualCallback);
- $(document).on("keypress", $input, function(event) {
+ $(document).on('keypress', $input, function(event) {
if (event.keyCode != 13) {
return true;
- } else {
- $input.blur();
- // Ignore ENTER -> Do not submit form on enter.
- return false;
}
+ $input.blur();
+ // Ignore ENTER -> Do not submit form on enter.
+ return false;
});
}
}
diff --git a/Resources/public/js/MediaType/Deezer/WebCreation.js b/Resources/public/js/MediaType/Deezer/WebCreation.js
index 7496c8fc..cb7ca362 100644
--- a/Resources/public/js/MediaType/Deezer/WebCreation.js
+++ b/Resources/public/js/MediaType/Deezer/WebCreation.js
@@ -8,13 +8,13 @@
new window.CmfcmfMediaModule.WebCreation.tableColumns.FirstLineBoldColumn('Result')
],
{
- everything: 'Everything',
- track: 'Tracks',
- album: 'Albums',
- artist: 'Artists',
- playlist: 'Playlists'
+ everything: Translator.__('Everything'),
+ track: Translator.__('Tracks'),
+ album: Translator.__('Albums'),
+ artist: Translator.__('Artists'),
+ playlist: Translator.__('Playlists')
},
- 'Search for artist, track, playlist or album',
+ Translator.__('Search for artist, track, playlist or album'),
function (searchInput, dropdownValue, onFinished) {
var query = '/search';
if (dropdownValue != 'everything') {
@@ -39,15 +39,15 @@
title = result.title;
results.push([
result.album.cover_small,
- 'Track',
- title + "\nArtist: " + result.artist.name + "\nAlbum: " + result.album.title
+ Translator.__('Track'),
+ title + "\n" + Translator.__('Artist') + ': ' + result.artist.name + "\n" + Translator.__('Album') + ': ' + result.album.title
]);
break;
case 'album':
title = result.title;
results.push([
result.cover_small,
- 'Album',
+ Translator.__('Album'),
title + "\n" + result.artist.name
]);
break;
@@ -55,16 +55,16 @@
title = result.name;
results.push([
result.picture_small,
- 'Artist',
- name + "\nFans: " + result.nb_fan
+ Translator.__('Artist'),
+ name + "\n" + Translator.__('Fans') + ': ' + result.nb_fan
]);
break;
case 'playlist':
title = result.title;
results.push([
result.picture_small,
- 'Playlist',
- title + "\nCreator: " + result.user.name + "\nTracks: " + result.nb_tracks
+ Translator.__('Playlist'),
+ title + "\n" + Translator.__('Creator') + ': ' + result.user.name + "\n" + Translator.__('Tracks') + ': ' + result.nb_tracks
]);
break;
default:
diff --git a/Resources/public/js/MediaType/Flickr/WebCreation.js b/Resources/public/js/MediaType/Flickr/WebCreation.js
index 569a7d1d..724c2bb8 100644
--- a/Resources/public/js/MediaType/Flickr/WebCreation.js
+++ b/Resources/public/js/MediaType/Flickr/WebCreation.js
@@ -37,9 +37,9 @@
new window.CmfcmfMediaModule.WebCreation.tableColumns.UrlColumn('License')
],
{
- everything: 'Everything'
+ everything: Translator.__('Everything')
},
- 'Search for images',
+ Translator.__('Search for images'),
function (searchInput, dropdownValue, onFinished) {
var license = '';//encodeURIComponent(license);
diff --git a/Resources/public/js/MediaType/SoundCloud/WebCreation.js b/Resources/public/js/MediaType/SoundCloud/WebCreation.js
index c009ed4a..cd3d321e 100644
--- a/Resources/public/js/MediaType/SoundCloud/WebCreation.js
+++ b/Resources/public/js/MediaType/SoundCloud/WebCreation.js
@@ -8,12 +8,12 @@
new window.CmfcmfMediaModule.WebCreation.tableColumns.FirstLineBoldColumn('Result')
],
{
- tracks: 'Tracks',
- groups: 'Groups',
- users: 'Artists',
- playlists: 'Playlists'
+ tracks: Translator.__('Tracks'),
+ groups: Translator.__('Groups'),
+ users: Translator.__('Artists'),
+ playlists: Translator.__('Playlists')
},
- 'Search for artist, track, playlist',
+ Translator.__('Search for artist, track, playlist'),
function (searchInput, dropdownValue, onFinished) {
var query = '/' + encodeURIComponent(dropdownValue) + '?q=' + encodeURIComponent(searchInput);
@@ -35,8 +35,8 @@
title = result.full_name;
results.push([
result.avatar_url,
- 'User',
- title + "\nFollowers: " + result.followers_count + "\nTracks: " + result.track_count
+ Translator.__('User'),
+ title + "\n" + Translator.__('Followers') + ': ' + result.followers_count + "\n" + Translator.__('Tracks') + ': ' + result.track_count
]);
break;
case 'track':
@@ -49,25 +49,25 @@
}
results.push([
image,
- 'Track',
- title + "\nLicense: " + result.license
+ Translator.__('Track'),
+ title + "\n" + Translator.__('License') + ': ' + result.license
]);
break;
case 'group':
title = result.name;
results.push([
result.artwork_url,
- 'Group',
- title + "\nDescription: " + result.short_description
+ Translator.__('Group'),
+ title + "\n" + Translator.__('Description') + ': ' + result.short_description
]);
break;
case 'playlist':
title = result.title;
results.push([
result.picture_small,
- 'Playlist',
- title + "\nDuration: " + (result.duration / 60) + ' min'
- + "\nTracks: " + result.tracks.length
+ Translator.__('Playlist'),
+ title + "\n" + Translator.__('Duration') + ': ' + (result.duration / 60) + ' ' + Translator.__('min')
+ + "\n" + Translator.__('Tracks') + ': ' + result.tracks.length
]);
break;
default:
diff --git a/Resources/public/js/MediaType/Twitter/WebCreation.js b/Resources/public/js/MediaType/Twitter/WebCreation.js
index dd841626..ff2cafc5 100644
--- a/Resources/public/js/MediaType/Twitter/WebCreation.js
+++ b/Resources/public/js/MediaType/Twitter/WebCreation.js
@@ -9,11 +9,11 @@
new window.CmfcmfMediaModule.WebCreation.tableColumns.TextColumn('')
],
{
- /*everything: 'Everything',*/
- tweets: 'Tweets'/*,
- users: 'Users'*/
+ /*everything: Translator.__('Everything'),*/
+ tweets: Translator.__('Tweets')/*,
+ users: Translator.__('Users')*/
},
- 'Search for tweets and users'
+ Translator.__('Search for tweets')
);
});
})(jQuery);
diff --git a/Resources/public/js/MediaType/YouTube/WebCreation.js b/Resources/public/js/MediaType/YouTube/WebCreation.js
index 6d16ba22..7c9f70cd 100644
--- a/Resources/public/js/MediaType/YouTube/WebCreation.js
+++ b/Resources/public/js/MediaType/YouTube/WebCreation.js
@@ -9,12 +9,12 @@
new window.CmfcmfMediaModule.WebCreation.tableColumns.FirstLineBoldColumn('Title')
],
{
- everything: 'Everything',
- video: 'Videos',
- channel: 'Channels',
- playlist: 'Playlists'
+ everything: Translator.__('Everything'),
+ video: Translator.__('Videos'),
+ channel: Translator.__('Channels'),
+ playlist: Translator.__('Playlists')
},
- 'Search for videos, channels and playlists'
+ Translator.__('Search for videos, channels and playlists')
);
});
})(jQuery);
diff --git a/Resources/public/js/Settings/Upgrade.js b/Resources/public/js/Settings/Upgrade.js
index ed81f457..5ee044c3 100644
--- a/Resources/public/js/Settings/Upgrade.js
+++ b/Resources/public/js/Settings/Upgrade.js
@@ -35,7 +35,7 @@
} else {
$li.addClass('text-danger');
$upgradeButton.removeClass('btn-primary').addClass('btn-danger');
- $upgradeButton.text('Upgrade failed.');
+ $upgradeButton.text(Translator.__('Upgrade failed.'));
alert(result.message);
}
})
diff --git a/Resources/public/js/util.js b/Resources/public/js/util.js
index c41db2fa..06c19aa5 100644
--- a/Resources/public/js/util.js
+++ b/Resources/public/js/util.js
@@ -1,8 +1,10 @@
(function ($) {
- window.toastr.options = {
- "progressBar": true,
- "closeButton": true
- };
+ if ('undefined' != typeof window.toastr) {
+ window.toastr.options = {
+ 'progressBar': true,
+ 'closeButton': true
+ };
+ }
$(function () {
window.CmfcmfMediaModule = window.CmfcmfMediaModule || {};
window.CmfcmfMediaModule.Util = {
@@ -11,13 +13,17 @@
},
Ajax: {
fail: function (data) {
- var errorText = "Sorry, the AJAX request could not be finished. Please try again.";
+ var errorText = Translator.__('Sorry, the AJAX request could not be finished. Please try again.');
if (data.responseJSON && data.responseJSON.error) {
errorText = data.responseJSON.error;
} else if (data.status == 403) {
- errorText = "You do not have permission to execute this action."
+ errorText = Translator.__('You do not have permission to execute this action.');
+ }
+ if ('undefined' != typeof window.toastr) {
+ window.toastr['error'](errorText, Translator.__('Something went wrong!'));
+ } else {
+ alert(Translator.__('Something went wrong!') + ' ' + errorText);
}
- window.toastr["error"](errorText, "Something went wrong!");
},
makeExternalRequest: function (url, done, fail, always) {
var xmlhttp;
@@ -27,7 +33,7 @@
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
+ xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
@@ -37,13 +43,13 @@
} else {
fail();
}
- if (typeof always == "function") {
+ if (typeof always == 'function') {
always();
}
}
};
- xmlhttp.open("GET", url, true);
+ xmlhttp.open('GET', url, true);
xmlhttp.send();
}
},
diff --git a/Resources/public/js/vendor/Sortable.min.js b/Resources/public/js/vendor/Sortable.min.js
index 45b1cb8e..573538f0 100644
--- a/Resources/public/js/vendor/Sortable.min.js
+++ b/Resources/public/js/vendor/Sortable.min.js
@@ -1,2 +1,2 @@
-/*! Sortable 1.3.0-rc2 - MIT | git://github.com/rubaxa/Sortable.git */
-!function(a){"use strict";"function"==typeof define&&define.amd?define(a):"undefined"!=typeof module&&"undefined"!=typeof module.exports?module.exports=a():"undefined"!=typeof Package?Sortable=a():window.Sortable=a()}(function(){"use strict";function a(a,b){this.el=a,this.options=b=r({},b),a[L]=this;var c={group:Math.random(),sort:!0,disabled:!1,store:null,handle:null,scroll:!0,scrollSensitivity:30,scrollSpeed:10,draggable:/[uo]l/i.test(a.nodeName)?"li":">*",ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",ignore:"a, img",filter:null,animation:0,setData:function(a,b){a.setData("Text",b.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1};for(var d in c)!(d in b)&&(b[d]=c[d]);V(b);for(var f in this)"_"===f.charAt(0)&&(this[f]=this[f].bind(this));this.nativeDraggable=b.forceFallback?!1:P,e(a,"mousedown",this._onTapStart),e(a,"touchstart",this._onTapStart),this.nativeDraggable&&(e(a,"dragover",this),e(a,"dragenter",this)),T.push(this._onDragOver),b.store&&this.sort(b.store.get(this))}function b(a){v&&v.state!==a&&(h(v,"display",a?"none":""),!a&&v.state&&w.insertBefore(v,s),v.state=a)}function c(a,b,c){if(a){c=c||N,b=b.split(".");var d=b.shift().toUpperCase(),e=new RegExp("\\s("+b.join("|")+")(?=\\s)","g");do if(">*"===d&&a.parentNode===c||(""===d||a.nodeName.toUpperCase()==d)&&(!b.length||((" "+a.className+" ").match(e)||[]).length==b.length))return a;while(a!==c&&(a=a.parentNode))}return null}function d(a){a.dataTransfer&&(a.dataTransfer.dropEffect="move"),a.preventDefault()}function e(a,b,c){a.addEventListener(b,c,!1)}function f(a,b,c){a.removeEventListener(b,c,!1)}function g(a,b,c){if(a)if(a.classList)a.classList[c?"add":"remove"](b);else{var d=(" "+a.className+" ").replace(K," ").replace(" "+b+" "," ");a.className=(d+(c?" "+b:"")).replace(K," ")}}function h(a,b,c){var d=a&&a.style;if(d){if(void 0===c)return N.defaultView&&N.defaultView.getComputedStyle?c=N.defaultView.getComputedStyle(a,""):a.currentStyle&&(c=a.currentStyle),void 0===b?c:c[b];b in d||(b="-webkit-"+b),d[b]=c+("string"==typeof c?"":"px")}}function i(a,b,c){if(a){var d=a.getElementsByTagName(b),e=0,f=d.length;if(c)for(;f>e;e++)c(d[e],e);return d}return[]}function j(a,b,c,d,e,f,g){var h=N.createEvent("Event"),i=(a||b[L]).options,j="on"+c.charAt(0).toUpperCase()+c.substr(1);h.initEvent(c,!0,!0),h.to=b,h.from=e||b,h.item=d||b,h.clone=v,h.oldIndex=f,h.newIndex=g,b.dispatchEvent(h),i[j]&&i[j].call(a,h)}function k(a,b,c,d,e,f){var g,h,i=a[L],j=i.options.onMove;return g=N.createEvent("Event"),g.initEvent("move",!0,!0),g.to=b,g.from=a,g.dragged=c,g.draggedRect=d,g.related=e||b,g.relatedRect=f||b.getBoundingClientRect(),a.dispatchEvent(g),j&&(h=j.call(i,g)),h}function l(a){a.draggable=!1}function m(){R=!1}function n(a,b){var c=a.lastElementChild,d=c.getBoundingClientRect();return(b.clientY-(d.top+d.height)>5||b.clientX-(d.right+d.width)>5)&&c}function o(a){for(var b=a.tagName+a.className+a.src+a.href+a.textContent,c=b.length,d=0;c--;)d+=b.charCodeAt(c);return d.toString(36)}function p(a){var b=0;if(!a||!a.parentNode)return-1;for(;a&&(a=a.previousElementSibling);)"TEMPLATE"!==a.nodeName.toUpperCase()&&b++;return b}function q(a,b){var c,d;return function(){void 0===c&&(c=arguments,d=this,setTimeout(function(){1===c.length?a.call(d,c[0]):a.apply(d,c),c=void 0},b))}}function r(a,b){if(a&&b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}var s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J={},K=/\s+/g,L="Sortable"+(new Date).getTime(),M=window,N=M.document,O=M.parseInt,P=!!("draggable"in N.createElement("div")),Q=function(a){return a=N.createElement("x"),a.style.cssText="pointer-events:auto","auto"===a.style.pointerEvents}(),R=!1,S=Math.abs,T=([].slice,[]),U=q(function(a,b,c){if(c&&b.scroll){var d,e,f,g,h=b.scrollSensitivity,i=b.scrollSpeed,j=a.clientX,k=a.clientY,l=window.innerWidth,m=window.innerHeight;if(z!==c&&(y=b.scroll,z=c,y===!0)){y=c;do if(y.offsetWidth=l-j)-(h>=j),g=(h>=m-k)-(h>=k),(f||g)&&(d=M)),(J.vx!==f||J.vy!==g||J.el!==d)&&(J.el=d,J.vx=f,J.vy=g,clearInterval(J.pid),d&&(J.pid=setInterval(function(){d===M?M.scrollTo(M.pageXOffset+f*i,M.pageYOffset+g*i):(g&&(d.scrollTop+=g*i),f&&(d.scrollLeft+=f*i))},24)))}},30),V=function(a){var b=a.group;b&&"object"==typeof b||(b=a.group={name:b}),["pull","put"].forEach(function(a){a in b||(b[a]=!0)}),a.groups=" "+b.name+(b.put.join?" "+b.put.join(" "):"")+" "};return a.prototype={constructor:a,_onTapStart:function(a){var b=this,d=this.el,e=this.options,f=a.type,g=a.touches&&a.touches[0],h=(g||a).target,i=h,k=e.filter;if(!("mousedown"===f&&0!==a.button||e.disabled)&&(h=c(h,e.draggable,d))){if(D=p(h),"function"==typeof k){if(k.call(this,a,h,this))return j(b,i,"filter",h,d,D),void a.preventDefault()}else if(k&&(k=k.split(",").some(function(a){return a=c(i,a.trim(),d),a?(j(b,a,"filter",h,d,D),!0):void 0})))return void a.preventDefault();(!e.handle||c(i,e.handle,d))&&this._prepareDragStart(a,g,h)}},_prepareDragStart:function(a,b,c){var d,f=this,h=f.el,j=f.options,k=h.ownerDocument;c&&!s&&c.parentNode===h&&(G=a,w=h,s=c,t=s.parentNode,x=s.nextSibling,F=j.group,d=function(){f._disableDelayedDrag(),s.draggable=!0,g(s,f.options.chosenClass,!0),f._triggerDragStart(b)},j.ignore.split(",").forEach(function(a){i(s,a.trim(),l)}),e(k,"mouseup",f._onDrop),e(k,"touchend",f._onDrop),e(k,"touchcancel",f._onDrop),j.delay?(e(k,"mouseup",f._disableDelayedDrag),e(k,"touchend",f._disableDelayedDrag),e(k,"touchcancel",f._disableDelayedDrag),e(k,"mousemove",f._disableDelayedDrag),e(k,"touchmove",f._disableDelayedDrag),f._dragStartTimer=setTimeout(d,j.delay)):d())},_disableDelayedDrag:function(){var a=this.el.ownerDocument;clearTimeout(this._dragStartTimer),f(a,"mouseup",this._disableDelayedDrag),f(a,"touchend",this._disableDelayedDrag),f(a,"touchcancel",this._disableDelayedDrag),f(a,"mousemove",this._disableDelayedDrag),f(a,"touchmove",this._disableDelayedDrag)},_triggerDragStart:function(a){a?(G={target:s,clientX:a.clientX,clientY:a.clientY},this._onDragStart(G,"touch")):this.nativeDraggable?(e(s,"dragend",this),e(w,"dragstart",this._onDragStart)):this._onDragStart(G,!0);try{N.selection?N.selection.empty():window.getSelection().removeAllRanges()}catch(b){}},_dragStarted:function(){w&&s&&(g(s,this.options.ghostClass,!0),a.active=this,j(this,w,"start",s,w,D))},_emulateDragOver:function(){if(H){if(this._lastX===H.clientX&&this._lastY===H.clientY)return;this._lastX=H.clientX,this._lastY=H.clientY,Q||h(u,"display","none");var a=N.elementFromPoint(H.clientX,H.clientY),b=a,c=" "+this.options.group.name,d=T.length;if(b)do{if(b[L]&&b[L].options.groups.indexOf(c)>-1){for(;d--;)T[d]({clientX:H.clientX,clientY:H.clientY,target:a,rootEl:b});break}a=b}while(b=b.parentNode);Q||h(u,"display","")}},_onTouchMove:function(b){if(G){a.active||this._dragStarted(),this._appendGhost();var c=b.touches?b.touches[0]:b,d=c.clientX-G.clientX,e=c.clientY-G.clientY,f=b.touches?"translate3d("+d+"px,"+e+"px,0)":"translate("+d+"px,"+e+"px)";I=!0,H=c,h(u,"webkitTransform",f),h(u,"mozTransform",f),h(u,"msTransform",f),h(u,"transform",f),b.preventDefault()}},_appendGhost:function(){if(!u){var a,b=s.getBoundingClientRect(),c=h(s);u=s.cloneNode(!0),g(u,this.options.ghostClass,!1),g(u,this.options.fallbackClass,!0),h(u,"top",b.top-O(c.marginTop,10)),h(u,"left",b.left-O(c.marginLeft,10)),h(u,"width",b.width),h(u,"height",b.height),h(u,"opacity","0.8"),h(u,"position","fixed"),h(u,"zIndex","100000"),h(u,"pointerEvents","none"),this.options.fallbackOnBody&&N.body.appendChild(u)||w.appendChild(u),a=u.getBoundingClientRect(),h(u,"width",2*b.width-a.width),h(u,"height",2*b.height-a.height)}},_onDragStart:function(a,b){var c=a.dataTransfer,d=this.options;this._offUpEvents(),"clone"==F.pull&&(v=s.cloneNode(!0),h(v,"display","none"),w.insertBefore(v,s)),b?("touch"===b?(e(N,"touchmove",this._onTouchMove),e(N,"touchend",this._onDrop),e(N,"touchcancel",this._onDrop)):(e(N,"mousemove",this._onTouchMove),e(N,"mouseup",this._onDrop)),this._loopId=setInterval(this._emulateDragOver,50)):(c&&(c.effectAllowed="move",d.setData&&d.setData.call(this,c,s)),e(N,"drop",this),setTimeout(this._dragStarted,0))},_onDragOver:function(a){var d,e,f,g=this.el,i=this.options,j=i.group,l=j.put,o=F===j,p=i.sort;if(void 0!==a.preventDefault&&(a.preventDefault(),!i.dragoverBubble&&a.stopPropagation()),I=!0,F&&!i.disabled&&(o?p||(f=!w.contains(s)):F.pull&&l&&(F.name===j.name||l.indexOf&&~l.indexOf(F.name)))&&(void 0===a.rootEl||a.rootEl===this.el)){if(U(a,i,this.el),R)return;if(d=c(a.target,i.draggable,g),e=s.getBoundingClientRect(),f)return b(!0),void(v||x?w.insertBefore(s,v||x):p||w.appendChild(s));if(0===g.children.length||g.children[0]===u||g===a.target&&(d=n(g,a))){if(d){if(d.animated)return;r=d.getBoundingClientRect()}b(o),k(w,g,s,e,d,r)!==!1&&(s.contains(g)||(g.appendChild(s),t=g),this._animate(e,s),d&&this._animate(r,d))}else if(d&&!d.animated&&d!==s&&void 0!==d.parentNode[L]){A!==d&&(A=d,B=h(d),C=h(d.parentNode));var q,r=d.getBoundingClientRect(),y=r.right-r.left,z=r.bottom-r.top,D=/left|right|inline/.test(B.cssFloat+B.display)||"flex"==C.display&&0===C["flex-direction"].indexOf("row"),E=d.offsetWidth>s.offsetWidth,G=d.offsetHeight>s.offsetHeight,H=(D?(a.clientX-r.left)/y:(a.clientY-r.top)/z)>.5,J=d.nextElementSibling,K=k(w,g,s,e,d,r);if(K!==!1){if(R=!0,setTimeout(m,30),b(o),1===K||-1===K)q=1===K;else if(D){var M=s.offsetTop,N=d.offsetTop;q=M===N?d.previousElementSibling===s&&!E||H&&E:N>M}else q=J!==s&&!G||H&&G;s.contains(g)||(q&&!J?g.appendChild(s):d.parentNode.insertBefore(s,q?J:d)),t=s.parentNode,this._animate(e,s),this._animate(r,d)}}}},_animate:function(a,b){var c=this.options.animation;if(c){var d=b.getBoundingClientRect();h(b,"transition","none"),h(b,"transform","translate3d("+(a.left-d.left)+"px,"+(a.top-d.top)+"px,0)"),b.offsetWidth,h(b,"transition","all "+c+"ms"),h(b,"transform","translate3d(0,0,0)"),clearTimeout(b.animated),b.animated=setTimeout(function(){h(b,"transition",""),h(b,"transform",""),b.animated=!1},c)}},_offUpEvents:function(){var a=this.el.ownerDocument;f(N,"touchmove",this._onTouchMove),f(a,"mouseup",this._onDrop),f(a,"touchend",this._onDrop),f(a,"touchcancel",this._onDrop)},_onDrop:function(b){var c=this.el,d=this.options;clearInterval(this._loopId),clearInterval(J.pid),clearTimeout(this._dragStartTimer),f(N,"mousemove",this._onTouchMove),this.nativeDraggable&&(f(N,"drop",this),f(c,"dragstart",this._onDragStart)),this._offUpEvents(),b&&(I&&(b.preventDefault(),!d.dropBubble&&b.stopPropagation()),u&&u.parentNode.removeChild(u),s&&(this.nativeDraggable&&f(s,"dragend",this),l(s),g(s,this.options.ghostClass,!1),g(s,this.options.chosenClass,!1),w!==t?(E=p(s),E>=0&&(j(null,t,"sort",s,w,D,E),j(this,w,"sort",s,w,D,E),j(null,t,"add",s,w,D,E),j(this,w,"remove",s,w,D,E))):(v&&v.parentNode.removeChild(v),s.nextSibling!==x&&(E=p(s),E>=0&&(j(this,w,"update",s,w,D,E),j(this,w,"sort",s,w,D,E)))),a.active&&((null===E||-1===E)&&(E=D),j(this,w,"end",s,w,D,E),this.save())),w=s=t=u=x=v=y=z=G=H=I=E=A=B=F=a.active=null)},handleEvent:function(a){var b=a.type;"dragover"===b||"dragenter"===b?s&&(this._onDragOver(a),d(a)):("drop"===b||"dragend"===b)&&this._onDrop(a)},toArray:function(){for(var a,b=[],d=this.el.children,e=0,f=d.length,g=this.options;f>e;e++)a=d[e],c(a,g.draggable,this.el)&&b.push(a.getAttribute(g.dataIdAttr)||o(a));return b},sort:function(a){var b={},d=this.el;this.toArray().forEach(function(a,e){var f=d.children[e];c(f,this.options.draggable,d)&&(b[a]=f)},this),a.forEach(function(a){b[a]&&(d.removeChild(b[a]),d.appendChild(b[a]))})},save:function(){var a=this.options.store;a&&a.set(this)},closest:function(a,b){return c(a,b||this.options.draggable,this.el)},option:function(a,b){var c=this.options;return void 0===b?c[a]:(c[a]=b,void("group"===a&&V(c)))},destroy:function(){var a=this.el;a[L]=null,f(a,"mousedown",this._onTapStart),f(a,"touchstart",this._onTapStart),this.nativeDraggable&&(f(a,"dragover",this),f(a,"dragenter",this)),Array.prototype.forEach.call(a.querySelectorAll("[draggable]"),function(a){a.removeAttribute("draggable")}),T.splice(T.indexOf(this._onDragOver),1),this._onDrop(),this.el=a=null}},a.utils={on:e,off:f,css:h,find:i,is:function(a,b){return!!c(a,b,a)},extend:r,throttle:q,closest:c,toggleClass:g,index:p},a.create=function(b,c){return new a(b,c)},a.version="1.3.0-rc2",a});
\ No newline at end of file
+/*! Sortable 1.6.0 - MIT | git://github.com/rubaxa/Sortable.git */
+!function(a){"use strict";"function"==typeof define&&define.amd?define(a):"undefined"!=typeof module&&"undefined"!=typeof module.exports?module.exports=a():window.Sortable=a()}(function(){"use strict";function a(a,b){if(!a||!a.nodeType||1!==a.nodeType)throw"Sortable: `el` must be HTMLElement, and not "+{}.toString.call(a);this.el=a,this.options=b=t({},b),a[T]=this;var c={group:Math.random(),sort:!0,disabled:!1,store:null,handle:null,scroll:!0,scrollSensitivity:30,scrollSpeed:10,draggable:/[uo]l/i.test(a.nodeName)?"li":">*",ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,setData:function(a,b){a.setData("Text",b.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0}};for(var d in c)!(d in b)&&(b[d]=c[d]);ga(b);for(var e in this)"_"===e.charAt(0)&&"function"==typeof this[e]&&(this[e]=this[e].bind(this));this.nativeDraggable=!b.forceFallback&&$,f(a,"mousedown",this._onTapStart),f(a,"touchstart",this._onTapStart),f(a,"pointerdown",this._onTapStart),this.nativeDraggable&&(f(a,"dragover",this),f(a,"dragenter",this)),ea.push(this._onDragOver),b.store&&this.sort(b.store.get(this))}function b(a,b){"clone"!==a.lastPullMode&&(b=!0),z&&z.state!==b&&(i(z,"display",b?"none":""),b||z.state&&(a.options.group.revertClone?(A.insertBefore(z,B),a._animate(w,z)):A.insertBefore(z,w)),z.state=b)}function c(a,b,c){if(a){c=c||V;do if(">*"===b&&a.parentNode===c||r(a,b))return a;while(a=d(a))}return null}function d(a){var b=a.host;return b&&b.nodeType?b:a.parentNode}function e(a){a.dataTransfer&&(a.dataTransfer.dropEffect="move"),a.preventDefault()}function f(a,b,c){a.addEventListener(b,c,Z)}function g(a,b,c){a.removeEventListener(b,c,Z)}function h(a,b,c){if(a)if(a.classList)a.classList[c?"add":"remove"](b);else{var d=(" "+a.className+" ").replace(R," ").replace(" "+b+" "," ");a.className=(d+(c?" "+b:"")).replace(R," ")}}function i(a,b,c){var d=a&&a.style;if(d){if(void 0===c)return V.defaultView&&V.defaultView.getComputedStyle?c=V.defaultView.getComputedStyle(a,""):a.currentStyle&&(c=a.currentStyle),void 0===b?c:c[b];b in d||(b="-webkit-"+b),d[b]=c+("string"==typeof c?"":"px")}}function j(a,b,c){if(a){var d=a.getElementsByTagName(b),e=0,f=d.length;if(c)for(;e5||b.clientX-(d.left+d.width)>5}function p(a){for(var b=a.tagName+a.className+a.src+a.href+a.textContent,c=b.length,d=0;c--;)d+=b.charCodeAt(c);return d.toString(36)}function q(a,b){var c=0;if(!a||!a.parentNode)return-1;for(;a&&(a=a.previousElementSibling);)"TEMPLATE"===a.nodeName.toUpperCase()||">*"!==b&&!r(a,b)||c++;return c}function r(a,b){if(a){b=b.split(".");var c=b.shift().toUpperCase(),d=new RegExp("\\s("+b.join("|")+")(?=\\s)","g");return!(""!==c&&a.nodeName.toUpperCase()!=c||b.length&&((" "+a.className+" ").match(d)||[]).length!=b.length)}return!1}function s(a,b){var c,d;return function(){void 0===c&&(c=arguments,d=this,setTimeout(function(){1===c.length?a.call(d,c[0]):a.apply(d,c),c=void 0},b))}}function t(a,b){if(a&&b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function u(a){return X?X(a).clone(!0)[0]:Y&&Y.dom?Y.dom(a).cloneNode(!0):a.cloneNode(!0)}function v(a){for(var b=a.getElementsByTagName("input"),c=b.length;c--;){var d=b[c];d.checked&&da.push(d)}}if("undefined"==typeof window||!window.document)return function(){throw new Error("Sortable.js requires a window with a document")};var w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q={},R=/\s+/g,S=/left|right|inline/,T="Sortable"+(new Date).getTime(),U=window,V=U.document,W=U.parseInt,X=U.jQuery||U.Zepto,Y=U.Polymer,Z=!1,$=!!("draggable"in V.createElement("div")),_=function(a){return!navigator.userAgent.match(/Trident.*rv[ :]?11\./)&&(a=V.createElement("x"),a.style.cssText="pointer-events:auto","auto"===a.style.pointerEvents)}(),aa=!1,ba=Math.abs,ca=Math.min,da=[],ea=[],fa=s(function(a,b,c){if(c&&b.scroll){var d,e,f,g,h,i,j=c[T],k=b.scrollSensitivity,l=b.scrollSpeed,m=a.clientX,n=a.clientY,o=window.innerWidth,p=window.innerHeight;if(E!==c&&(D=b.scroll,E=c,F=b.scrollFn,D===!0)){D=c;do if(D.offsetWidth-1:e==a)}}var c={},d=a.group;d&&"object"==typeof d||(d={name:d}),c.name=d.name,c.checkPull=b(d.pull,!0),c.checkPut=b(d.put),c.revertClone=d.revertClone,a.group=c};a.prototype={constructor:a,_onTapStart:function(a){var b,d=this,e=this.el,f=this.options,g=f.preventOnFilter,h=a.type,i=a.touches&&a.touches[0],j=(i||a).target,l=a.target.shadowRoot&&a.path[0]||j,m=f.filter;if(v(e),!w&&!("mousedown"===h&&0!==a.button||f.disabled)&&(j=c(j,f.draggable,e),j&&C!==j)){if(b=q(j,f.draggable),"function"==typeof m){if(m.call(this,a,j,this))return k(d,l,"filter",j,e,b),void(g&&a.preventDefault())}else if(m&&(m=m.split(",").some(function(a){if(a=c(l,a.trim(),e))return k(d,a,"filter",j,e,b),!0})))return void(g&&a.preventDefault());f.handle&&!c(l,f.handle,e)||this._prepareDragStart(a,i,j,b)}},_prepareDragStart:function(a,b,c,d){var e,g=this,i=g.el,l=g.options,n=i.ownerDocument;c&&!w&&c.parentNode===i&&(N=a,A=i,w=c,x=w.parentNode,B=w.nextSibling,C=c,L=l.group,J=d,this._lastX=(b||a).clientX,this._lastY=(b||a).clientY,w.style["will-change"]="transform",e=function(){g._disableDelayedDrag(),w.draggable=g.nativeDraggable,h(w,l.chosenClass,!0),g._triggerDragStart(a,b),k(g,A,"choose",w,A,J)},l.ignore.split(",").forEach(function(a){j(w,a.trim(),m)}),f(n,"mouseup",g._onDrop),f(n,"touchend",g._onDrop),f(n,"touchcancel",g._onDrop),f(n,"pointercancel",g._onDrop),f(n,"selectstart",g),l.delay?(f(n,"mouseup",g._disableDelayedDrag),f(n,"touchend",g._disableDelayedDrag),f(n,"touchcancel",g._disableDelayedDrag),f(n,"mousemove",g._disableDelayedDrag),f(n,"touchmove",g._disableDelayedDrag),f(n,"pointermove",g._disableDelayedDrag),g._dragStartTimer=setTimeout(e,l.delay)):e())},_disableDelayedDrag:function(){var a=this.el.ownerDocument;clearTimeout(this._dragStartTimer),g(a,"mouseup",this._disableDelayedDrag),g(a,"touchend",this._disableDelayedDrag),g(a,"touchcancel",this._disableDelayedDrag),g(a,"mousemove",this._disableDelayedDrag),g(a,"touchmove",this._disableDelayedDrag),g(a,"pointermove",this._disableDelayedDrag)},_triggerDragStart:function(a,b){b=b||("touch"==a.pointerType?a:null),b?(N={target:w,clientX:b.clientX,clientY:b.clientY},this._onDragStart(N,"touch")):this.nativeDraggable?(f(w,"dragend",this),f(A,"dragstart",this._onDragStart)):this._onDragStart(N,!0);try{V.selection?setTimeout(function(){V.selection.empty()}):window.getSelection().removeAllRanges()}catch(a){}},_dragStarted:function(){if(A&&w){var b=this.options;h(w,b.ghostClass,!0),h(w,b.dragClass,!1),a.active=this,k(this,A,"start",w,A,J)}else this._nulling()},_emulateDragOver:function(){if(O){if(this._lastX===O.clientX&&this._lastY===O.clientY)return;this._lastX=O.clientX,this._lastY=O.clientY,_||i(y,"display","none");var a=V.elementFromPoint(O.clientX,O.clientY),b=a,c=ea.length;if(b)do{if(b[T]){for(;c--;)ea[c]({clientX:O.clientX,clientY:O.clientY,target:a,rootEl:b});break}a=b}while(b=b.parentNode);_||i(y,"display","")}},_onTouchMove:function(b){if(N){var c=this.options,d=c.fallbackTolerance,e=c.fallbackOffset,f=b.touches?b.touches[0]:b,g=f.clientX-N.clientX+e.x,h=f.clientY-N.clientY+e.y,j=b.touches?"translate3d("+g+"px,"+h+"px,0)":"translate("+g+"px,"+h+"px)";if(!a.active){if(d&&ca(ba(f.clientX-this._lastX),ba(f.clientY-this._lastY))w.offsetWidth,D=e.offsetHeight>w.offsetHeight,E=(v?(d.clientX-g.left)/t:(d.clientY-g.top)/u)>.5,F=e.nextElementSibling,J=!1;if(v){var K=w.offsetTop,N=e.offsetTop;J=K===N?e.previousElementSibling===w&&!C||E&&C:e.previousElementSibling===w||w.previousElementSibling===e?(d.clientY-g.top)/u>.5:N>K}else r||(J=F!==w&&!D||E&&D);var O=l(A,j,w,f,e,g,d,J);O!==!1&&(1!==O&&O!==-1||(J=1===O),aa=!0,setTimeout(n,30),b(p,q),w.contains(j)||(J&&!F?j.appendChild(w):e.parentNode.insertBefore(w,J?F:e)),x=w.parentNode,this._animate(f,w),this._animate(g,e))}}},_animate:function(a,b){var c=this.options.animation;if(c){var d=b.getBoundingClientRect();1===a.nodeType&&(a=a.getBoundingClientRect()),i(b,"transition","none"),i(b,"transform","translate3d("+(a.left-d.left)+"px,"+(a.top-d.top)+"px,0)"),b.offsetWidth,i(b,"transition","all "+c+"ms"),i(b,"transform","translate3d(0,0,0)"),clearTimeout(b.animated),b.animated=setTimeout(function(){i(b,"transition",""),i(b,"transform",""),b.animated=!1},c)}},_offUpEvents:function(){var a=this.el.ownerDocument;g(V,"touchmove",this._onTouchMove),g(V,"pointermove",this._onTouchMove),g(a,"mouseup",this._onDrop),g(a,"touchend",this._onDrop),g(a,"pointerup",this._onDrop),g(a,"touchcancel",this._onDrop),g(a,"pointercancel",this._onDrop),g(a,"selectstart",this)},_onDrop:function(b){var c=this.el,d=this.options;clearInterval(this._loopId),clearInterval(Q.pid),clearTimeout(this._dragStartTimer),g(V,"mousemove",this._onTouchMove),this.nativeDraggable&&(g(V,"drop",this),g(c,"dragstart",this._onDragStart)),this._offUpEvents(),b&&(P&&(b.preventDefault(),!d.dropBubble&&b.stopPropagation()),y&&y.parentNode&&y.parentNode.removeChild(y),A!==x&&"clone"===a.active.lastPullMode||z&&z.parentNode&&z.parentNode.removeChild(z),w&&(this.nativeDraggable&&g(w,"dragend",this),m(w),w.style["will-change"]="",h(w,this.options.ghostClass,!1),h(w,this.options.chosenClass,!1),k(this,A,"unchoose",w,A,J),A!==x?(K=q(w,d.draggable),K>=0&&(k(null,x,"add",w,A,J,K),k(this,A,"remove",w,A,J,K),k(null,x,"sort",w,A,J,K),k(this,A,"sort",w,A,J,K))):w.nextSibling!==B&&(K=q(w,d.draggable),K>=0&&(k(this,A,"update",w,A,J,K),k(this,A,"sort",w,A,J,K))),a.active&&(null!=K&&K!==-1||(K=J),k(this,A,"end",w,A,J,K),this.save()))),this._nulling()},_nulling:function(){A=w=x=y=B=z=C=D=E=N=O=P=K=G=H=M=L=a.active=null,da.forEach(function(a){a.checked=!0}),da.length=0},handleEvent:function(a){switch(a.type){case"drop":case"dragend":this._onDrop(a);break;case"dragover":case"dragenter":w&&(this._onDragOver(a),e(a));break;case"selectstart":a.preventDefault()}},toArray:function(){for(var a,b=[],d=this.el.children,e=0,f=d.length,g=this.options;e 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+
+ for (var _iterator = callbacks, _isArray = true, _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
+ var _ref;
+
+ if (_isArray) {
+ if (_i >= _iterator.length) break;
+ _ref = _iterator[_i++];
+ } else {
+ _i = _iterator.next();
+ if (_i.done) break;
+ _ref = _i.value;
+ }
+
+ var callback = _ref;
+
callback.apply(this, args);
}
}
- return this;
- };
-
- Emitter.prototype.removeListener = Emitter.prototype.off;
- Emitter.prototype.removeAllListeners = Emitter.prototype.off;
+ return this;
+ }
- Emitter.prototype.removeEventListener = Emitter.prototype.off;
+ // Remove event listener for given event. If fn is not provided, all event
+ // listeners for that event will be removed. If neither is provided, all
+ // event listeners will be removed.
- Emitter.prototype.off = function(event, fn) {
- var callback, callbacks, i, _i, _len;
+ }, {
+ key: "off",
+ value: function off(event, fn) {
if (!this._callbacks || arguments.length === 0) {
this._callbacks = {};
return this;
}
- callbacks = this._callbacks[event];
+
+ // specific event
+ var callbacks = this._callbacks[event];
if (!callbacks) {
return this;
}
+
+ // remove all handlers
if (arguments.length === 1) {
delete this._callbacks[event];
return this;
}
- for (i = _i = 0, _len = callbacks.length; _i < _len; i = ++_i) {
- callback = callbacks[i];
+
+ // remove specific handler
+ for (var i = 0; i < callbacks.length; i++) {
+ var callback = callbacks[i];
if (callback === fn) {
callbacks.splice(i, 1);
break;
}
}
+
return this;
- };
+ }
+ }]);
- return Emitter;
+ return Emitter;
+}();
- })();
+var Dropzone = function (_Emitter) {
+ _inherits(Dropzone, _Emitter);
- Dropzone = (function(_super) {
- var extend, resolveOption;
+ _createClass(Dropzone, null, [{
+ key: "initClass",
+ value: function initClass() {
- __extends(Dropzone, _super);
+ // Exposing the emitter class, mainly for tests
+ this.prototype.Emitter = Emitter;
+
+ /*
+ This is a list of all available events you can register on a dropzone object.
+ You can register an event handler like this:
+ dropzone.on("dragEnter", function() { });
+ */
+ this.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "addedfiles", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached", "queuecomplete"];
+
+ this.prototype.defaultOptions = {
+ /**
+ * Has to be specified on elements other than form (or when the form
+ * doesn't have an `action` attribute). You can also
+ * provide a function that will be called with `files` and
+ * must return the url (since `v3.12.0`)
+ */
+ url: null,
+
+ /**
+ * Can be changed to `"put"` if necessary. You can also provide a function
+ * that will be called with `files` and must return the method (since `v3.12.0`).
+ */
+ method: "post",
+
+ /**
+ * Will be set on the XHRequest.
+ */
+ withCredentials: false,
+
+ /**
+ * The timeout for the XHR requests in milliseconds (since `v4.4.0`).
+ */
+ timeout: 30000,
+
+ /**
+ * How many file uploads to process in parallel (See the
+ * Enqueuing file uploads* documentation section for more info)
+ */
+ parallelUploads: 2,
+
+ /**
+ * Whether to send multiple files in one request. If
+ * this it set to true, then the fallback file input element will
+ * have the `multiple` attribute as well. This option will
+ * also trigger additional events (like `processingmultiple`). See the events
+ * documentation section for more information.
+ */
+ uploadMultiple: false,
+
+ /**
+ * Whether you want files to be uploaded in chunks to your server. This can't be
+ * used in combination with `uploadMultiple`.
+ *
+ * See [chunksUploaded](#config-chunksUploaded) for the callback to finalise an upload.
+ */
+ chunking: false,
+
+ /**
+ * If `chunking` is enabled, this defines whether **every** file should be chunked,
+ * even if the file size is below chunkSize. This means, that the additional chunk
+ * form data will be submitted and the `chunksUploaded` callback will be invoked.
+ */
+ forceChunking: false,
+
+ /**
+ * If `chunking` is `true`, then this defines the chunk size in bytes.
+ */
+ chunkSize: 2000000,
+
+ /**
+ * If `true`, the individual chunks of a file are being uploaded simultaneously.
+ */
+ parallelChunkUploads: false,
+
+ /**
+ * Whether a chunk should be retried if it fails.
+ */
+ retryChunks: false,
+
+ /**
+ * If `retryChunks` is true, how many times should it be retried.
+ */
+ retryChunksLimit: 3,
+
+ /**
+ * If not `null` defines how many files this Dropzone handles. If it exceeds,
+ * the event `maxfilesexceeded` will be called. The dropzone element gets the
+ * class `dz-max-files-reached` accordingly so you can provide visual feedback.
+ */
+ maxFilesize: 256,
+
+ /**
+ * The name of the file param that gets transferred.
+ * **NOTE**: If you have the option `uploadMultiple` set to `true`, then
+ * Dropzone will append `[]` to the name.
+ */
+ paramName: "file",
+
+ /**
+ * Whether thumbnails for images should be generated
+ */
+ createImageThumbnails: true,
+
+ /**
+ * In MB. When the filename exceeds this limit, the thumbnail will not be generated.
+ */
+ maxThumbnailFilesize: 10,
+
+ /**
+ * If `null`, the ratio of the image will be used to calculate it.
+ */
+ thumbnailWidth: 120,
+
+ /**
+ * The same as `thumbnailWidth`. If both are null, images will not be resized.
+ */
+ thumbnailHeight: 120,
+
+ /**
+ * How the images should be scaled down in case both, `thumbnailWidth` and `thumbnailHeight` are provided.
+ * Can be either `contain` or `crop`.
+ */
+ thumbnailMethod: 'crop',
+
+ /**
+ * If set, images will be resized to these dimensions before being **uploaded**.
+ * If only one, `resizeWidth` **or** `resizeHeight` is provided, the original aspect
+ * ratio of the file will be preserved.
+ *
+ * The `options.transformFile` function uses these options, so if the `transformFile` function
+ * is overridden, these options don't do anything.
+ */
+ resizeWidth: null,
+
+ /**
+ * See `resizeWidth`.
+ */
+ resizeHeight: null,
+
+ /**
+ * The mime type of the resized image (before it gets uploaded to the server).
+ * If `null` the original mime type will be used. To force jpeg, for example, use `image/jpeg`.
+ * See `resizeWidth` for more information.
+ */
+ resizeMimeType: null,
+
+ /**
+ * The quality of the resized images. See `resizeWidth`.
+ */
+ resizeQuality: 0.8,
+
+ /**
+ * How the images should be scaled down in case both, `resizeWidth` and `resizeHeight` are provided.
+ * Can be either `contain` or `crop`.
+ */
+ resizeMethod: 'contain',
+
+ /**
+ * The base that is used to calculate the filesize. You can change this to
+ * 1024 if you would rather display kibibytes, mebibytes, etc...
+ * 1024 is technically incorrect, because `1024 bytes` are `1 kibibyte` not `1 kilobyte`.
+ * You can change this to `1024` if you don't care about validity.
+ */
+ filesizeBase: 1000,
+
+ /**
+ * Can be used to limit the maximum number of files that will be handled by this Dropzone
+ */
+ maxFiles: null,
+
+ /**
+ * An optional object to send additional headers to the server. Eg:
+ * `{ "My-Awesome-Header": "header value" }`
+ */
+ headers: null,
+
+ /**
+ * If `true`, the dropzone element itself will be clickable, if `false`
+ * nothing will be clickable.
+ *
+ * You can also pass an HTML element, a CSS selector (for multiple elements)
+ * or an array of those. In that case, all of those elements will trigger an
+ * upload when clicked.
+ */
+ clickable: true,
+
+ /**
+ * Whether hidden files in directories should be ignored.
+ */
+ ignoreHiddenFiles: true,
+
+ /**
+ * The default implementation of `accept` checks the file's mime type or
+ * extension against this list. This is a comma separated list of mime
+ * types or file extensions.
+ *
+ * Eg.: `image/*,application/pdf,.psd`
+ *
+ * If the Dropzone is `clickable` this option will also be used as
+ * [`accept`](https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept)
+ * parameter on the hidden file input as well.
+ */
+ acceptedFiles: null,
+
+ /**
+ * **Deprecated!**
+ * Use acceptedFiles instead.
+ */
+ acceptedMimeTypes: null,
+
+ /**
+ * If false, files will be added to the queue but the queue will not be
+ * processed automatically.
+ * This can be useful if you need some additional user input before sending
+ * files (or if you want want all files sent at once).
+ * If you're ready to send the file simply call `myDropzone.processQueue()`.
+ *
+ * See the [enqueuing file uploads](#enqueuing-file-uploads) documentation
+ * section for more information.
+ */
+ autoProcessQueue: true,
+
+ /**
+ * If false, files added to the dropzone will not be queued by default.
+ * You'll have to call `enqueueFile(file)` manually.
+ */
+ autoQueue: true,
+
+ /**
+ * If `true`, this will add a link to every file preview to remove or cancel (if
+ * already uploading) the file. The `dictCancelUpload`, `dictCancelUploadConfirmation`
+ * and `dictRemoveFile` options are used for the wording.
+ */
+ addRemoveLinks: false,
+
+ /**
+ * Defines where to display the file previews – if `null` the
+ * Dropzone element itself is used. Can be a plain `HTMLElement` or a CSS
+ * selector. The element should have the `dropzone-previews` class so
+ * the previews are displayed properly.
+ */
+ previewsContainer: null,
+
+ /**
+ * This is the element the hidden input field (which is used when clicking on the
+ * dropzone to trigger file selection) will be appended to. This might
+ * be important in case you use frameworks to switch the content of your page.
+ *
+ * Can be a selector string, or an element directly.
+ */
+ hiddenInputContainer: "body",
+
+ /**
+ * If null, no capture type will be specified
+ * If camera, mobile devices will skip the file selection and choose camera
+ * If microphone, mobile devices will skip the file selection and choose the microphone
+ * If camcorder, mobile devices will skip the file selection and choose the camera in video mode
+ * On apple devices multiple must be set to false. AcceptedFiles may need to
+ * be set to an appropriate mime type (e.g. "image/*", "audio/*", or "video/*").
+ */
+ capture: null,
+
+ /**
+ * **Deprecated**. Use `renameFile` instead.
+ */
+ renameFilename: null,
+
+ /**
+ * A function that is invoked before the file is uploaded to the server and renames the file.
+ * This function gets the `File` as argument and can use the `file.name`. The actual name of the
+ * file that gets used during the upload can be accessed through `file.upload.filename`.
+ */
+ renameFile: null,
+
+ /**
+ * If `true` the fallback will be forced. This is very useful to test your server
+ * implementations first and make sure that everything works as
+ * expected without dropzone if you experience problems, and to test
+ * how your fallbacks will look.
+ */
+ forceFallback: false,
+
+ /**
+ * The text used before any files are dropped.
+ */
+ dictDefaultMessage: "Drop files here to upload",
+
+ /**
+ * The text that replaces the default message text it the browser is not supported.
+ */
+ dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",
+
+ /**
+ * The text that will be added before the fallback form.
+ * If you provide a fallback element yourself, or if this option is `null` this will
+ * be ignored.
+ */
+ dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",
+
+ /**
+ * If the filesize is too big.
+ * `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
+ */
+ dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",
+
+ /**
+ * If the file doesn't match the file type.
+ */
+ dictInvalidFileType: "You can't upload files of this type.",
+
+ /**
+ * If the server response was invalid.
+ * `{{statusCode}}` will be replaced with the servers status code.
+ */
+ dictResponseError: "Server responded with {{statusCode}} code.",
+
+ /**
+ * If `addRemoveLinks` is true, the text to be used for the cancel upload link.
+ */
+ dictCancelUpload: "Cancel upload",
+
+ /**
+ * The text that is displayed if an upload was manually canceled
+ */
+ dictUploadCanceled: "Upload canceled.",
+
+ /**
+ * If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
+ */
+ dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
+
+ /**
+ * If `addRemoveLinks` is true, the text to be used to remove a file.
+ */
+ dictRemoveFile: "Remove file",
+
+ /**
+ * If this is not null, then the user will be prompted before removing a file.
+ */
+ dictRemoveFileConfirmation: null,
+
+ /**
+ * Displayed if `maxFiles` is st and exceeded.
+ * The string `{{maxFiles}}` will be replaced by the configuration value.
+ */
+ dictMaxFilesExceeded: "You can not upload any more files.",
+
+ /**
+ * Allows you to translate the different units. Starting with `tb` for terabytes and going down to
+ * `b` for bytes.
+ */
+ dictFileSizeUnits: { tb: "TB", gb: "GB", mb: "MB", kb: "KB", b: "b" },
+ /**
+ * Called when dropzone initialized
+ * You can add event listeners here
+ */
+ init: function init() {},
+
+
+ /**
+ * Can be an **object** of additional parameters to transfer to the server, **or** a `Function`
+ * that gets invoked with the `files`, `xhr` and, if it's a chunked upload, `chunk` arguments. In case
+ * of a function, this needs to return a map.
+ *
+ * The default implementation does nothing for normal uploads, but adds relevant information for
+ * chunked uploads.
+ *
+ * This is the same as adding hidden input fields in the form element.
+ */
+ params: function params(files, xhr, chunk) {
+ if (chunk) {
+ return {
+ dzuuid: chunk.file.upload.uuid,
+ dzchunkindex: chunk.index,
+ dztotalfilesize: chunk.file.size,
+ dzchunksize: this.options.chunkSize,
+ dztotalchunkcount: chunk.file.upload.totalChunkCount,
+ dzchunkbyteoffset: chunk.index * this.options.chunkSize
+ };
+ }
+ },
+
+
+ /**
+ * A function that gets a [file](https://developer.mozilla.org/en-US/docs/DOM/File)
+ * and a `done` function as parameters.
+ *
+ * If the done function is invoked without arguments, the file is "accepted" and will
+ * be processed. If you pass an error message, the file is rejected, and the error
+ * message will be displayed.
+ * This function will not be called if the file is too big or doesn't match the mime types.
+ */
+ accept: function accept(file, done) {
+ return done();
+ },
+
+
+ /**
+ * The callback that will be invoked when all chunks have been uploaded for a file.
+ * It gets the file for which the chunks have been uploaded as the first parameter,
+ * and the `done` function as second. `done()` needs to be invoked when everything
+ * needed to finish the upload process is done.
+ */
+ chunksUploaded: function chunksUploaded(file, done) {
+ done();
+ },
+
+ /**
+ * Gets called when the browser is not supported.
+ * The default implementation shows the fallback input field and adds
+ * a text.
+ */
+ fallback: function fallback() {
+ // This code should pass in IE7... :(
+ var messageElement = void 0;
+ this.element.className = this.element.className + " dz-browser-not-supported";
+
+ for (var _iterator2 = this.element.getElementsByTagName("div"), _isArray2 = true, _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
+ var _ref2;
+
+ if (_isArray2) {
+ if (_i2 >= _iterator2.length) break;
+ _ref2 = _iterator2[_i2++];
+ } else {
+ _i2 = _iterator2.next();
+ if (_i2.done) break;
+ _ref2 = _i2.value;
+ }
- Dropzone.prototype.Emitter = Emitter;
+ var child = _ref2;
+ if (/(^| )dz-message($| )/.test(child.className)) {
+ messageElement = child;
+ child.className = "dz-message"; // Removes the 'dz-default' class
+ break;
+ }
+ }
+ if (!messageElement) {
+ messageElement = Dropzone.createElement("
");
+ this.element.appendChild(messageElement);
+ }
- /*
- This is a list of all available events you can register on a dropzone object.
-
- You can register an event handler like this:
-
- dropzone.on("dragEnter", function() { });
- */
-
- Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached", "queuecomplete"];
-
- Dropzone.prototype.defaultOptions = {
- url: null,
- method: "post",
- withCredentials: false,
- parallelUploads: 2,
- uploadMultiple: false,
- maxFilesize: 256,
- paramName: "file",
- createImageThumbnails: true,
- maxThumbnailFilesize: 10,
- thumbnailWidth: 120,
- thumbnailHeight: 120,
- filesizeBase: 1000,
- maxFiles: null,
- filesizeBase: 1000,
- params: {},
- clickable: true,
- ignoreHiddenFiles: true,
- acceptedFiles: null,
- acceptedMimeTypes: null,
- autoProcessQueue: true,
- autoQueue: true,
- addRemoveLinks: false,
- previewsContainer: null,
- capture: null,
- dictDefaultMessage: "Drop files here to upload",
- dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",
- dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",
- dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",
- dictInvalidFileType: "You can't upload files of this type.",
- dictResponseError: "Server responded with {{statusCode}} code.",
- dictCancelUpload: "Cancel upload",
- dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
- dictRemoveFile: "Remove file",
- dictRemoveFileConfirmation: null,
- dictMaxFilesExceeded: "You can not upload any more files.",
- accept: function(file, done) {
- return done();
- },
- init: function() {
- return noop;
- },
- forceFallback: false,
- fallback: function() {
- var child, messageElement, span, _i, _len, _ref;
- this.element.className = "" + this.element.className + " dz-browser-not-supported";
- _ref = this.element.getElementsByTagName("div");
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- child = _ref[_i];
- if (/(^| )dz-message($| )/.test(child.className)) {
- messageElement = child;
- child.className = "dz-message";
- continue;
+ var span = messageElement.getElementsByTagName("span")[0];
+ if (span) {
+ if (span.textContent != null) {
+ span.textContent = this.options.dictFallbackMessage;
+ } else if (span.innerText != null) {
+ span.innerText = this.options.dictFallbackMessage;
+ }
}
- }
- if (!messageElement) {
- messageElement = Dropzone.createElement("
");
- this.element.appendChild(messageElement);
- }
- span = messageElement.getElementsByTagName("span")[0];
- if (span) {
- span.textContent = this.options.dictFallbackMessage;
- }
- return this.element.appendChild(this.getFallbackForm());
- },
- resize: function(file) {
- var info, srcRatio, trgRatio;
- info = {
- srcX: 0,
- srcY: 0,
- srcWidth: file.width,
- srcHeight: file.height
- };
- srcRatio = file.width / file.height;
- info.optWidth = this.options.thumbnailWidth;
- info.optHeight = this.options.thumbnailHeight;
- if ((info.optWidth == null) && (info.optHeight == null)) {
- info.optWidth = info.srcWidth;
- info.optHeight = info.srcHeight;
- } else if (info.optWidth == null) {
- info.optWidth = srcRatio * info.optHeight;
- } else if (info.optHeight == null) {
- info.optHeight = (1 / srcRatio) * info.optWidth;
- }
- trgRatio = info.optWidth / info.optHeight;
- if (file.height < info.optHeight || file.width < info.optWidth) {
- info.trgHeight = info.srcHeight;
- info.trgWidth = info.srcWidth;
- } else {
- if (srcRatio > trgRatio) {
- info.srcHeight = file.height;
- info.srcWidth = info.srcHeight * trgRatio;
- } else {
- info.srcWidth = file.width;
- info.srcHeight = info.srcWidth / trgRatio;
+
+ return this.element.appendChild(this.getFallbackForm());
+ },
+
+
+ /**
+ * Gets called to calculate the thumbnail dimensions.
+ *
+ * It gets `file`, `width` and `height` (both may be `null`) as parameters and must return an object containing:
+ *
+ * - `srcWidth` & `srcHeight` (required)
+ * - `trgWidth` & `trgHeight` (required)
+ * - `srcX` & `srcY` (optional, default `0`)
+ * - `trgX` & `trgY` (optional, default `0`)
+ *
+ * Those values are going to be used by `ctx.drawImage()`.
+ */
+ resize: function resize(file, width, height, resizeMethod) {
+ var info = {
+ srcX: 0,
+ srcY: 0,
+ srcWidth: file.width,
+ srcHeight: file.height
+ };
+
+ var srcRatio = file.width / file.height;
+
+ // Automatically calculate dimensions if not specified
+ if (width == null && height == null) {
+ width = info.srcWidth;
+ height = info.srcHeight;
+ } else if (width == null) {
+ width = height * srcRatio;
+ } else if (height == null) {
+ height = width / srcRatio;
}
- }
- info.srcX = (file.width - info.srcWidth) / 2;
- info.srcY = (file.height - info.srcHeight) / 2;
- return info;
- },
- /*
- Those functions register themselves to the events on init and handle all
- the user interface specific stuff. Overwriting them won't break the upload
- but can break the way it's displayed.
- You can overwrite them if you don't like the default behavior. If you just
- want to add an additional event handler, register it on the dropzone object
- and don't overwrite those options.
- */
- drop: function(e) {
- return this.element.classList.remove("dz-drag-hover");
- },
- dragstart: noop,
- dragend: function(e) {
- return this.element.classList.remove("dz-drag-hover");
- },
- dragenter: function(e) {
- return this.element.classList.add("dz-drag-hover");
- },
- dragover: function(e) {
- return this.element.classList.add("dz-drag-hover");
- },
- dragleave: function(e) {
- return this.element.classList.remove("dz-drag-hover");
- },
- paste: noop,
- reset: function() {
- return this.element.classList.remove("dz-started");
- },
- addedfile: function(file) {
- var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results;
- if (this.element === this.previewsContainer) {
- this.element.classList.add("dz-started");
- }
- if (this.previewsContainer) {
- file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim());
- file.previewTemplate = file.previewElement;
- this.previewsContainer.appendChild(file.previewElement);
- _ref = file.previewElement.querySelectorAll("[data-dz-name]");
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- node = _ref[_i];
- node.textContent = file.name;
+ // Make sure images aren't upscaled
+ width = Math.min(width, info.srcWidth);
+ height = Math.min(height, info.srcHeight);
+
+ var trgRatio = width / height;
+
+ if (info.srcWidth > width || info.srcHeight > height) {
+ // Image is bigger and needs rescaling
+ if (resizeMethod === 'crop') {
+ if (srcRatio > trgRatio) {
+ info.srcHeight = file.height;
+ info.srcWidth = info.srcHeight * trgRatio;
+ } else {
+ info.srcWidth = file.width;
+ info.srcHeight = info.srcWidth / trgRatio;
+ }
+ } else if (resizeMethod === 'contain') {
+ // Method 'contain'
+ if (srcRatio > trgRatio) {
+ height = width / srcRatio;
+ } else {
+ width = height * srcRatio;
+ }
+ } else {
+ throw new Error("Unknown resizeMethod '" + resizeMethod + "'");
+ }
}
- _ref1 = file.previewElement.querySelectorAll("[data-dz-size]");
- for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
- node = _ref1[_j];
- node.innerHTML = this.filesize(file.size);
+
+ info.srcX = (file.width - info.srcWidth) / 2;
+ info.srcY = (file.height - info.srcHeight) / 2;
+
+ info.trgWidth = width;
+ info.trgHeight = height;
+
+ return info;
+ },
+
+
+ /**
+ * Can be used to transform the file (for example, resize an image if necessary).
+ *
+ * The default implementation uses `resizeWidth` and `resizeHeight` (if provided) and resizes
+ * images according to those dimensions.
+ *
+ * Gets the `file` as the first parameter, and a `done()` function as the second, that needs
+ * to be invoked with the file when the transformation is done.
+ */
+ transformFile: function transformFile(file, done) {
+ if ((this.options.resizeWidth || this.options.resizeHeight) && file.type.match(/image.*/)) {
+ return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, done);
+ } else {
+ return done(file);
}
- if (this.options.addRemoveLinks) {
- file._removeLink = Dropzone.createElement("" + this.options.dictRemoveFile + " ");
- file.previewElement.appendChild(file._removeLink);
+ },
+
+
+ /**
+ * A string that contains the template used for each dropped
+ * file. Change it to fulfill your needs but make sure to properly
+ * provide all elements.
+ *
+ * If you want to use an actual HTML element instead of providing a String
+ * as a config option, you could create a div with the id `tpl`,
+ * put the template inside it and provide the element like this:
+ *
+ * document
+ * .querySelector('#tpl')
+ * .innerHTML
+ *
+ */
+ previewTemplate: "\n
\n
\n
\n
\n
\n
\n Check \n \n \n \n \n \n
\n
\n
\n Error \n \n \n \n \n \n \n \n
\n
",
+
+ // END OPTIONS
+ // (Required by the dropzone documentation parser)
+
+
+ /*
+ Those functions register themselves to the events on init and handle all
+ the user interface specific stuff. Overwriting them won't break the upload
+ but can break the way it's displayed.
+ You can overwrite them if you don't like the default behavior. If you just
+ want to add an additional event handler, register it on the dropzone object
+ and don't overwrite those options.
+ */
+
+ // Those are self explanatory and simply concern the DragnDrop.
+ drop: function drop(e) {
+ return this.element.classList.remove("dz-drag-hover");
+ },
+ dragstart: function dragstart(e) {},
+ dragend: function dragend(e) {
+ return this.element.classList.remove("dz-drag-hover");
+ },
+ dragenter: function dragenter(e) {
+ return this.element.classList.add("dz-drag-hover");
+ },
+ dragover: function dragover(e) {
+ return this.element.classList.add("dz-drag-hover");
+ },
+ dragleave: function dragleave(e) {
+ return this.element.classList.remove("dz-drag-hover");
+ },
+ paste: function paste(e) {},
+
+
+ // Called whenever there are no files left in the dropzone anymore, and the
+ // dropzone should be displayed as if in the initial state.
+ reset: function reset() {
+ return this.element.classList.remove("dz-started");
+ },
+
+
+ // Called when a file is added to the queue
+ // Receives `file`
+ addedfile: function addedfile(file) {
+ var _this2 = this;
+
+ if (this.element === this.previewsContainer) {
+ this.element.classList.add("dz-started");
}
- removeFileEvent = (function(_this) {
- return function(e) {
+
+ if (this.previewsContainer) {
+ file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim());
+ file.previewTemplate = file.previewElement; // Backwards compatibility
+
+ this.previewsContainer.appendChild(file.previewElement);
+ for (var _iterator3 = file.previewElement.querySelectorAll("[data-dz-name]"), _isArray3 = true, _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
+ var _ref3;
+
+ if (_isArray3) {
+ if (_i3 >= _iterator3.length) break;
+ _ref3 = _iterator3[_i3++];
+ } else {
+ _i3 = _iterator3.next();
+ if (_i3.done) break;
+ _ref3 = _i3.value;
+ }
+
+ var node = _ref3;
+
+ node.textContent = file.name;
+ }
+ for (var _iterator4 = file.previewElement.querySelectorAll("[data-dz-size]"), _isArray4 = true, _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
+ if (_isArray4) {
+ if (_i4 >= _iterator4.length) break;
+ node = _iterator4[_i4++];
+ } else {
+ _i4 = _iterator4.next();
+ if (_i4.done) break;
+ node = _i4.value;
+ }
+
+ node.innerHTML = this.filesize(file.size);
+ }
+
+ if (this.options.addRemoveLinks) {
+ file._removeLink = Dropzone.createElement("" + this.options.dictRemoveFile + " ");
+ file.previewElement.appendChild(file._removeLink);
+ }
+
+ var removeFileEvent = function removeFileEvent(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
- return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
- return _this.removeFile(file);
+ return Dropzone.confirm(_this2.options.dictCancelUploadConfirmation, function () {
+ return _this2.removeFile(file);
});
} else {
- if (_this.options.dictRemoveFileConfirmation) {
- return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
- return _this.removeFile(file);
+ if (_this2.options.dictRemoveFileConfirmation) {
+ return Dropzone.confirm(_this2.options.dictRemoveFileConfirmation, function () {
+ return _this2.removeFile(file);
});
} else {
- return _this.removeFile(file);
+ return _this2.removeFile(file);
}
}
};
- })(this);
- _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
- _results = [];
- for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
- removeLink = _ref2[_k];
- _results.push(removeLink.addEventListener("click", removeFileEvent));
- }
- return _results;
- }
- },
- removedfile: function(file) {
- var _ref;
- if (file.previewElement) {
- if ((_ref = file.previewElement) != null) {
- _ref.parentNode.removeChild(file.previewElement);
+
+ for (var _iterator5 = file.previewElement.querySelectorAll("[data-dz-remove]"), _isArray5 = true, _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
+ var _ref4;
+
+ if (_isArray5) {
+ if (_i5 >= _iterator5.length) break;
+ _ref4 = _iterator5[_i5++];
+ } else {
+ _i5 = _iterator5.next();
+ if (_i5.done) break;
+ _ref4 = _i5.value;
+ }
+
+ var removeLink = _ref4;
+
+ removeLink.addEventListener("click", removeFileEvent);
+ }
}
- }
- return this._updateMaxFilesReachedClass();
- },
- thumbnail: function(file, dataUrl) {
- var thumbnailElement, _i, _len, _ref;
- if (file.previewElement) {
- file.previewElement.classList.remove("dz-file-preview");
- _ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- thumbnailElement = _ref[_i];
- thumbnailElement.alt = file.name;
- thumbnailElement.src = dataUrl;
+ },
+
+
+ // Called whenever a file is removed.
+ removedfile: function removedfile(file) {
+ if (file.previewElement != null && file.previewElement.parentNode != null) {
+ file.previewElement.parentNode.removeChild(file.previewElement);
}
- return setTimeout(((function(_this) {
- return function() {
+ return this._updateMaxFilesReachedClass();
+ },
+
+
+ // Called when a thumbnail has been generated
+ // Receives `file` and `dataUrl`
+ thumbnail: function thumbnail(file, dataUrl) {
+ if (file.previewElement) {
+ file.previewElement.classList.remove("dz-file-preview");
+ for (var _iterator6 = file.previewElement.querySelectorAll("[data-dz-thumbnail]"), _isArray6 = true, _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
+ var _ref5;
+
+ if (_isArray6) {
+ if (_i6 >= _iterator6.length) break;
+ _ref5 = _iterator6[_i6++];
+ } else {
+ _i6 = _iterator6.next();
+ if (_i6.done) break;
+ _ref5 = _i6.value;
+ }
+
+ var thumbnailElement = _ref5;
+
+ thumbnailElement.alt = file.name;
+ thumbnailElement.src = dataUrl;
+ }
+
+ return setTimeout(function () {
return file.previewElement.classList.add("dz-image-preview");
- };
- })(this)), 1);
- }
- },
- error: function(file, message) {
- var node, _i, _len, _ref, _results;
- if (file.previewElement) {
- file.previewElement.classList.add("dz-error");
- if (typeof message !== "String" && message.error) {
- message = message.error;
+ }, 1);
}
- _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- node = _ref[_i];
- _results.push(node.textContent = message);
+ },
+
+
+ // Called whenever an error occurs
+ // Receives `file` and `message`
+ error: function error(file, message) {
+ if (file.previewElement) {
+ file.previewElement.classList.add("dz-error");
+ if (typeof message !== "String" && message.error) {
+ message = message.error;
+ }
+ for (var _iterator7 = file.previewElement.querySelectorAll("[data-dz-errormessage]"), _isArray7 = true, _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
+ var _ref6;
+
+ if (_isArray7) {
+ if (_i7 >= _iterator7.length) break;
+ _ref6 = _iterator7[_i7++];
+ } else {
+ _i7 = _iterator7.next();
+ if (_i7.done) break;
+ _ref6 = _i7.value;
+ }
+
+ var node = _ref6;
+
+ node.textContent = message;
+ }
}
- return _results;
- }
- },
- errormultiple: noop,
- processing: function(file) {
- if (file.previewElement) {
- file.previewElement.classList.add("dz-processing");
- if (file._removeLink) {
- return file._removeLink.textContent = this.options.dictCancelUpload;
+ },
+ errormultiple: function errormultiple() {},
+
+
+ // Called when a file gets processed. Since there is a cue, not all added
+ // files are processed immediately.
+ // Receives `file`
+ processing: function processing(file) {
+ if (file.previewElement) {
+ file.previewElement.classList.add("dz-processing");
+ if (file._removeLink) {
+ return file._removeLink.innerHTML = this.options.dictCancelUpload;
+ }
}
- }
- },
- processingmultiple: noop,
- uploadprogress: function(file, progress, bytesSent) {
- var node, _i, _len, _ref, _results;
- if (file.previewElement) {
- _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]");
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- node = _ref[_i];
- if (node.nodeName === 'PROGRESS') {
- _results.push(node.value = progress);
- } else {
- _results.push(node.style.width = "" + progress + "%");
+ },
+ processingmultiple: function processingmultiple() {},
+
+
+ // Called whenever the upload progress gets updated.
+ // Receives `file`, `progress` (percentage 0-100) and `bytesSent`.
+ // To get the total number of bytes of the file, use `file.size`
+ uploadprogress: function uploadprogress(file, progress, bytesSent) {
+ if (file.previewElement) {
+ for (var _iterator8 = file.previewElement.querySelectorAll("[data-dz-uploadprogress]"), _isArray8 = true, _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
+ var _ref7;
+
+ if (_isArray8) {
+ if (_i8 >= _iterator8.length) break;
+ _ref7 = _iterator8[_i8++];
+ } else {
+ _i8 = _iterator8.next();
+ if (_i8.done) break;
+ _ref7 = _i8.value;
+ }
+
+ var node = _ref7;
+
+ node.nodeName === 'PROGRESS' ? node.value = progress : node.style.width = progress + "%";
}
}
- return _results;
- }
- },
- totaluploadprogress: noop,
- sending: noop,
- sendingmultiple: noop,
- success: function(file) {
- if (file.previewElement) {
- return file.previewElement.classList.add("dz-success");
- }
- },
- successmultiple: noop,
- canceled: function(file) {
- return this.emit("error", file, "Upload canceled.");
- },
- canceledmultiple: noop,
- complete: function(file) {
- if (file._removeLink) {
- file._removeLink.textContent = this.options.dictRemoveFile;
- }
- if (file.previewElement) {
- return file.previewElement.classList.add("dz-complete");
- }
- },
- completemultiple: noop,
- maxfilesexceeded: noop,
- maxfilesreached: noop,
- queuecomplete: noop,
- previewTemplate: "\n
\n
\n
\n
\n
\n
\n Check \n \n \n \n \n \n
\n
\n
\n Error \n \n \n \n \n \n \n \n
\n
"
- };
+ },
- extend = function() {
- var key, object, objects, target, val, _i, _len;
- target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
- for (_i = 0, _len = objects.length; _i < _len; _i++) {
- object = objects[_i];
- for (key in object) {
- val = object[key];
- target[key] = val;
- }
+
+ // Called whenever the total upload progress gets updated.
+ // Called with totalUploadProgress (0-100), totalBytes and totalBytesSent
+ totaluploadprogress: function totaluploadprogress() {},
+
+
+ // Called just before the file is sent. Gets the `xhr` object as second
+ // parameter, so you can modify it (for example to add a CSRF token) and a
+ // `formData` object to add additional information.
+ sending: function sending() {},
+ sendingmultiple: function sendingmultiple() {},
+
+
+ // When the complete upload is finished and successful
+ // Receives `file`
+ success: function success(file) {
+ if (file.previewElement) {
+ return file.previewElement.classList.add("dz-success");
+ }
+ },
+ successmultiple: function successmultiple() {},
+
+
+ // When the upload is canceled.
+ canceled: function canceled(file) {
+ return this.emit("error", file, this.options.dictUploadCanceled);
+ },
+ canceledmultiple: function canceledmultiple() {},
+
+
+ // When the upload is finished, either with success or an error.
+ // Receives `file`
+ complete: function complete(file) {
+ if (file._removeLink) {
+ file._removeLink.innerHTML = this.options.dictRemoveFile;
+ }
+ if (file.previewElement) {
+ return file.previewElement.classList.add("dz-complete");
+ }
+ },
+ completemultiple: function completemultiple() {},
+ maxfilesexceeded: function maxfilesexceeded() {},
+ maxfilesreached: function maxfilesreached() {},
+ queuecomplete: function queuecomplete() {},
+ addedfiles: function addedfiles() {}
+ };
+
+ this.prototype._thumbnailQueue = [];
+ this.prototype._processingThumbnail = false;
+ }
+
+ // global utility
+
+ }, {
+ key: "extend",
+ value: function extend(target) {
+ for (var _len2 = arguments.length, objects = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ objects[_key2 - 1] = arguments[_key2];
}
- return target;
- };
- function Dropzone(element, options) {
- var elementOptions, fallback, _ref;
- this.element = element;
- this.version = Dropzone.version;
- this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, "");
- this.clickableElements = [];
- this.listeners = [];
- this.files = [];
- if (typeof this.element === "string") {
- this.element = document.querySelector(this.element);
- }
- if (!(this.element && (this.element.nodeType != null))) {
- throw new Error("Invalid dropzone element.");
- }
- if (this.element.dropzone) {
- throw new Error("Dropzone already attached.");
- }
- Dropzone.instances.push(this);
- this.element.dropzone = this;
- elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {};
- this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {});
- if (this.options.forceFallback || !Dropzone.isBrowserSupported()) {
- return this.options.fallback.call(this);
- }
- if (this.options.url == null) {
- this.options.url = this.element.getAttribute("action");
- }
- if (!this.options.url) {
- throw new Error("No URL provided.");
- }
- if (this.options.acceptedFiles && this.options.acceptedMimeTypes) {
- throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");
- }
- if (this.options.acceptedMimeTypes) {
- this.options.acceptedFiles = this.options.acceptedMimeTypes;
- delete this.options.acceptedMimeTypes;
- }
- this.options.method = this.options.method.toUpperCase();
- if ((fallback = this.getExistingFallback()) && fallback.parentNode) {
- fallback.parentNode.removeChild(fallback);
- }
- if (this.options.previewsContainer !== false) {
- if (this.options.previewsContainer) {
- this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer");
+ for (var _iterator9 = objects, _isArray9 = true, _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
+ var _ref8;
+
+ if (_isArray9) {
+ if (_i9 >= _iterator9.length) break;
+ _ref8 = _iterator9[_i9++];
} else {
- this.previewsContainer = this.element;
+ _i9 = _iterator9.next();
+ if (_i9.done) break;
+ _ref8 = _i9.value;
}
- }
- if (this.options.clickable) {
- if (this.options.clickable === true) {
- this.clickableElements = [this.element];
- } else {
- this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable");
+
+ var object = _ref8;
+
+ for (var key in object) {
+ var val = object[key];
+ target[key] = val;
}
}
- this.init();
+ return target;
}
+ }]);
- Dropzone.prototype.getAcceptedFiles = function() {
- var file, _i, _len, _ref, _results;
- _ref = this.files;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
- if (file.accepted) {
- _results.push(file);
- }
- }
- return _results;
- };
+ function Dropzone(el, options) {
+ _classCallCheck(this, Dropzone);
- Dropzone.prototype.getRejectedFiles = function() {
- var file, _i, _len, _ref, _results;
- _ref = this.files;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
- if (!file.accepted) {
- _results.push(file);
- }
+ var _this = _possibleConstructorReturn(this, (Dropzone.__proto__ || Object.getPrototypeOf(Dropzone)).call(this));
+
+ var fallback = void 0,
+ left = void 0;
+ _this.element = el;
+ // For backwards compatibility since the version was in the prototype previously
+ _this.version = Dropzone.version;
+
+ _this.defaultOptions.previewTemplate = _this.defaultOptions.previewTemplate.replace(/\n*/g, "");
+
+ _this.clickableElements = [];
+ _this.listeners = [];
+ _this.files = []; // All files
+
+ if (typeof _this.element === "string") {
+ _this.element = document.querySelector(_this.element);
+ }
+
+ // Not checking if instance of HTMLElement or Element since IE9 is extremely weird.
+ if (!_this.element || _this.element.nodeType == null) {
+ throw new Error("Invalid dropzone element.");
+ }
+
+ if (_this.element.dropzone) {
+ throw new Error("Dropzone already attached.");
+ }
+
+ // Now add this dropzone to the instances.
+ Dropzone.instances.push(_this);
+
+ // Put the dropzone inside the element itself.
+ _this.element.dropzone = _this;
+
+ var elementOptions = (left = Dropzone.optionsForElement(_this.element)) != null ? left : {};
+
+ _this.options = Dropzone.extend({}, _this.defaultOptions, elementOptions, options != null ? options : {});
+
+ // If the browser failed, just call the fallback and leave
+ if (_this.options.forceFallback || !Dropzone.isBrowserSupported()) {
+ var _ret;
+
+ return _ret = _this.options.fallback.call(_this), _possibleConstructorReturn(_this, _ret);
+ }
+
+ // @options.url = @element.getAttribute "action" unless @options.url?
+ if (_this.options.url == null) {
+ _this.options.url = _this.element.getAttribute("action");
+ }
+
+ if (!_this.options.url) {
+ throw new Error("No URL provided.");
+ }
+
+ if (_this.options.acceptedFiles && _this.options.acceptedMimeTypes) {
+ throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");
+ }
+
+ if (_this.options.uploadMultiple && _this.options.chunking) {
+ throw new Error('You cannot set both: uploadMultiple and chunking.');
+ }
+
+ // Backwards compatibility
+ if (_this.options.acceptedMimeTypes) {
+ _this.options.acceptedFiles = _this.options.acceptedMimeTypes;
+ delete _this.options.acceptedMimeTypes;
+ }
+
+ // Backwards compatibility
+ if (_this.options.renameFilename != null) {
+ _this.options.renameFile = function (file) {
+ return _this.options.renameFilename.call(_this, file.name, file);
+ };
+ }
+
+ _this.options.method = _this.options.method.toUpperCase();
+
+ if ((fallback = _this.getExistingFallback()) && fallback.parentNode) {
+ // Remove the fallback
+ fallback.parentNode.removeChild(fallback);
+ }
+
+ // Display previews in the previewsContainer element or the Dropzone element unless explicitly set to false
+ if (_this.options.previewsContainer !== false) {
+ if (_this.options.previewsContainer) {
+ _this.previewsContainer = Dropzone.getElement(_this.options.previewsContainer, "previewsContainer");
+ } else {
+ _this.previewsContainer = _this.element;
}
- return _results;
- };
+ }
- Dropzone.prototype.getFilesWithStatus = function(status) {
- var file, _i, _len, _ref, _results;
- _ref = this.files;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
- if (file.status === status) {
- _results.push(file);
- }
+ if (_this.options.clickable) {
+ if (_this.options.clickable === true) {
+ _this.clickableElements = [_this.element];
+ } else {
+ _this.clickableElements = Dropzone.getElements(_this.options.clickable, "clickable");
}
- return _results;
- };
+ }
- Dropzone.prototype.getQueuedFiles = function() {
- return this.getFilesWithStatus(Dropzone.QUEUED);
- };
+ _this.init();
+ return _this;
+ }
+
+ // Returns all files that have been accepted
+
+
+ _createClass(Dropzone, [{
+ key: "getAcceptedFiles",
+ value: function getAcceptedFiles() {
+ return this.files.filter(function (file) {
+ return file.accepted;
+ }).map(function (file) {
+ return file;
+ });
+ }
+
+ // Returns all files that have been rejected
+ // Not sure when that's going to be useful, but added for completeness.
+
+ }, {
+ key: "getRejectedFiles",
+ value: function getRejectedFiles() {
+ return this.files.filter(function (file) {
+ return !file.accepted;
+ }).map(function (file) {
+ return file;
+ });
+ }
+ }, {
+ key: "getFilesWithStatus",
+ value: function getFilesWithStatus(status) {
+ return this.files.filter(function (file) {
+ return file.status === status;
+ }).map(function (file) {
+ return file;
+ });
+ }
+
+ // Returns all files that are in the queue
- Dropzone.prototype.getUploadingFiles = function() {
+ }, {
+ key: "getQueuedFiles",
+ value: function getQueuedFiles() {
+ return this.getFilesWithStatus(Dropzone.QUEUED);
+ }
+ }, {
+ key: "getUploadingFiles",
+ value: function getUploadingFiles() {
return this.getFilesWithStatus(Dropzone.UPLOADING);
- };
+ }
+ }, {
+ key: "getAddedFiles",
+ value: function getAddedFiles() {
+ return this.getFilesWithStatus(Dropzone.ADDED);
+ }
- Dropzone.prototype.getActiveFiles = function() {
- var file, _i, _len, _ref, _results;
- _ref = this.files;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
- if (file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED) {
- _results.push(file);
- }
- }
- return _results;
- };
+ // Files that are either queued or uploading
+
+ }, {
+ key: "getActiveFiles",
+ value: function getActiveFiles() {
+ return this.files.filter(function (file) {
+ return file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED;
+ }).map(function (file) {
+ return file;
+ });
+ }
+
+ // The function that gets called when Dropzone is initialized. You
+ // can (and should) setup event listeners inside this function.
- Dropzone.prototype.init = function() {
- var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1;
+ }, {
+ key: "init",
+ value: function init() {
+ var _this3 = this;
+
+ // In case it isn't set already
if (this.element.tagName === "form") {
this.element.setAttribute("enctype", "multipart/form-data");
}
+
if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) {
this.element.appendChild(Dropzone.createElement("" + this.options.dictDefaultMessage + "
"));
}
+
if (this.clickableElements.length) {
- setupHiddenFileInput = (function(_this) {
- return function() {
- if (_this.hiddenFileInput) {
- document.body.removeChild(_this.hiddenFileInput);
- }
- _this.hiddenFileInput = document.createElement("input");
- _this.hiddenFileInput.setAttribute("type", "file");
- if ((_this.options.maxFiles == null) || _this.options.maxFiles > 1) {
- _this.hiddenFileInput.setAttribute("multiple", "multiple");
- }
- _this.hiddenFileInput.className = "dz-hidden-input";
- if (_this.options.acceptedFiles != null) {
- _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles);
- }
- if (_this.options.capture != null) {
- _this.hiddenFileInput.setAttribute("capture", _this.options.capture);
- }
- _this.hiddenFileInput.style.visibility = "hidden";
- _this.hiddenFileInput.style.position = "absolute";
- _this.hiddenFileInput.style.top = "0";
- _this.hiddenFileInput.style.left = "0";
- _this.hiddenFileInput.style.height = "0";
- _this.hiddenFileInput.style.width = "0";
- document.body.appendChild(_this.hiddenFileInput);
- return _this.hiddenFileInput.addEventListener("change", function() {
- var file, files, _i, _len;
- files = _this.hiddenFileInput.files;
- if (files.length) {
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
- _this.addFile(file);
+ var setupHiddenFileInput = function setupHiddenFileInput() {
+ if (_this3.hiddenFileInput) {
+ _this3.hiddenFileInput.parentNode.removeChild(_this3.hiddenFileInput);
+ }
+ _this3.hiddenFileInput = document.createElement("input");
+ _this3.hiddenFileInput.setAttribute("type", "file");
+ if (_this3.options.maxFiles === null || _this3.options.maxFiles > 1) {
+ _this3.hiddenFileInput.setAttribute("multiple", "multiple");
+ }
+ _this3.hiddenFileInput.className = "dz-hidden-input";
+
+ if (_this3.options.acceptedFiles !== null) {
+ _this3.hiddenFileInput.setAttribute("accept", _this3.options.acceptedFiles);
+ }
+ if (_this3.options.capture !== null) {
+ _this3.hiddenFileInput.setAttribute("capture", _this3.options.capture);
+ }
+
+ // Not setting `display="none"` because some browsers don't accept clicks
+ // on elements that aren't displayed.
+ _this3.hiddenFileInput.style.visibility = "hidden";
+ _this3.hiddenFileInput.style.position = "absolute";
+ _this3.hiddenFileInput.style.top = "0";
+ _this3.hiddenFileInput.style.left = "0";
+ _this3.hiddenFileInput.style.height = "0";
+ _this3.hiddenFileInput.style.width = "0";
+ Dropzone.getElement(_this3.options.hiddenInputContainer, 'hiddenInputContainer').appendChild(_this3.hiddenFileInput);
+ return _this3.hiddenFileInput.addEventListener("change", function () {
+ var files = _this3.hiddenFileInput.files;
+
+ if (files.length) {
+ for (var _iterator10 = files, _isArray10 = true, _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) {
+ var _ref9;
+
+ if (_isArray10) {
+ if (_i10 >= _iterator10.length) break;
+ _ref9 = _iterator10[_i10++];
+ } else {
+ _i10 = _iterator10.next();
+ if (_i10.done) break;
+ _ref9 = _i10.value;
}
+
+ var file = _ref9;
+
+ _this3.addFile(file);
}
- return setupHiddenFileInput();
- });
- };
- })(this);
+ }
+ _this3.emit("addedfiles", files);
+ return setupHiddenFileInput();
+ });
+ };
setupHiddenFileInput();
}
- this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL;
- _ref1 = this.events;
- for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
- eventName = _ref1[_i];
+
+ this.URL = window.URL !== null ? window.URL : window.webkitURL;
+
+ // Setup all event listeners on the Dropzone object itself.
+ // They're not in @setupEventListeners() because they shouldn't be removed
+ // again when the dropzone gets disabled.
+ for (var _iterator11 = this.events, _isArray11 = true, _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) {
+ var _ref10;
+
+ if (_isArray11) {
+ if (_i11 >= _iterator11.length) break;
+ _ref10 = _iterator11[_i11++];
+ } else {
+ _i11 = _iterator11.next();
+ if (_i11.done) break;
+ _ref10 = _i11.value;
+ }
+
+ var eventName = _ref10;
+
this.on(eventName, this.options[eventName]);
}
- this.on("uploadprogress", (function(_this) {
- return function() {
- return _this.updateTotalUploadProgress();
- };
- })(this));
- this.on("removedfile", (function(_this) {
- return function() {
- return _this.updateTotalUploadProgress();
- };
- })(this));
- this.on("canceled", (function(_this) {
- return function(file) {
- return _this.emit("complete", file);
- };
- })(this));
- this.on("complete", (function(_this) {
- return function(file) {
- if (_this.getUploadingFiles().length === 0 && _this.getQueuedFiles().length === 0) {
- return setTimeout((function() {
- return _this.emit("queuecomplete");
- }), 0);
- }
- };
- })(this));
- noPropagation = function(e) {
+
+ this.on("uploadprogress", function () {
+ return _this3.updateTotalUploadProgress();
+ });
+
+ this.on("removedfile", function () {
+ return _this3.updateTotalUploadProgress();
+ });
+
+ this.on("canceled", function (file) {
+ return _this3.emit("complete", file);
+ });
+
+ // Emit a `queuecomplete` event if all files finished uploading.
+ this.on("complete", function (file) {
+ if (_this3.getAddedFiles().length === 0 && _this3.getUploadingFiles().length === 0 && _this3.getQueuedFiles().length === 0) {
+ // This needs to be deferred so that `queuecomplete` really triggers after `complete`
+ return setTimeout(function () {
+ return _this3.emit("queuecomplete");
+ }, 0);
+ }
+ });
+
+ var noPropagation = function noPropagation(e) {
e.stopPropagation();
if (e.preventDefault) {
return e.preventDefault();
@@ -607,90 +1305,106 @@
return e.returnValue = false;
}
};
- this.listeners = [
- {
- element: this.element,
- events: {
- "dragstart": (function(_this) {
- return function(e) {
- return _this.emit("dragstart", e);
- };
- })(this),
- "dragenter": (function(_this) {
- return function(e) {
- noPropagation(e);
- return _this.emit("dragenter", e);
- };
- })(this),
- "dragover": (function(_this) {
- return function(e) {
- var efct;
- try {
- efct = e.dataTransfer.effectAllowed;
- } catch (_error) {}
- e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy';
- noPropagation(e);
- return _this.emit("dragover", e);
- };
- })(this),
- "dragleave": (function(_this) {
- return function(e) {
- return _this.emit("dragleave", e);
- };
- })(this),
- "drop": (function(_this) {
- return function(e) {
- noPropagation(e);
- return _this.drop(e);
- };
- })(this),
- "dragend": (function(_this) {
- return function(e) {
- return _this.emit("dragend", e);
- };
- })(this)
+
+ // Create the listeners
+ this.listeners = [{
+ element: this.element,
+ events: {
+ "dragstart": function dragstart(e) {
+ return _this3.emit("dragstart", e);
+ },
+ "dragenter": function dragenter(e) {
+ noPropagation(e);
+ return _this3.emit("dragenter", e);
+ },
+ "dragover": function dragover(e) {
+ // Makes it possible to drag files from chrome's download bar
+ // http://stackoverflow.com/questions/19526430/drag-and-drop-file-uploads-from-chrome-downloads-bar
+ // Try is required to prevent bug in Internet Explorer 11 (SCRIPT65535 exception)
+ var efct = void 0;
+ try {
+ efct = e.dataTransfer.effectAllowed;
+ } catch (error) {}
+ e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy';
+
+ noPropagation(e);
+ return _this3.emit("dragover", e);
+ },
+ "dragleave": function dragleave(e) {
+ return _this3.emit("dragleave", e);
+ },
+ "drop": function drop(e) {
+ noPropagation(e);
+ return _this3.drop(e);
+ },
+ "dragend": function dragend(e) {
+ return _this3.emit("dragend", e);
}
- }
- ];
- this.clickableElements.forEach((function(_this) {
- return function(clickableElement) {
- return _this.listeners.push({
- element: clickableElement,
- events: {
- "click": function(evt) {
- if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) {
- return _this.hiddenFileInput.click();
- }
+
+ // This is disabled right now, because the browsers don't implement it properly.
+ // "paste": (e) =>
+ // noPropagation e
+ // @paste e
+ } }];
+
+ this.clickableElements.forEach(function (clickableElement) {
+ return _this3.listeners.push({
+ element: clickableElement,
+ events: {
+ "click": function click(evt) {
+ // Only the actual dropzone or the message element should trigger file selection
+ if (clickableElement !== _this3.element || evt.target === _this3.element || Dropzone.elementInside(evt.target, _this3.element.querySelector(".dz-message"))) {
+ _this3.hiddenFileInput.click(); // Forward the click
}
+ return true;
}
- });
- };
- })(this));
+ }
+ });
+ });
+
this.enable();
+
return this.options.init.call(this);
- };
+ }
+
+ // Not fully tested yet
- Dropzone.prototype.destroy = function() {
- var _ref;
+ }, {
+ key: "destroy",
+ value: function destroy() {
this.disable();
this.removeAllFiles(true);
- if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) {
+ if (this.hiddenFileInput != null ? this.hiddenFileInput.parentNode : undefined) {
this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
this.hiddenFileInput = null;
}
delete this.element.dropzone;
return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1);
- };
+ }
+ }, {
+ key: "updateTotalUploadProgress",
+ value: function updateTotalUploadProgress() {
+ var totalUploadProgress = void 0;
+ var totalBytesSent = 0;
+ var totalBytes = 0;
+
+ var activeFiles = this.getActiveFiles();
- Dropzone.prototype.updateTotalUploadProgress = function() {
- var activeFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref;
- totalBytesSent = 0;
- totalBytes = 0;
- activeFiles = this.getActiveFiles();
if (activeFiles.length) {
- _ref = this.getActiveFiles();
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
+ for (var _iterator12 = this.getActiveFiles(), _isArray12 = true, _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) {
+ var _ref11;
+
+ if (_isArray12) {
+ if (_i12 >= _iterator12.length) break;
+ _ref11 = _iterator12[_i12++];
+ } else {
+ _i12 = _iterator12.next();
+ if (_i12.done) break;
+ _ref11 = _i12.value;
+ }
+
+ var file = _ref11;
+
totalBytesSent += file.upload.bytesSent;
totalBytes += file.upload.total;
}
@@ -698,139 +1412,200 @@
} else {
totalUploadProgress = 100;
}
+
return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent);
- };
+ }
+
+ // @options.paramName can be a function taking one parameter rather than a string.
+ // A parameter name for a file is obtained simply by calling this with an index number.
- Dropzone.prototype._getParamName = function(n) {
+ }, {
+ key: "_getParamName",
+ value: function _getParamName(n) {
if (typeof this.options.paramName === "function") {
return this.options.paramName(n);
} else {
return "" + this.options.paramName + (this.options.uploadMultiple ? "[" + n + "]" : "");
}
- };
+ }
+
+ // If @options.renameFile is a function,
+ // the function will be used to rename the file.name before appending it to the formData
+
+ }, {
+ key: "_renameFile",
+ value: function _renameFile(file) {
+ if (typeof this.options.renameFile !== "function") {
+ return file.name;
+ }
+ return this.options.renameFile(file);
+ }
- Dropzone.prototype.getFallbackForm = function() {
- var existingFallback, fields, fieldsString, form;
+ // Returns a form that can be used as fallback if the browser does not support DragnDrop
+ //
+ // If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
+ // This code has to pass in IE7 :(
+
+ }, {
+ key: "getFallbackForm",
+ value: function getFallbackForm() {
+ var existingFallback = void 0,
+ form = void 0;
if (existingFallback = this.getExistingFallback()) {
return existingFallback;
}
- fieldsString = "";
+
+ var fields = Dropzone.createElement(fieldsString);
if (this.element.tagName !== "FORM") {
form = Dropzone.createElement("");
form.appendChild(fields);
} else {
+ // Make sure that the enctype and method attributes are set properly
this.element.setAttribute("enctype", "multipart/form-data");
this.element.setAttribute("method", this.options.method);
}
return form != null ? form : fields;
- };
+ }
+
+ // Returns the fallback elements if they exist already
+ //
+ // This code has to pass in IE7 :(
+
+ }, {
+ key: "getExistingFallback",
+ value: function getExistingFallback() {
+ var getFallback = function getFallback(elements) {
+ for (var _iterator13 = elements, _isArray13 = true, _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) {
+ var _ref12;
+
+ if (_isArray13) {
+ if (_i13 >= _iterator13.length) break;
+ _ref12 = _iterator13[_i13++];
+ } else {
+ _i13 = _iterator13.next();
+ if (_i13.done) break;
+ _ref12 = _i13.value;
+ }
+
+ var el = _ref12;
- Dropzone.prototype.getExistingFallback = function() {
- var fallback, getFallback, tagName, _i, _len, _ref;
- getFallback = function(elements) {
- var el, _i, _len;
- for (_i = 0, _len = elements.length; _i < _len; _i++) {
- el = elements[_i];
if (/(^| )fallback($| )/.test(el.className)) {
return el;
}
}
};
- _ref = ["div", "form"];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- tagName = _ref[_i];
+
+ var _arr = ["div", "form"];
+ for (var _i14 = 0; _i14 < _arr.length; _i14++) {
+ var tagName = _arr[_i14];
+ var fallback;
if (fallback = getFallback(this.element.getElementsByTagName(tagName))) {
return fallback;
}
}
- };
+ }
- Dropzone.prototype.setupEventListeners = function() {
- var elementListeners, event, listener, _i, _len, _ref, _results;
- _ref = this.listeners;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- elementListeners = _ref[_i];
- _results.push((function() {
- var _ref1, _results1;
- _ref1 = elementListeners.events;
- _results1 = [];
- for (event in _ref1) {
- listener = _ref1[event];
- _results1.push(elementListeners.element.addEventListener(event, listener, false));
+ // Activates all listeners stored in @listeners
+
+ }, {
+ key: "setupEventListeners",
+ value: function setupEventListeners() {
+ return this.listeners.map(function (elementListeners) {
+ return function () {
+ var result = [];
+ for (var event in elementListeners.events) {
+ var listener = elementListeners.events[event];
+ result.push(elementListeners.element.addEventListener(event, listener, false));
}
- return _results1;
- })());
- }
- return _results;
- };
+ return result;
+ }();
+ });
+ }
- Dropzone.prototype.removeEventListeners = function() {
- var elementListeners, event, listener, _i, _len, _ref, _results;
- _ref = this.listeners;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- elementListeners = _ref[_i];
- _results.push((function() {
- var _ref1, _results1;
- _ref1 = elementListeners.events;
- _results1 = [];
- for (event in _ref1) {
- listener = _ref1[event];
- _results1.push(elementListeners.element.removeEventListener(event, listener, false));
+ // Deactivates all listeners stored in @listeners
+
+ }, {
+ key: "removeEventListeners",
+ value: function removeEventListeners() {
+ return this.listeners.map(function (elementListeners) {
+ return function () {
+ var result = [];
+ for (var event in elementListeners.events) {
+ var listener = elementListeners.events[event];
+ result.push(elementListeners.element.removeEventListener(event, listener, false));
}
- return _results1;
- })());
- }
- return _results;
- };
+ return result;
+ }();
+ });
+ }
- Dropzone.prototype.disable = function() {
- var file, _i, _len, _ref, _results;
- this.clickableElements.forEach(function(element) {
+ // Removes all event listeners and cancels all files in the queue or being processed.
+
+ }, {
+ key: "disable",
+ value: function disable() {
+ var _this4 = this;
+
+ this.clickableElements.forEach(function (element) {
return element.classList.remove("dz-clickable");
});
this.removeEventListeners();
- _ref = this.files;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
- _results.push(this.cancelUpload(file));
- }
- return _results;
- };
+ this.disabled = true;
- Dropzone.prototype.enable = function() {
- this.clickableElements.forEach(function(element) {
+ return this.files.map(function (file) {
+ return _this4.cancelUpload(file);
+ });
+ }
+ }, {
+ key: "enable",
+ value: function enable() {
+ delete this.disabled;
+ this.clickableElements.forEach(function (element) {
return element.classList.add("dz-clickable");
});
return this.setupEventListeners();
- };
+ }
- Dropzone.prototype.filesize = function(size) {
- var cutoff, i, selectedSize, selectedUnit, unit, units, _i, _len;
- units = ['TB', 'GB', 'MB', 'KB', 'b'];
- selectedSize = selectedUnit = null;
- for (i = _i = 0, _len = units.length; _i < _len; i = ++_i) {
- unit = units[i];
- cutoff = Math.pow(this.options.filesizeBase, 4 - i) / 10;
- if (size >= cutoff) {
- selectedSize = size / Math.pow(this.options.filesizeBase, 4 - i);
- selectedUnit = unit;
- break;
+ // Returns a nicely formatted filesize
+
+ }, {
+ key: "filesize",
+ value: function filesize(size) {
+ var selectedSize = 0;
+ var selectedUnit = "b";
+
+ if (size > 0) {
+ var units = ['tb', 'gb', 'mb', 'kb', 'b'];
+
+ for (var i = 0; i < units.length; i++) {
+ var unit = units[i];
+ var cutoff = Math.pow(this.options.filesizeBase, 4 - i) / 10;
+
+ if (size >= cutoff) {
+ selectedSize = size / Math.pow(this.options.filesizeBase, 4 - i);
+ selectedUnit = unit;
+ break;
+ }
}
+
+ selectedSize = Math.round(10 * selectedSize) / 10; // Cutting of digits
}
- selectedSize = Math.round(10 * selectedSize) / 10;
- return "" + selectedSize + " " + selectedUnit;
- };
- Dropzone.prototype._updateMaxFilesReachedClass = function() {
- if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) {
+ return "" + selectedSize + " " + this.options.dictFileSizeUnits[selectedUnit];
+ }
+
+ // Adds or removes the `dz-max-files-reached` class from the form.
+
+ }, {
+ key: "_updateMaxFilesReachedClass",
+ value: function _updateMaxFilesReachedClass() {
+ if (this.options.maxFiles != null && this.getAcceptedFiles().length >= this.options.maxFiles) {
if (this.getAcceptedFiles().length === this.options.maxFiles) {
this.emit('maxfilesreached', this.files);
}
@@ -838,519 +1613,1194 @@
} else {
return this.element.classList.remove("dz-max-files-reached");
}
- };
-
- Dropzone.prototype.drop = function(e) {
- var files, items;
+ }
+ }, {
+ key: "drop",
+ value: function drop(e) {
if (!e.dataTransfer) {
return;
}
this.emit("drop", e);
- files = e.dataTransfer.files;
+
+ // Convert the FileList to an Array
+ // This is necessary for IE11
+ var files = [];
+ for (var i = 0; i < e.dataTransfer.files.length; i++) {
+ files[i] = e.dataTransfer.files[i];
+ }
+
+ this.emit("addedfiles", files);
+
+ // Even if it's a folder, files.length will contain the folders.
if (files.length) {
- items = e.dataTransfer.items;
- if (items && items.length && (items[0].webkitGetAsEntry != null)) {
+ var items = e.dataTransfer.items;
+
+ if (items && items.length && items[0].webkitGetAsEntry != null) {
+ // The browser supports dropping of folders, so handle items instead of files
this._addFilesFromItems(items);
} else {
this.handleFiles(files);
}
}
- };
-
- Dropzone.prototype.paste = function(e) {
- var items, _ref;
- if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) {
+ }
+ }, {
+ key: "paste",
+ value: function paste(e) {
+ if (__guard__(e != null ? e.clipboardData : undefined, function (x) {
+ return x.items;
+ }) == null) {
return;
}
+
this.emit("paste", e);
- items = e.clipboardData.items;
+ var items = e.clipboardData.items;
+
+
if (items.length) {
return this._addFilesFromItems(items);
}
- };
+ }
+ }, {
+ key: "handleFiles",
+ value: function handleFiles(files) {
+ for (var _iterator14 = files, _isArray14 = true, _i15 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) {
+ var _ref13;
+
+ if (_isArray14) {
+ if (_i15 >= _iterator14.length) break;
+ _ref13 = _iterator14[_i15++];
+ } else {
+ _i15 = _iterator14.next();
+ if (_i15.done) break;
+ _ref13 = _i15.value;
+ }
+
+ var file = _ref13;
- Dropzone.prototype.handleFiles = function(files) {
- var file, _i, _len, _results;
- _results = [];
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
- _results.push(this.addFile(file));
+ this.addFile(file);
}
- return _results;
- };
+ }
- Dropzone.prototype._addFilesFromItems = function(items) {
- var entry, item, _i, _len, _results;
- _results = [];
- for (_i = 0, _len = items.length; _i < _len; _i++) {
- item = items[_i];
- if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) {
- if (entry.isFile) {
- _results.push(this.addFile(item.getAsFile()));
- } else if (entry.isDirectory) {
- _results.push(this._addFilesFromDirectory(entry, entry.name));
+ // When a folder is dropped (or files are pasted), items must be handled
+ // instead of files.
+
+ }, {
+ key: "_addFilesFromItems",
+ value: function _addFilesFromItems(items) {
+ var _this5 = this;
+
+ return function () {
+ var result = [];
+ for (var _iterator15 = items, _isArray15 = true, _i16 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) {
+ var _ref14;
+
+ if (_isArray15) {
+ if (_i16 >= _iterator15.length) break;
+ _ref14 = _iterator15[_i16++];
} else {
- _results.push(void 0);
+ _i16 = _iterator15.next();
+ if (_i16.done) break;
+ _ref14 = _i16.value;
}
- } else if (item.getAsFile != null) {
- if ((item.kind == null) || item.kind === "file") {
- _results.push(this.addFile(item.getAsFile()));
+
+ var item = _ref14;
+
+ var entry;
+ if (item.webkitGetAsEntry != null && (entry = item.webkitGetAsEntry())) {
+ if (entry.isFile) {
+ result.push(_this5.addFile(item.getAsFile()));
+ } else if (entry.isDirectory) {
+ // Append all files from that directory to files
+ result.push(_this5._addFilesFromDirectory(entry, entry.name));
+ } else {
+ result.push(undefined);
+ }
+ } else if (item.getAsFile != null) {
+ if (item.kind == null || item.kind === "file") {
+ result.push(_this5.addFile(item.getAsFile()));
+ } else {
+ result.push(undefined);
+ }
} else {
- _results.push(void 0);
+ result.push(undefined);
}
- } else {
- _results.push(void 0);
}
- }
- return _results;
- };
+ return result;
+ }();
+ }
- Dropzone.prototype._addFilesFromDirectory = function(directory, path) {
- var dirReader, entriesReader;
- dirReader = directory.createReader();
- entriesReader = (function(_this) {
- return function(entries) {
- var entry, _i, _len;
- for (_i = 0, _len = entries.length; _i < _len; _i++) {
- entry = entries[_i];
- if (entry.isFile) {
- entry.file(function(file) {
- if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') {
- return;
- }
- file.fullPath = "" + path + "/" + file.name;
- return _this.addFile(file);
- });
- } else if (entry.isDirectory) {
- _this._addFilesFromDirectory(entry, "" + path + "/" + entry.name);
+ // Goes through the directory, and adds each file it finds recursively
+
+ }, {
+ key: "_addFilesFromDirectory",
+ value: function _addFilesFromDirectory(directory, path) {
+ var _this6 = this;
+
+ var dirReader = directory.createReader();
+
+ var errorHandler = function errorHandler(error) {
+ return __guardMethod__(console, 'log', function (o) {
+ return o.log(error);
+ });
+ };
+
+ var readEntries = function readEntries() {
+ return dirReader.readEntries(function (entries) {
+ if (entries.length > 0) {
+ for (var _iterator16 = entries, _isArray16 = true, _i17 = 0, _iterator16 = _isArray16 ? _iterator16 : _iterator16[Symbol.iterator]();;) {
+ var _ref15;
+
+ if (_isArray16) {
+ if (_i17 >= _iterator16.length) break;
+ _ref15 = _iterator16[_i17++];
+ } else {
+ _i17 = _iterator16.next();
+ if (_i17.done) break;
+ _ref15 = _i17.value;
+ }
+
+ var entry = _ref15;
+
+ if (entry.isFile) {
+ entry.file(function (file) {
+ if (_this6.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') {
+ return;
+ }
+ file.fullPath = path + "/" + file.name;
+ return _this6.addFile(file);
+ });
+ } else if (entry.isDirectory) {
+ _this6._addFilesFromDirectory(entry, path + "/" + entry.name);
+ }
}
+
+ // Recursively call readEntries() again, since browser only handle
+ // the first 100 entries.
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/DirectoryReader#readEntries
+ readEntries();
}
- };
- })(this);
- return dirReader.readEntries(entriesReader, function(error) {
- return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0;
- });
- };
+ return null;
+ }, errorHandler);
+ };
- Dropzone.prototype.accept = function(file, done) {
- if (file.size > this.options.maxFilesize * 1024 * 1024) {
+ return readEntries();
+ }
+
+ // If `done()` is called without argument the file is accepted
+ // If you call it with an error message, the file is rejected
+ // (This allows for asynchronous validation)
+ //
+ // This function checks the filesize, and if the file.type passes the
+ // `acceptedFiles` check.
+
+ }, {
+ key: "accept",
+ value: function accept(file, done) {
+ if (this.options.maxFilesize && file.size > this.options.maxFilesize * 1024 * 1024) {
return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize));
} else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) {
return done(this.options.dictInvalidFileType);
- } else if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) {
+ } else if (this.options.maxFiles != null && this.getAcceptedFiles().length >= this.options.maxFiles) {
done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles));
return this.emit("maxfilesexceeded", file);
} else {
return this.options.accept.call(this, file, done);
}
- };
+ }
+ }, {
+ key: "addFile",
+ value: function addFile(file) {
+ var _this7 = this;
- Dropzone.prototype.addFile = function(file) {
file.upload = {
+ uuid: Dropzone.uuidv4(),
progress: 0,
+ // Setting the total upload size to file.size for the beginning
+ // It's actual different than the size to be transmitted.
total: file.size,
- bytesSent: 0
+ bytesSent: 0,
+ filename: this._renameFile(file),
+ chunked: this.options.chunking && (this.options.forceChunking || file.size > this.options.chunkSize),
+ totalChunkCount: Math.ceil(file.size / this.options.chunkSize)
};
this.files.push(file);
+
file.status = Dropzone.ADDED;
+
this.emit("addedfile", file);
+
this._enqueueThumbnail(file);
- return this.accept(file, (function(_this) {
- return function(error) {
- if (error) {
- file.accepted = false;
- _this._errorProcessing([file], error);
- } else {
- file.accepted = true;
- if (_this.options.autoQueue) {
- _this.enqueueFile(file);
- }
- }
- return _this._updateMaxFilesReachedClass();
- };
- })(this));
- };
- Dropzone.prototype.enqueueFiles = function(files) {
- var file, _i, _len;
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
+ return this.accept(file, function (error) {
+ if (error) {
+ file.accepted = false;
+ _this7._errorProcessing([file], error); // Will set the file.status
+ } else {
+ file.accepted = true;
+ if (_this7.options.autoQueue) {
+ _this7.enqueueFile(file);
+ } // Will set .accepted = true
+ }
+ return _this7._updateMaxFilesReachedClass();
+ });
+ }
+
+ // Wrapper for enqueueFile
+
+ }, {
+ key: "enqueueFiles",
+ value: function enqueueFiles(files) {
+ for (var _iterator17 = files, _isArray17 = true, _i18 = 0, _iterator17 = _isArray17 ? _iterator17 : _iterator17[Symbol.iterator]();;) {
+ var _ref16;
+
+ if (_isArray17) {
+ if (_i18 >= _iterator17.length) break;
+ _ref16 = _iterator17[_i18++];
+ } else {
+ _i18 = _iterator17.next();
+ if (_i18.done) break;
+ _ref16 = _i18.value;
+ }
+
+ var file = _ref16;
+
this.enqueueFile(file);
}
return null;
- };
+ }
+ }, {
+ key: "enqueueFile",
+ value: function enqueueFile(file) {
+ var _this8 = this;
- Dropzone.prototype.enqueueFile = function(file) {
if (file.status === Dropzone.ADDED && file.accepted === true) {
file.status = Dropzone.QUEUED;
if (this.options.autoProcessQueue) {
- return setTimeout(((function(_this) {
- return function() {
- return _this.processQueue();
- };
- })(this)), 0);
+ return setTimeout(function () {
+ return _this8.processQueue();
+ }, 0); // Deferring the call
}
} else {
throw new Error("This file can't be queued because it has already been processed or was rejected.");
}
- };
-
- Dropzone.prototype._thumbnailQueue = [];
-
- Dropzone.prototype._processingThumbnail = false;
+ }
+ }, {
+ key: "_enqueueThumbnail",
+ value: function _enqueueThumbnail(file) {
+ var _this9 = this;
- Dropzone.prototype._enqueueThumbnail = function(file) {
if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) {
this._thumbnailQueue.push(file);
- return setTimeout(((function(_this) {
- return function() {
- return _this._processThumbnailQueue();
- };
- })(this)), 0);
+ return setTimeout(function () {
+ return _this9._processThumbnailQueue();
+ }, 0); // Deferring the call
}
- };
+ }
+ }, {
+ key: "_processThumbnailQueue",
+ value: function _processThumbnailQueue() {
+ var _this10 = this;
- Dropzone.prototype._processThumbnailQueue = function() {
if (this._processingThumbnail || this._thumbnailQueue.length === 0) {
return;
}
+
this._processingThumbnail = true;
- return this.createThumbnail(this._thumbnailQueue.shift(), (function(_this) {
- return function() {
- _this._processingThumbnail = false;
- return _this._processThumbnailQueue();
- };
- })(this));
- };
+ var file = this._thumbnailQueue.shift();
+ return this.createThumbnail(file, this.options.thumbnailWidth, this.options.thumbnailHeight, this.options.thumbnailMethod, true, function (dataUrl) {
+ _this10.emit("thumbnail", file, dataUrl);
+ _this10._processingThumbnail = false;
+ return _this10._processThumbnailQueue();
+ });
+ }
- Dropzone.prototype.removeFile = function(file) {
+ // Can be called by the user to remove a file
+
+ }, {
+ key: "removeFile",
+ value: function removeFile(file) {
if (file.status === Dropzone.UPLOADING) {
this.cancelUpload(file);
}
this.files = without(this.files, file);
+
this.emit("removedfile", file);
if (this.files.length === 0) {
return this.emit("reset");
}
- };
+ }
- Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) {
- var file, _i, _len, _ref;
+ // Removes all files that aren't currently processed from the list
+
+ }, {
+ key: "removeAllFiles",
+ value: function removeAllFiles(cancelIfNecessary) {
+ // Create a copy of files since removeFile() changes the @files array.
if (cancelIfNecessary == null) {
cancelIfNecessary = false;
}
- _ref = this.files.slice();
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
+ for (var _iterator18 = this.files.slice(), _isArray18 = true, _i19 = 0, _iterator18 = _isArray18 ? _iterator18 : _iterator18[Symbol.iterator]();;) {
+ var _ref17;
+
+ if (_isArray18) {
+ if (_i19 >= _iterator18.length) break;
+ _ref17 = _iterator18[_i19++];
+ } else {
+ _i19 = _iterator18.next();
+ if (_i19.done) break;
+ _ref17 = _i19.value;
+ }
+
+ var file = _ref17;
+
if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) {
this.removeFile(file);
}
}
return null;
- };
+ }
- Dropzone.prototype.createThumbnail = function(file, callback) {
- var fileReader;
- fileReader = new FileReader;
- fileReader.onload = (function(_this) {
- return function() {
- if (file.type === "image/svg+xml") {
- _this.emit("thumbnail", file, fileReader.result);
- if (callback != null) {
- callback();
- }
- return;
+ // Resizes an image before it gets sent to the server. This function is the default behavior of
+ // `options.transformFile` if `resizeWidth` or `resizeHeight` are set. The callback is invoked with
+ // the resized blob.
+
+ }, {
+ key: "resizeImage",
+ value: function resizeImage(file, width, height, resizeMethod, callback) {
+ var _this11 = this;
+
+ return this.createThumbnail(file, width, height, resizeMethod, true, function (dataUrl, canvas) {
+ if (canvas == null) {
+ // The image has not been resized
+ return callback(file);
+ } else {
+ var resizeMimeType = _this11.options.resizeMimeType;
+
+ if (resizeMimeType == null) {
+ resizeMimeType = file.type;
}
- return _this.createThumbnailFromUrl(file, fileReader.result, callback);
- };
- })(this);
+ var resizedDataURL = canvas.toDataURL(resizeMimeType, _this11.options.resizeQuality);
+ if (resizeMimeType === 'image/jpeg' || resizeMimeType === 'image/jpg') {
+ // Now add the original EXIF information
+ resizedDataURL = ExifRestore.restore(file.dataURL, resizedDataURL);
+ }
+ return callback(Dropzone.dataURItoBlob(resizedDataURL));
+ }
+ });
+ }
+ }, {
+ key: "createThumbnail",
+ value: function createThumbnail(file, width, height, resizeMethod, fixOrientation, callback) {
+ var _this12 = this;
+
+ var fileReader = new FileReader();
+
+ fileReader.onload = function () {
+
+ file.dataURL = fileReader.result;
+
+ // Don't bother creating a thumbnail for SVG images since they're vector
+ if (file.type === "image/svg+xml") {
+ if (callback != null) {
+ callback(fileReader.result);
+ }
+ return;
+ }
+
+ return _this12.createThumbnailFromUrl(file, width, height, resizeMethod, fixOrientation, callback);
+ };
+
return fileReader.readAsDataURL(file);
- };
+ }
+ }, {
+ key: "createThumbnailFromUrl",
+ value: function createThumbnailFromUrl(file, width, height, resizeMethod, fixOrientation, callback, crossOrigin) {
+ var _this13 = this;
+
+ // Not using `new Image` here because of a bug in latest Chrome versions.
+ // See https://github.com/enyo/dropzone/pull/226
+ var img = document.createElement("img");
+
+ if (crossOrigin) {
+ img.crossOrigin = crossOrigin;
+ }
+
+ img.onload = function () {
+ var loadExif = function loadExif(callback) {
+ return callback(1);
+ };
+ if (typeof EXIF !== 'undefined' && EXIF !== null && fixOrientation) {
+ loadExif = function loadExif(callback) {
+ return EXIF.getData(img, function () {
+ return callback(EXIF.getTag(this, 'Orientation'));
+ });
+ };
+ }
- Dropzone.prototype.createThumbnailFromUrl = function(file, imageUrl, callback) {
- var img;
- img = document.createElement("img");
- img.onload = (function(_this) {
- return function() {
- var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3;
+ return loadExif(function (orientation) {
file.width = img.width;
file.height = img.height;
- resizeInfo = _this.options.resize.call(_this, file);
- if (resizeInfo.trgWidth == null) {
- resizeInfo.trgWidth = resizeInfo.optWidth;
- }
- if (resizeInfo.trgHeight == null) {
- resizeInfo.trgHeight = resizeInfo.optHeight;
- }
- canvas = document.createElement("canvas");
- ctx = canvas.getContext("2d");
+
+ var resizeInfo = _this13.options.resize.call(_this13, file, width, height, resizeMethod);
+
+ var canvas = document.createElement("canvas");
+ var ctx = canvas.getContext("2d");
+
canvas.width = resizeInfo.trgWidth;
canvas.height = resizeInfo.trgHeight;
- drawImageIOSFix(ctx, img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight);
- thumbnail = canvas.toDataURL("image/png");
- _this.emit("thumbnail", file, thumbnail);
+
+ if (orientation > 4) {
+ canvas.width = resizeInfo.trgHeight;
+ canvas.height = resizeInfo.trgWidth;
+ }
+
+ switch (orientation) {
+ case 2:
+ // horizontal flip
+ ctx.translate(canvas.width, 0);
+ ctx.scale(-1, 1);
+ break;
+ case 3:
+ // 180° rotate left
+ ctx.translate(canvas.width, canvas.height);
+ ctx.rotate(Math.PI);
+ break;
+ case 4:
+ // vertical flip
+ ctx.translate(0, canvas.height);
+ ctx.scale(1, -1);
+ break;
+ case 5:
+ // vertical flip + 90 rotate right
+ ctx.rotate(0.5 * Math.PI);
+ ctx.scale(1, -1);
+ break;
+ case 6:
+ // 90° rotate right
+ ctx.rotate(0.5 * Math.PI);
+ ctx.translate(0, -canvas.width);
+ break;
+ case 7:
+ // horizontal flip + 90 rotate right
+ ctx.rotate(0.5 * Math.PI);
+ ctx.translate(canvas.height, -canvas.width);
+ ctx.scale(-1, 1);
+ break;
+ case 8:
+ // 90° rotate left
+ ctx.rotate(-0.5 * Math.PI);
+ ctx.translate(-canvas.height, 0);
+ break;
+ }
+
+ // This is a bugfix for iOS' scaling bug.
+ drawImageIOSFix(ctx, img, resizeInfo.srcX != null ? resizeInfo.srcX : 0, resizeInfo.srcY != null ? resizeInfo.srcY : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, resizeInfo.trgX != null ? resizeInfo.trgX : 0, resizeInfo.trgY != null ? resizeInfo.trgY : 0, resizeInfo.trgWidth, resizeInfo.trgHeight);
+
+ var thumbnail = canvas.toDataURL("image/png");
+
if (callback != null) {
- return callback();
+ return callback(thumbnail, canvas);
}
- };
- })(this);
+ });
+ };
+
if (callback != null) {
img.onerror = callback;
}
- return img.src = imageUrl;
- };
- Dropzone.prototype.processQueue = function() {
- var i, parallelUploads, processingLength, queuedFiles;
- parallelUploads = this.options.parallelUploads;
- processingLength = this.getUploadingFiles().length;
- i = processingLength;
+ return img.src = file.dataURL;
+ }
+
+ // Goes through the queue and processes files if there aren't too many already.
+
+ }, {
+ key: "processQueue",
+ value: function processQueue() {
+ var parallelUploads = this.options.parallelUploads;
+
+ var processingLength = this.getUploadingFiles().length;
+ var i = processingLength;
+
+ // There are already at least as many files uploading than should be
if (processingLength >= parallelUploads) {
return;
}
- queuedFiles = this.getQueuedFiles();
+
+ var queuedFiles = this.getQueuedFiles();
+
if (!(queuedFiles.length > 0)) {
return;
}
+
if (this.options.uploadMultiple) {
+ // The files should be uploaded in one request
return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength));
} else {
while (i < parallelUploads) {
if (!queuedFiles.length) {
return;
- }
+ } // Nothing left to process
this.processFile(queuedFiles.shift());
i++;
}
}
- };
+ }
- Dropzone.prototype.processFile = function(file) {
+ // Wrapper for `processFiles`
+
+ }, {
+ key: "processFile",
+ value: function processFile(file) {
return this.processFiles([file]);
- };
+ }
+
+ // Loads the file, then calls finishedLoading()
+
+ }, {
+ key: "processFiles",
+ value: function processFiles(files) {
+ for (var _iterator19 = files, _isArray19 = true, _i20 = 0, _iterator19 = _isArray19 ? _iterator19 : _iterator19[Symbol.iterator]();;) {
+ var _ref18;
+
+ if (_isArray19) {
+ if (_i20 >= _iterator19.length) break;
+ _ref18 = _iterator19[_i20++];
+ } else {
+ _i20 = _iterator19.next();
+ if (_i20.done) break;
+ _ref18 = _i20.value;
+ }
+
+ var file = _ref18;
+
+ file.processing = true; // Backwards compatibility
+ file.status = Dropzone.UPLOADING;
- Dropzone.prototype.processFiles = function(files) {
- var file, _i, _len;
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
- file.processing = true;
- file.status = Dropzone.UPLOADING;
this.emit("processing", file);
}
+
if (this.options.uploadMultiple) {
this.emit("processingmultiple", files);
}
+
return this.uploadFiles(files);
- };
+ }
+ }, {
+ key: "_getFilesWithXhr",
+ value: function _getFilesWithXhr(xhr) {
+ var files = void 0;
+ return files = this.files.filter(function (file) {
+ return file.xhr === xhr;
+ }).map(function (file) {
+ return file;
+ });
+ }
- Dropzone.prototype._getFilesWithXhr = function(xhr) {
- var file, files;
- return files = (function() {
- var _i, _len, _ref, _results;
- _ref = this.files;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- file = _ref[_i];
- if (file.xhr === xhr) {
- _results.push(file);
- }
- }
- return _results;
- }).call(this);
- };
+ // Cancels the file upload and sets the status to CANCELED
+ // **if** the file is actually being uploaded.
+ // If it's still in the queue, the file is being removed from it and the status
+ // set to CANCELED.
- Dropzone.prototype.cancelUpload = function(file) {
- var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref;
+ }, {
+ key: "cancelUpload",
+ value: function cancelUpload(file) {
if (file.status === Dropzone.UPLOADING) {
- groupedFiles = this._getFilesWithXhr(file.xhr);
- for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) {
- groupedFile = groupedFiles[_i];
+ var groupedFiles = this._getFilesWithXhr(file.xhr);
+ for (var _iterator20 = groupedFiles, _isArray20 = true, _i21 = 0, _iterator20 = _isArray20 ? _iterator20 : _iterator20[Symbol.iterator]();;) {
+ var _ref19;
+
+ if (_isArray20) {
+ if (_i21 >= _iterator20.length) break;
+ _ref19 = _iterator20[_i21++];
+ } else {
+ _i21 = _iterator20.next();
+ if (_i21.done) break;
+ _ref19 = _i21.value;
+ }
+
+ var groupedFile = _ref19;
+
groupedFile.status = Dropzone.CANCELED;
}
- file.xhr.abort();
- for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) {
- groupedFile = groupedFiles[_j];
- this.emit("canceled", groupedFile);
+ if (typeof file.xhr !== 'undefined') {
+ file.xhr.abort();
+ }
+ for (var _iterator21 = groupedFiles, _isArray21 = true, _i22 = 0, _iterator21 = _isArray21 ? _iterator21 : _iterator21[Symbol.iterator]();;) {
+ var _ref20;
+
+ if (_isArray21) {
+ if (_i22 >= _iterator21.length) break;
+ _ref20 = _iterator21[_i22++];
+ } else {
+ _i22 = _iterator21.next();
+ if (_i22.done) break;
+ _ref20 = _i22.value;
+ }
+
+ var _groupedFile = _ref20;
+
+ this.emit("canceled", _groupedFile);
}
if (this.options.uploadMultiple) {
this.emit("canceledmultiple", groupedFiles);
}
- } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) {
+ } else if (file.status === Dropzone.ADDED || file.status === Dropzone.QUEUED) {
file.status = Dropzone.CANCELED;
this.emit("canceled", file);
if (this.options.uploadMultiple) {
this.emit("canceledmultiple", [file]);
}
}
+
if (this.options.autoProcessQueue) {
return this.processQueue();
}
- };
-
- resolveOption = function() {
- var args, option;
- option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+ }
+ }, {
+ key: "resolveOption",
+ value: function resolveOption(option) {
if (typeof option === 'function') {
+ for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
+ args[_key3 - 1] = arguments[_key3];
+ }
+
return option.apply(this, args);
}
return option;
- };
-
- Dropzone.prototype.uploadFile = function(file) {
+ }
+ }, {
+ key: "uploadFile",
+ value: function uploadFile(file) {
return this.uploadFiles([file]);
- };
+ }
+ }, {
+ key: "uploadFiles",
+ value: function uploadFiles(files) {
+ var _this14 = this;
- Dropzone.prototype.uploadFiles = function(files) {
- var file, formData, handleError, headerName, headerValue, headers, i, input, inputName, inputType, key, method, option, progressObj, response, updateProgress, url, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
- xhr = new XMLHttpRequest();
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
- file.xhr = xhr;
- }
- method = resolveOption(this.options.method, files);
- url = resolveOption(this.options.url, files);
- xhr.open(method, url, true);
- xhr.withCredentials = !!this.options.withCredentials;
- response = null;
- handleError = (function(_this) {
- return function() {
- var _j, _len1, _results;
- _results = [];
- for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
- file = files[_j];
- _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr));
- }
- return _results;
- };
- })(this);
- updateProgress = (function(_this) {
- return function(e) {
- var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results;
- if (e != null) {
- progress = 100 * e.loaded / e.total;
- for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
- file = files[_j];
- file.upload = {
- progress: progress,
- total: e.total,
- bytesSent: e.loaded
- };
+ this._transformFiles(files, function (transformedFiles) {
+ if (files[0].upload.chunked) {
+ // This file should be sent in chunks!
+
+ // If the chunking option is set, we **know** that there can only be **one** file, since
+ // uploadMultiple is not allowed with this option.
+ var file = files[0];
+ var transformedFile = transformedFiles[0];
+ var startedChunkCount = 0;
+
+ file.upload.chunks = [];
+
+ var handleNextChunk = function handleNextChunk() {
+ var chunkIndex = 0;
+
+ // Find the next item in file.upload.chunks that is not defined yet.
+ while (file.upload.chunks[chunkIndex] !== undefined) {
+ chunkIndex++;
}
- } else {
- allFilesFinished = true;
- progress = 100;
- for (_k = 0, _len2 = files.length; _k < _len2; _k++) {
- file = files[_k];
- if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) {
- allFilesFinished = false;
+
+ // This means, that all chunks have already been started.
+ if (chunkIndex >= file.upload.totalChunkCount) return;
+
+ startedChunkCount++;
+
+ var start = chunkIndex * _this14.options.chunkSize;
+ var end = Math.min(start + _this14.options.chunkSize, file.size);
+
+ var dataBlock = {
+ name: _this14._getParamName(0),
+ data: transformedFile.webkitSlice ? transformedFile.webkitSlice(start, end) : transformedFile.slice(start, end),
+ filename: file.upload.filename,
+ chunkIndex: chunkIndex
+ };
+
+ file.upload.chunks[chunkIndex] = {
+ file: file,
+ index: chunkIndex,
+ dataBlock: dataBlock, // In case we want to retry.
+ status: Dropzone.UPLOADING,
+ progress: 0,
+ retries: 0 // The number of times this block has been retried.
+ };
+
+ _this14._uploadData(files, [dataBlock]);
+ };
+
+ file.upload.finishedChunkUpload = function (chunk) {
+ var allFinished = true;
+ chunk.status = Dropzone.SUCCESS;
+
+ // Clear the data from the chunk
+ chunk.dataBlock = null;
+ // Leaving this reference to xhr intact here will cause memory leaks in some browsers
+ chunk.xhr = null;
+
+ for (var i = 0; i < file.upload.totalChunkCount; i++) {
+ if (file.upload.chunks[i] === undefined) {
+ return handleNextChunk();
+ }
+ if (file.upload.chunks[i].status !== Dropzone.SUCCESS) {
+ allFinished = false;
}
- file.upload.progress = progress;
- file.upload.bytesSent = file.upload.total;
}
- if (allFilesFinished) {
- return;
+
+ if (allFinished) {
+ _this14.options.chunksUploaded(file, function () {
+ _this14._finished(files, '', null);
+ });
}
- }
- _results = [];
- for (_l = 0, _len3 = files.length; _l < _len3; _l++) {
- file = files[_l];
- _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent));
- }
- return _results;
- };
- })(this);
- xhr.onload = (function(_this) {
- return function(e) {
- var _ref;
- if (files[0].status === Dropzone.CANCELED) {
- return;
- }
- if (xhr.readyState !== 4) {
- return;
- }
- response = xhr.responseText;
- if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
- try {
- response = JSON.parse(response);
- } catch (_error) {
- e = _error;
- response = "Invalid JSON response from server.";
+ };
+
+ if (_this14.options.parallelChunkUploads) {
+ for (var i = 0; i < file.upload.totalChunkCount; i++) {
+ handleNextChunk();
}
- }
- updateProgress();
- if (!((200 <= (_ref = xhr.status) && _ref < 300))) {
- return handleError();
} else {
- return _this._finished(files, response, e);
+ handleNextChunk();
}
- };
- })(this);
- xhr.onerror = (function(_this) {
- return function() {
- if (files[0].status === Dropzone.CANCELED) {
- return;
+ } else {
+ var dataBlocks = [];
+ for (var _i23 = 0; _i23 < files.length; _i23++) {
+ dataBlocks[_i23] = {
+ name: _this14._getParamName(_i23),
+ data: transformedFiles[_i23],
+ filename: files[_i23].upload.filename
+ };
}
- return handleError();
- };
- })(this);
- progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
- progressObj.onprogress = updateProgress;
- headers = {
+ _this14._uploadData(files, dataBlocks);
+ }
+ });
+ }
+
+ /// Returns the right chunk for given file and xhr
+
+ }, {
+ key: "_getChunk",
+ value: function _getChunk(file, xhr) {
+ for (var i = 0; i < file.upload.totalChunkCount; i++) {
+ if (file.upload.chunks[i] !== undefined && file.upload.chunks[i].xhr === xhr) {
+ return file.upload.chunks[i];
+ }
+ }
+ }
+
+ // This function actually uploads the file(s) to the server.
+ // If dataBlocks contains the actual data to upload (meaning, that this could either be transformed
+ // files, or individual chunks for chunked upload).
+
+ }, {
+ key: "_uploadData",
+ value: function _uploadData(files, dataBlocks) {
+ var _this15 = this;
+
+ var xhr = new XMLHttpRequest();
+
+ // Put the xhr object in the file objects to be able to reference it later.
+ for (var _iterator22 = files, _isArray22 = true, _i24 = 0, _iterator22 = _isArray22 ? _iterator22 : _iterator22[Symbol.iterator]();;) {
+ var _ref21;
+
+ if (_isArray22) {
+ if (_i24 >= _iterator22.length) break;
+ _ref21 = _iterator22[_i24++];
+ } else {
+ _i24 = _iterator22.next();
+ if (_i24.done) break;
+ _ref21 = _i24.value;
+ }
+
+ var file = _ref21;
+
+ file.xhr = xhr;
+ }
+ if (files[0].upload.chunked) {
+ // Put the xhr object in the right chunk object, so it can be associated later, and found with _getChunk
+ files[0].upload.chunks[dataBlocks[0].chunkIndex].xhr = xhr;
+ }
+
+ var method = this.resolveOption(this.options.method, files);
+ var url = this.resolveOption(this.options.url, files);
+ xhr.open(method, url, true);
+
+ // Setting the timeout after open because of IE11 issue: https://gitlab.com/meno/dropzone/issues/8
+ xhr.timeout = this.resolveOption(this.options.timeout, files);
+
+ // Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
+ xhr.withCredentials = !!this.options.withCredentials;
+
+ xhr.onload = function (e) {
+ _this15._finishedUploading(files, xhr, e);
+ };
+
+ xhr.onerror = function () {
+ _this15._handleUploadError(files, xhr);
+ };
+
+ // Some browsers do not have the .upload property
+ var progressObj = xhr.upload != null ? xhr.upload : xhr;
+ progressObj.onprogress = function (e) {
+ return _this15._updateFilesUploadProgress(files, xhr, e);
+ };
+
+ var headers = {
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest"
};
+
if (this.options.headers) {
- extend(headers, this.options.headers);
+ Dropzone.extend(headers, this.options.headers);
}
- for (headerName in headers) {
- headerValue = headers[headerName];
- xhr.setRequestHeader(headerName, headerValue);
+
+ for (var headerName in headers) {
+ var headerValue = headers[headerName];
+ if (headerValue) {
+ xhr.setRequestHeader(headerName, headerValue);
+ }
}
- formData = new FormData();
+
+ var formData = new FormData();
+
+ // Adding all @options parameters
if (this.options.params) {
- _ref1 = this.options.params;
- for (key in _ref1) {
- value = _ref1[key];
+ var additionalParams = this.options.params;
+ if (typeof additionalParams === 'function') {
+ additionalParams = additionalParams.call(this, files, xhr, files[0].upload.chunked ? this._getChunk(files[0], xhr) : null);
+ }
+
+ for (var key in additionalParams) {
+ var value = additionalParams[key];
formData.append(key, value);
}
}
- for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
- file = files[_j];
- this.emit("sending", file, xhr, formData);
+
+ // Let the user add additional data if necessary
+ for (var _iterator23 = files, _isArray23 = true, _i25 = 0, _iterator23 = _isArray23 ? _iterator23 : _iterator23[Symbol.iterator]();;) {
+ var _ref22;
+
+ if (_isArray23) {
+ if (_i25 >= _iterator23.length) break;
+ _ref22 = _iterator23[_i25++];
+ } else {
+ _i25 = _iterator23.next();
+ if (_i25.done) break;
+ _ref22 = _i25.value;
+ }
+
+ var _file = _ref22;
+
+ this.emit("sending", _file, xhr, formData);
}
if (this.options.uploadMultiple) {
this.emit("sendingmultiple", files, xhr, formData);
}
+
+ this._addFormElementData(formData);
+
+ // Finally add the files
+ // Has to be last because some servers (eg: S3) expect the file to be the last parameter
+ for (var i = 0; i < dataBlocks.length; i++) {
+ var dataBlock = dataBlocks[i];
+ formData.append(dataBlock.name, dataBlock.data, dataBlock.filename);
+ }
+
+ this.submitRequest(xhr, formData, files);
+ }
+
+ // Transforms all files with this.options.transformFile and invokes done with the transformed files when done.
+
+ }, {
+ key: "_transformFiles",
+ value: function _transformFiles(files, done) {
+ var _this16 = this;
+
+ var transformedFiles = [];
+ // Clumsy way of handling asynchronous calls, until I get to add a proper Future library.
+ var doneCounter = 0;
+
+ var _loop = function _loop(i) {
+ _this16.options.transformFile.call(_this16, files[i], function (transformedFile) {
+ transformedFiles[i] = transformedFile;
+ if (++doneCounter === files.length) {
+ done(transformedFiles);
+ }
+ });
+ };
+
+ for (var i = 0; i < files.length; i++) {
+ _loop(i);
+ }
+ }
+
+ // Takes care of adding other input elements of the form to the AJAX request
+
+ }, {
+ key: "_addFormElementData",
+ value: function _addFormElementData(formData) {
+ // Take care of other input elements
if (this.element.tagName === "FORM") {
- _ref2 = this.element.querySelectorAll("input, textarea, select, button");
- for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
- input = _ref2[_k];
- inputName = input.getAttribute("name");
- inputType = input.getAttribute("type");
+ for (var _iterator24 = this.element.querySelectorAll("input, textarea, select, button"), _isArray24 = true, _i26 = 0, _iterator24 = _isArray24 ? _iterator24 : _iterator24[Symbol.iterator]();;) {
+ var _ref23;
+
+ if (_isArray24) {
+ if (_i26 >= _iterator24.length) break;
+ _ref23 = _iterator24[_i26++];
+ } else {
+ _i26 = _iterator24.next();
+ if (_i26.done) break;
+ _ref23 = _i26.value;
+ }
+
+ var input = _ref23;
+
+ var inputName = input.getAttribute("name");
+ var inputType = input.getAttribute("type");
+ if (inputType) inputType = inputType.toLowerCase();
+
+ // If the input doesn't have a name, we can't use it.
+ if (typeof inputName === 'undefined' || inputName === null) continue;
+
if (input.tagName === "SELECT" && input.hasAttribute("multiple")) {
- _ref3 = input.options;
- for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
- option = _ref3[_l];
+ // Possibly multiple values
+ for (var _iterator25 = input.options, _isArray25 = true, _i27 = 0, _iterator25 = _isArray25 ? _iterator25 : _iterator25[Symbol.iterator]();;) {
+ var _ref24;
+
+ if (_isArray25) {
+ if (_i27 >= _iterator25.length) break;
+ _ref24 = _iterator25[_i27++];
+ } else {
+ _i27 = _iterator25.next();
+ if (_i27.done) break;
+ _ref24 = _i27.value;
+ }
+
+ var option = _ref24;
+
if (option.selected) {
formData.append(inputName, option.value);
}
}
- } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) {
+ } else if (!inputType || inputType !== "checkbox" && inputType !== "radio" || input.checked) {
formData.append(inputName, input.value);
}
}
}
- for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) {
- formData.append(this._getParamName(i), files[i], files[i].name);
+ }
+
+ // Invoked when there is new progress information about given files.
+ // If e is not provided, it is assumed that the upload is finished.
+
+ }, {
+ key: "_updateFilesUploadProgress",
+ value: function _updateFilesUploadProgress(files, xhr, e) {
+ var progress = void 0;
+ if (typeof e !== 'undefined') {
+ progress = 100 * e.loaded / e.total;
+
+ if (files[0].upload.chunked) {
+ var file = files[0];
+ // Since this is a chunked upload, we need to update the appropriate chunk progress.
+ var chunk = this._getChunk(file, xhr);
+ chunk.progress = progress;
+ chunk.total = e.total;
+ chunk.bytesSent = e.loaded;
+ var fileProgress = 0,
+ fileTotal = void 0,
+ fileBytesSent = void 0;
+ file.upload.progress = 0;
+ file.upload.total = 0;
+ file.upload.bytesSent = 0;
+ for (var i = 0; i < file.upload.totalChunkCount; i++) {
+ if (file.upload.chunks[i] !== undefined && file.upload.chunks[i].progress !== undefined) {
+ file.upload.progress += file.upload.chunks[i].progress;
+ file.upload.total += file.upload.chunks[i].total;
+ file.upload.bytesSent += file.upload.chunks[i].bytesSent;
+ }
+ }
+ file.upload.progress = file.upload.progress / file.upload.totalChunkCount;
+ } else {
+ for (var _iterator26 = files, _isArray26 = true, _i28 = 0, _iterator26 = _isArray26 ? _iterator26 : _iterator26[Symbol.iterator]();;) {
+ var _ref25;
+
+ if (_isArray26) {
+ if (_i28 >= _iterator26.length) break;
+ _ref25 = _iterator26[_i28++];
+ } else {
+ _i28 = _iterator26.next();
+ if (_i28.done) break;
+ _ref25 = _i28.value;
+ }
+
+ var _file2 = _ref25;
+
+ _file2.upload.progress = progress;
+ _file2.upload.total = e.total;
+ _file2.upload.bytesSent = e.loaded;
+ }
+ }
+ for (var _iterator27 = files, _isArray27 = true, _i29 = 0, _iterator27 = _isArray27 ? _iterator27 : _iterator27[Symbol.iterator]();;) {
+ var _ref26;
+
+ if (_isArray27) {
+ if (_i29 >= _iterator27.length) break;
+ _ref26 = _iterator27[_i29++];
+ } else {
+ _i29 = _iterator27.next();
+ if (_i29.done) break;
+ _ref26 = _i29.value;
+ }
+
+ var _file3 = _ref26;
+
+ this.emit("uploadprogress", _file3, _file3.upload.progress, _file3.upload.bytesSent);
+ }
+ } else {
+ // Called when the file finished uploading
+
+ var allFilesFinished = true;
+
+ progress = 100;
+
+ for (var _iterator28 = files, _isArray28 = true, _i30 = 0, _iterator28 = _isArray28 ? _iterator28 : _iterator28[Symbol.iterator]();;) {
+ var _ref27;
+
+ if (_isArray28) {
+ if (_i30 >= _iterator28.length) break;
+ _ref27 = _iterator28[_i30++];
+ } else {
+ _i30 = _iterator28.next();
+ if (_i30.done) break;
+ _ref27 = _i30.value;
+ }
+
+ var _file4 = _ref27;
+
+ if (_file4.upload.progress !== 100 || _file4.upload.bytesSent !== _file4.upload.total) {
+ allFilesFinished = false;
+ }
+ _file4.upload.progress = progress;
+ _file4.upload.bytesSent = _file4.upload.total;
+ }
+
+ // Nothing to do, all files already at 100%
+ if (allFilesFinished) {
+ return;
+ }
+
+ for (var _iterator29 = files, _isArray29 = true, _i31 = 0, _iterator29 = _isArray29 ? _iterator29 : _iterator29[Symbol.iterator]();;) {
+ var _ref28;
+
+ if (_isArray29) {
+ if (_i31 >= _iterator29.length) break;
+ _ref28 = _iterator29[_i31++];
+ } else {
+ _i31 = _iterator29.next();
+ if (_i31.done) break;
+ _ref28 = _i31.value;
+ }
+
+ var _file5 = _ref28;
+
+ this.emit("uploadprogress", _file5, progress, _file5.upload.bytesSent);
+ }
}
- return xhr.send(formData);
- };
+ }
+ }, {
+ key: "_finishedUploading",
+ value: function _finishedUploading(files, xhr, e) {
+ var response = void 0;
+
+ if (files[0].status === Dropzone.CANCELED) {
+ return;
+ }
+
+ if (xhr.readyState !== 4) {
+ return;
+ }
+
+ if (xhr.responseType !== 'arraybuffer' && xhr.responseType !== 'blob') {
+ response = xhr.responseText;
+
+ if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
+ try {
+ response = JSON.parse(response);
+ } catch (error) {
+ e = error;
+ response = "Invalid JSON response from server.";
+ }
+ }
+ }
+
+ this._updateFilesUploadProgress(files);
+
+ if (!(200 <= xhr.status && xhr.status < 300)) {
+ this._handleUploadError(files, xhr, response);
+ } else {
+ if (files[0].upload.chunked) {
+ files[0].upload.finishedChunkUpload(this._getChunk(files[0], xhr));
+ } else {
+ this._finished(files, response, e);
+ }
+ }
+ }
+ }, {
+ key: "_handleUploadError",
+ value: function _handleUploadError(files, xhr, response) {
+ if (files[0].status === Dropzone.CANCELED) {
+ return;
+ }
+
+ if (files[0].upload.chunked && this.options.retryChunks) {
+ var chunk = this._getChunk(files[0], xhr);
+ if (chunk.retries++ < this.options.retryChunksLimit) {
+ this._uploadData(files, [chunk.dataBlock]);
+ return;
+ } else {
+ console.warn('Retried this chunk too often. Giving up.');
+ }
+ }
+
+ for (var _iterator30 = files, _isArray30 = true, _i32 = 0, _iterator30 = _isArray30 ? _iterator30 : _iterator30[Symbol.iterator]();;) {
+ var _ref29;
+
+ if (_isArray30) {
+ if (_i32 >= _iterator30.length) break;
+ _ref29 = _iterator30[_i32++];
+ } else {
+ _i32 = _iterator30.next();
+ if (_i32.done) break;
+ _ref29 = _i32.value;
+ }
+
+ var file = _ref29;
+
+ this._errorProcessing(files, response || this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr);
+ }
+ }
+ }, {
+ key: "submitRequest",
+ value: function submitRequest(xhr, formData, files) {
+ xhr.send(formData);
+ }
+
+ // Called internally when processing is finished.
+ // Individual callbacks have to be called in the appropriate sections.
+
+ }, {
+ key: "_finished",
+ value: function _finished(files, responseText, e) {
+ for (var _iterator31 = files, _isArray31 = true, _i33 = 0, _iterator31 = _isArray31 ? _iterator31 : _iterator31[Symbol.iterator]();;) {
+ var _ref30;
+
+ if (_isArray31) {
+ if (_i33 >= _iterator31.length) break;
+ _ref30 = _iterator31[_i33++];
+ } else {
+ _i33 = _iterator31.next();
+ if (_i33.done) break;
+ _ref30 = _i33.value;
+ }
+
+ var file = _ref30;
- Dropzone.prototype._finished = function(files, responseText, e) {
- var file, _i, _len;
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
file.status = Dropzone.SUCCESS;
this.emit("success", file, responseText, e);
this.emit("complete", file);
@@ -1359,15 +2809,32 @@
this.emit("successmultiple", files, responseText, e);
this.emit("completemultiple", files);
}
+
if (this.options.autoProcessQueue) {
return this.processQueue();
}
- };
+ }
+
+ // Called internally when processing is finished.
+ // Individual callbacks have to be called in the appropriate sections.
+
+ }, {
+ key: "_errorProcessing",
+ value: function _errorProcessing(files, message, xhr) {
+ for (var _iterator32 = files, _isArray32 = true, _i34 = 0, _iterator32 = _isArray32 ? _iterator32 : _iterator32[Symbol.iterator]();;) {
+ var _ref31;
+
+ if (_isArray32) {
+ if (_i34 >= _iterator32.length) break;
+ _ref31 = _iterator32[_i34++];
+ } else {
+ _i34 = _iterator32.next();
+ if (_i34.done) break;
+ _ref31 = _i34.value;
+ }
+
+ var file = _ref31;
- Dropzone.prototype._errorProcessing = function(files, message, xhr) {
- var file, _i, _len;
- for (_i = 0, _len = files.length; _i < _len; _i++) {
- file = files[_i];
file.status = Dropzone.ERROR;
this.emit("error", file, message, xhr);
this.emit("complete", file);
@@ -1376,353 +2843,688 @@
this.emit("errormultiple", files, message, xhr);
this.emit("completemultiple", files);
}
+
if (this.options.autoProcessQueue) {
return this.processQueue();
}
- };
-
- return Dropzone;
-
- })(Emitter);
-
- Dropzone.version = "4.0.1";
+ }
+ }], [{
+ key: "uuidv4",
+ value: function uuidv4() {
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
+ var r = Math.random() * 16 | 0,
+ v = c === 'x' ? r : r & 0x3 | 0x8;
+ return v.toString(16);
+ });
+ }
+ }]);
+
+ return Dropzone;
+}(Emitter);
+
+Dropzone.initClass();
+
+Dropzone.version = "5.5.0";
+
+// This is a map of options for your different dropzones. Add configurations
+// to this object for your different dropzone elemens.
+//
+// Example:
+//
+// Dropzone.options.myDropzoneElementId = { maxFilesize: 1 };
+//
+// To disable autoDiscover for a specific element, you can set `false` as an option:
+//
+// Dropzone.options.myDisabledElementId = false;
+//
+// And in html:
+//
+//
+Dropzone.options = {};
+
+// Returns the options for an element or undefined if none available.
+Dropzone.optionsForElement = function (element) {
+ // Get the `Dropzone.options.elementId` for this element if it exists
+ if (element.getAttribute("id")) {
+ return Dropzone.options[camelize(element.getAttribute("id"))];
+ } else {
+ return undefined;
+ }
+};
- Dropzone.options = {};
+// Holds a list of all dropzone instances
+Dropzone.instances = [];
- Dropzone.optionsForElement = function(element) {
- if (element.getAttribute("id")) {
- return Dropzone.options[camelize(element.getAttribute("id"))];
- } else {
- return void 0;
- }
- };
+// Returns the dropzone for given element if any
+Dropzone.forElement = function (element) {
+ if (typeof element === "string") {
+ element = document.querySelector(element);
+ }
+ if ((element != null ? element.dropzone : undefined) == null) {
+ throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");
+ }
+ return element.dropzone;
+};
- Dropzone.instances = [];
+// Set to false if you don't want Dropzone to automatically find and attach to .dropzone elements.
+Dropzone.autoDiscover = true;
- Dropzone.forElement = function(element) {
- if (typeof element === "string") {
- element = document.querySelector(element);
- }
- if ((element != null ? element.dropzone : void 0) == null) {
- throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");
- }
- return element.dropzone;
- };
+// Looks for all .dropzone elements and creates a dropzone for them
+Dropzone.discover = function () {
+ var dropzones = void 0;
+ if (document.querySelectorAll) {
+ dropzones = document.querySelectorAll(".dropzone");
+ } else {
+ dropzones = [];
+ // IE :(
+ var checkElements = function checkElements(elements) {
+ return function () {
+ var result = [];
+ for (var _iterator33 = elements, _isArray33 = true, _i35 = 0, _iterator33 = _isArray33 ? _iterator33 : _iterator33[Symbol.iterator]();;) {
+ var _ref32;
+
+ if (_isArray33) {
+ if (_i35 >= _iterator33.length) break;
+ _ref32 = _iterator33[_i35++];
+ } else {
+ _i35 = _iterator33.next();
+ if (_i35.done) break;
+ _ref32 = _i35.value;
+ }
- Dropzone.autoDiscover = true;
+ var el = _ref32;
- Dropzone.discover = function() {
- var checkElements, dropzone, dropzones, _i, _len, _results;
- if (document.querySelectorAll) {
- dropzones = document.querySelectorAll(".dropzone");
- } else {
- dropzones = [];
- checkElements = function(elements) {
- var el, _i, _len, _results;
- _results = [];
- for (_i = 0, _len = elements.length; _i < _len; _i++) {
- el = elements[_i];
if (/(^| )dropzone($| )/.test(el.className)) {
- _results.push(dropzones.push(el));
+ result.push(dropzones.push(el));
} else {
- _results.push(void 0);
+ result.push(undefined);
}
}
- return _results;
- };
- checkElements(document.getElementsByTagName("div"));
- checkElements(document.getElementsByTagName("form"));
- }
- _results = [];
- for (_i = 0, _len = dropzones.length; _i < _len; _i++) {
- dropzone = dropzones[_i];
- if (Dropzone.optionsForElement(dropzone) !== false) {
- _results.push(new Dropzone(dropzone));
+ return result;
+ }();
+ };
+ checkElements(document.getElementsByTagName("div"));
+ checkElements(document.getElementsByTagName("form"));
+ }
+
+ return function () {
+ var result = [];
+ for (var _iterator34 = dropzones, _isArray34 = true, _i36 = 0, _iterator34 = _isArray34 ? _iterator34 : _iterator34[Symbol.iterator]();;) {
+ var _ref33;
+
+ if (_isArray34) {
+ if (_i36 >= _iterator34.length) break;
+ _ref33 = _iterator34[_i36++];
} else {
- _results.push(void 0);
+ _i36 = _iterator34.next();
+ if (_i36.done) break;
+ _ref33 = _i36.value;
}
- }
- return _results;
- };
- Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i];
+ var dropzone = _ref33;
- Dropzone.isBrowserSupported = function() {
- var capableBrowser, regex, _i, _len, _ref;
- capableBrowser = true;
- if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) {
- if (!("classList" in document.createElement("a"))) {
- capableBrowser = false;
+ // Create a dropzone unless auto discover has been disabled for specific element
+ if (Dropzone.optionsForElement(dropzone) !== false) {
+ result.push(new Dropzone(dropzone));
} else {
- _ref = Dropzone.blacklistedBrowsers;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- regex = _ref[_i];
- if (regex.test(navigator.userAgent)) {
- capableBrowser = false;
- continue;
- }
- }
+ result.push(undefined);
}
- } else {
- capableBrowser = false;
}
- return capableBrowser;
- };
+ return result;
+ }();
+};
+
+// Since the whole Drag'n'Drop API is pretty new, some browsers implement it,
+// but not correctly.
+// So I created a blacklist of userAgents. Yes, yes. Browser sniffing, I know.
+// But what to do when browsers *theoretically* support an API, but crash
+// when using it.
+//
+// This is a list of regular expressions tested against navigator.userAgent
+//
+// ** It should only be used on browser that *do* support the API, but
+// incorrectly **
+//
+Dropzone.blacklistedBrowsers = [
+// The mac os and windows phone version of opera 12 seems to have a problem with the File drag'n'drop API.
+/opera.*(Macintosh|Windows Phone).*version\/12/i];
+
+// Checks if the browser is supported
+Dropzone.isBrowserSupported = function () {
+ var capableBrowser = true;
+
+ if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) {
+ if (!("classList" in document.createElement("a"))) {
+ capableBrowser = false;
+ } else {
+ // The browser supports the API, but may be blacklisted.
+ for (var _iterator35 = Dropzone.blacklistedBrowsers, _isArray35 = true, _i37 = 0, _iterator35 = _isArray35 ? _iterator35 : _iterator35[Symbol.iterator]();;) {
+ var _ref34;
+
+ if (_isArray35) {
+ if (_i37 >= _iterator35.length) break;
+ _ref34 = _iterator35[_i37++];
+ } else {
+ _i37 = _iterator35.next();
+ if (_i37.done) break;
+ _ref34 = _i37.value;
+ }
+
+ var regex = _ref34;
- without = function(list, rejectedItem) {
- var item, _i, _len, _results;
- _results = [];
- for (_i = 0, _len = list.length; _i < _len; _i++) {
- item = list[_i];
- if (item !== rejectedItem) {
- _results.push(item);
+ if (regex.test(navigator.userAgent)) {
+ capableBrowser = false;
+ continue;
+ }
}
}
- return _results;
- };
+ } else {
+ capableBrowser = false;
+ }
- camelize = function(str) {
- return str.replace(/[\-_](\w)/g, function(match) {
- return match.charAt(1).toUpperCase();
- });
- };
+ return capableBrowser;
+};
- Dropzone.createElement = function(string) {
- var div;
- div = document.createElement("div");
- div.innerHTML = string;
- return div.childNodes[0];
- };
+Dropzone.dataURItoBlob = function (dataURI) {
+ // convert base64 to raw binary data held in a string
+ // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
+ var byteString = atob(dataURI.split(',')[1]);
+
+ // separate out the mime component
+ var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
+
+ // write the bytes of the string to an ArrayBuffer
+ var ab = new ArrayBuffer(byteString.length);
+ var ia = new Uint8Array(ab);
+ for (var i = 0, end = byteString.length, asc = 0 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) {
+ ia[i] = byteString.charCodeAt(i);
+ }
- Dropzone.elementInside = function(element, container) {
+ // write the ArrayBuffer to a blob
+ return new Blob([ab], { type: mimeString });
+};
+
+// Returns an array without the rejected item
+var without = function without(list, rejectedItem) {
+ return list.filter(function (item) {
+ return item !== rejectedItem;
+ }).map(function (item) {
+ return item;
+ });
+};
+
+// abc-def_ghi -> abcDefGhi
+var camelize = function camelize(str) {
+ return str.replace(/[\-_](\w)/g, function (match) {
+ return match.charAt(1).toUpperCase();
+ });
+};
+
+// Creates an element from string
+Dropzone.createElement = function (string) {
+ var div = document.createElement("div");
+ div.innerHTML = string;
+ return div.childNodes[0];
+};
+
+// Tests if given element is inside (or simply is) the container
+Dropzone.elementInside = function (element, container) {
+ if (element === container) {
+ return true;
+ } // Coffeescript doesn't support do/while loops
+ while (element = element.parentNode) {
if (element === container) {
return true;
}
- while (element = element.parentNode) {
- if (element === container) {
- return true;
+ }
+ return false;
+};
+
+Dropzone.getElement = function (el, name) {
+ var element = void 0;
+ if (typeof el === "string") {
+ element = document.querySelector(el);
+ } else if (el.nodeType != null) {
+ element = el;
+ }
+ if (element == null) {
+ throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element.");
+ }
+ return element;
+};
+
+Dropzone.getElements = function (els, name) {
+ var el = void 0,
+ elements = void 0;
+ if (els instanceof Array) {
+ elements = [];
+ try {
+ for (var _iterator36 = els, _isArray36 = true, _i38 = 0, _iterator36 = _isArray36 ? _iterator36 : _iterator36[Symbol.iterator]();;) {
+ if (_isArray36) {
+ if (_i38 >= _iterator36.length) break;
+ el = _iterator36[_i38++];
+ } else {
+ _i38 = _iterator36.next();
+ if (_i38.done) break;
+ el = _i38.value;
+ }
+
+ elements.push(this.getElement(el, name));
}
+ } catch (e) {
+ elements = null;
}
- return false;
- };
+ } else if (typeof els === "string") {
+ elements = [];
+ for (var _iterator37 = document.querySelectorAll(els), _isArray37 = true, _i39 = 0, _iterator37 = _isArray37 ? _iterator37 : _iterator37[Symbol.iterator]();;) {
+ if (_isArray37) {
+ if (_i39 >= _iterator37.length) break;
+ el = _iterator37[_i39++];
+ } else {
+ _i39 = _iterator37.next();
+ if (_i39.done) break;
+ el = _i39.value;
+ }
- Dropzone.getElement = function(el, name) {
- var element;
- if (typeof el === "string") {
- element = document.querySelector(el);
- } else if (el.nodeType != null) {
- element = el;
+ elements.push(el);
}
- if (element == null) {
- throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element.");
+ } else if (els.nodeType != null) {
+ elements = [els];
+ }
+
+ if (elements == null || !elements.length) {
+ throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");
+ }
+
+ return elements;
+};
+
+// Asks the user the question and calls accepted or rejected accordingly
+//
+// The default implementation just uses `window.confirm` and then calls the
+// appropriate callback.
+Dropzone.confirm = function (question, accepted, rejected) {
+ if (window.confirm(question)) {
+ return accepted();
+ } else if (rejected != null) {
+ return rejected();
+ }
+};
+
+// Validates the mime type like this:
+//
+// https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
+Dropzone.isValidFile = function (file, acceptedFiles) {
+ if (!acceptedFiles) {
+ return true;
+ } // If there are no accepted mime types, it's OK
+ acceptedFiles = acceptedFiles.split(",");
+
+ var mimeType = file.type;
+ var baseMimeType = mimeType.replace(/\/.*$/, "");
+
+ for (var _iterator38 = acceptedFiles, _isArray38 = true, _i40 = 0, _iterator38 = _isArray38 ? _iterator38 : _iterator38[Symbol.iterator]();;) {
+ var _ref35;
+
+ if (_isArray38) {
+ if (_i40 >= _iterator38.length) break;
+ _ref35 = _iterator38[_i40++];
+ } else {
+ _i40 = _iterator38.next();
+ if (_i40.done) break;
+ _ref35 = _i40.value;
}
- return element;
- };
- Dropzone.getElements = function(els, name) {
- var e, el, elements, _i, _j, _len, _len1, _ref;
- if (els instanceof Array) {
- elements = [];
- try {
- for (_i = 0, _len = els.length; _i < _len; _i++) {
- el = els[_i];
- elements.push(this.getElement(el, name));
- }
- } catch (_error) {
- e = _error;
- elements = null;
+ var validType = _ref35;
+
+ validType = validType.trim();
+ if (validType.charAt(0) === ".") {
+ if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) {
+ return true;
}
- } else if (typeof els === "string") {
- elements = [];
- _ref = document.querySelectorAll(els);
- for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
- el = _ref[_j];
- elements.push(el);
+ } else if (/\/\*$/.test(validType)) {
+ // This is something like a image/* mime type
+ if (baseMimeType === validType.replace(/\/.*$/, "")) {
+ return true;
+ }
+ } else {
+ if (mimeType === validType) {
+ return true;
}
- } else if (els.nodeType != null) {
- elements = [els];
- }
- if (!((elements != null) && elements.length)) {
- throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");
}
- return elements;
- };
+ }
- Dropzone.confirm = function(question, accepted, rejected) {
- if (window.confirm(question)) {
- return accepted();
- } else if (rejected != null) {
- return rejected();
- }
- };
+ return false;
+};
- Dropzone.isValidFile = function(file, acceptedFiles) {
- var baseMimeType, mimeType, validType, _i, _len;
- if (!acceptedFiles) {
- return true;
- }
- acceptedFiles = acceptedFiles.split(",");
- mimeType = file.type;
- baseMimeType = mimeType.replace(/\/.*$/, "");
- for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) {
- validType = acceptedFiles[_i];
- validType = validType.trim();
- if (validType.charAt(0) === ".") {
- if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) {
- return true;
- }
- } else if (/\/\*$/.test(validType)) {
- if (baseMimeType === validType.replace(/\/.*$/, "")) {
- return true;
- }
- } else {
- if (mimeType === validType) {
- return true;
- }
- }
- }
- return false;
+// Augment jQuery
+if (typeof jQuery !== 'undefined' && jQuery !== null) {
+ jQuery.fn.dropzone = function (options) {
+ return this.each(function () {
+ return new Dropzone(this, options);
+ });
};
+}
- if (typeof jQuery !== "undefined" && jQuery !== null) {
- jQuery.fn.dropzone = function(options) {
- return this.each(function() {
- return new Dropzone(this, options);
- });
- };
- }
+if (typeof module !== 'undefined' && module !== null) {
+ module.exports = Dropzone;
+} else {
+ window.Dropzone = Dropzone;
+}
- if (typeof module !== "undefined" && module !== null) {
- module.exports = Dropzone;
- } else {
- window.Dropzone = Dropzone;
- }
+// Dropzone file status codes
+Dropzone.ADDED = "added";
- Dropzone.ADDED = "added";
+Dropzone.QUEUED = "queued";
+// For backwards compatibility. Now, if a file is accepted, it's either queued
+// or uploading.
+Dropzone.ACCEPTED = Dropzone.QUEUED;
- Dropzone.QUEUED = "queued";
+Dropzone.UPLOADING = "uploading";
+Dropzone.PROCESSING = Dropzone.UPLOADING; // alias
- Dropzone.ACCEPTED = Dropzone.QUEUED;
+Dropzone.CANCELED = "canceled";
+Dropzone.ERROR = "error";
+Dropzone.SUCCESS = "success";
- Dropzone.UPLOADING = "uploading";
+/*
- Dropzone.PROCESSING = Dropzone.UPLOADING;
+ Bugfix for iOS 6 and 7
+ Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios
+ based on the work of https://github.com/stomita/ios-imagefile-megapixel
- Dropzone.CANCELED = "canceled";
+ */
- Dropzone.ERROR = "error";
+// Detecting vertical squash in loaded image.
+// Fixes a bug which squash image vertically while drawing into canvas for some images.
+// This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel
+var detectVerticalSquash = function detectVerticalSquash(img) {
+ var iw = img.naturalWidth;
+ var ih = img.naturalHeight;
+ var canvas = document.createElement("canvas");
+ canvas.width = 1;
+ canvas.height = ih;
+ var ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0);
- Dropzone.SUCCESS = "success";
+ var _ctx$getImageData = ctx.getImageData(1, 0, 1, ih),
+ data = _ctx$getImageData.data;
+ // search image edge pixel position in case it is squashed vertically.
- /*
-
- Bugfix for iOS 6 and 7
- Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios
- based on the work of https://github.com/stomita/ios-imagefile-megapixel
- */
- detectVerticalSquash = function(img) {
- var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy;
- iw = img.naturalWidth;
- ih = img.naturalHeight;
- canvas = document.createElement("canvas");
- canvas.width = 1;
- canvas.height = ih;
- ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0);
- data = ctx.getImageData(0, 0, 1, ih).data;
- sy = 0;
- ey = ih;
- py = ih;
- while (py > sy) {
- alpha = data[(py - 1) * 4 + 3];
- if (alpha === 0) {
- ey = py;
- } else {
- sy = py;
- }
- py = (ey + sy) >> 1;
- }
- ratio = py / ih;
- if (ratio === 0) {
- return 1;
+ var sy = 0;
+ var ey = ih;
+ var py = ih;
+ while (py > sy) {
+ var alpha = data[(py - 1) * 4 + 3];
+
+ if (alpha === 0) {
+ ey = py;
} else {
- return ratio;
+ sy = py;
}
- };
- drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
- var vertSquashRatio;
- vertSquashRatio = detectVerticalSquash(img);
- return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
- };
+ py = ey + sy >> 1;
+ }
+ var ratio = py / ih;
+ if (ratio === 0) {
+ return 1;
+ } else {
+ return ratio;
+ }
+};
+
+// A replacement for context.drawImage
+// (args are for source and destination).
+var drawImageIOSFix = function drawImageIOSFix(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
+ var vertSquashRatio = detectVerticalSquash(img);
+ return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
+};
+
+// Based on MinifyJpeg
+// Source: http://www.perry.cz/files/ExifRestorer.js
+// http://elicon.blog57.fc2.com/blog-entry-206.html
+
+var ExifRestore = function () {
+ function ExifRestore() {
+ _classCallCheck(this, ExifRestore);
+ }
- /*
- * contentloaded.js
- *
- * Author: Diego Perini (diego.perini at gmail.com)
- * Summary: cross-browser wrapper for DOMContentLoaded
- * Updated: 20101020
- * License: MIT
- * Version: 1.2
- *
- * URL:
- * http://javascript.nwbox.com/ContentLoaded/
- * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
- */
-
- contentLoaded = function(win, fn) {
- var add, doc, done, init, poll, pre, rem, root, top;
- done = false;
- top = true;
- doc = win.document;
- root = doc.documentElement;
- add = (doc.addEventListener ? "addEventListener" : "attachEvent");
- rem = (doc.addEventListener ? "removeEventListener" : "detachEvent");
- pre = (doc.addEventListener ? "" : "on");
- init = function(e) {
- if (e.type === "readystatechange" && doc.readyState !== "complete") {
- return;
+ _createClass(ExifRestore, null, [{
+ key: "initClass",
+ value: function initClass() {
+ this.KEY_STR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
+ }
+ }, {
+ key: "encode64",
+ value: function encode64(input) {
+ var output = '';
+ var chr1 = undefined;
+ var chr2 = undefined;
+ var chr3 = '';
+ var enc1 = undefined;
+ var enc2 = undefined;
+ var enc3 = undefined;
+ var enc4 = '';
+ var i = 0;
+ while (true) {
+ chr1 = input[i++];
+ chr2 = input[i++];
+ chr3 = input[i++];
+ enc1 = chr1 >> 2;
+ enc2 = (chr1 & 3) << 4 | chr2 >> 4;
+ enc3 = (chr2 & 15) << 2 | chr3 >> 6;
+ enc4 = chr3 & 63;
+ if (isNaN(chr2)) {
+ enc3 = enc4 = 64;
+ } else if (isNaN(chr3)) {
+ enc4 = 64;
+ }
+ output = output + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4);
+ chr1 = chr2 = chr3 = '';
+ enc1 = enc2 = enc3 = enc4 = '';
+ if (!(i < input.length)) {
+ break;
+ }
}
- (e.type === "load" ? win : doc)[rem](pre + e.type, init, false);
- if (!done && (done = true)) {
- return fn.call(win, e.type || e);
+ return output;
+ }
+ }, {
+ key: "restore",
+ value: function restore(origFileBase64, resizedFileBase64) {
+ if (!origFileBase64.match('data:image/jpeg;base64,')) {
+ return resizedFileBase64;
+ }
+ var rawImage = this.decode64(origFileBase64.replace('data:image/jpeg;base64,', ''));
+ var segments = this.slice2Segments(rawImage);
+ var image = this.exifManipulation(resizedFileBase64, segments);
+ return "data:image/jpeg;base64," + this.encode64(image);
+ }
+ }, {
+ key: "exifManipulation",
+ value: function exifManipulation(resizedFileBase64, segments) {
+ var exifArray = this.getExifArray(segments);
+ var newImageArray = this.insertExif(resizedFileBase64, exifArray);
+ var aBuffer = new Uint8Array(newImageArray);
+ return aBuffer;
+ }
+ }, {
+ key: "getExifArray",
+ value: function getExifArray(segments) {
+ var seg = undefined;
+ var x = 0;
+ while (x < segments.length) {
+ seg = segments[x];
+ if (seg[0] === 255 & seg[1] === 225) {
+ return seg;
+ }
+ x++;
}
- };
- poll = function() {
- var e;
- try {
- root.doScroll("left");
- } catch (_error) {
- e = _error;
- setTimeout(poll, 50);
- return;
+ return [];
+ }
+ }, {
+ key: "insertExif",
+ value: function insertExif(resizedFileBase64, exifArray) {
+ var imageData = resizedFileBase64.replace('data:image/jpeg;base64,', '');
+ var buf = this.decode64(imageData);
+ var separatePoint = buf.indexOf(255, 3);
+ var mae = buf.slice(0, separatePoint);
+ var ato = buf.slice(separatePoint);
+ var array = mae;
+ array = array.concat(exifArray);
+ array = array.concat(ato);
+ return array;
+ }
+ }, {
+ key: "slice2Segments",
+ value: function slice2Segments(rawImageArray) {
+ var head = 0;
+ var segments = [];
+ while (true) {
+ var length;
+ if (rawImageArray[head] === 255 & rawImageArray[head + 1] === 218) {
+ break;
+ }
+ if (rawImageArray[head] === 255 & rawImageArray[head + 1] === 216) {
+ head += 2;
+ } else {
+ length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3];
+ var endPoint = head + length + 2;
+ var seg = rawImageArray.slice(head, endPoint);
+ segments.push(seg);
+ head = endPoint;
+ }
+ if (head > rawImageArray.length) {
+ break;
+ }
}
- return init("poll");
- };
- if (doc.readyState !== "complete") {
- if (doc.createEventObject && root.doScroll) {
- try {
- top = !win.frameElement;
- } catch (_error) {}
- if (top) {
- poll();
+ return segments;
+ }
+ }, {
+ key: "decode64",
+ value: function decode64(input) {
+ var output = '';
+ var chr1 = undefined;
+ var chr2 = undefined;
+ var chr3 = '';
+ var enc1 = undefined;
+ var enc2 = undefined;
+ var enc3 = undefined;
+ var enc4 = '';
+ var i = 0;
+ var buf = [];
+ // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
+ var base64test = /[^A-Za-z0-9\+\/\=]/g;
+ if (base64test.exec(input)) {
+ console.warn('There were invalid base64 characters in the input text.\nValid base64 characters are A-Z, a-z, 0-9, \'+\', \'/\',and \'=\'\nExpect errors in decoding.');
+ }
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
+ while (true) {
+ enc1 = this.KEY_STR.indexOf(input.charAt(i++));
+ enc2 = this.KEY_STR.indexOf(input.charAt(i++));
+ enc3 = this.KEY_STR.indexOf(input.charAt(i++));
+ enc4 = this.KEY_STR.indexOf(input.charAt(i++));
+ chr1 = enc1 << 2 | enc2 >> 4;
+ chr2 = (enc2 & 15) << 4 | enc3 >> 2;
+ chr3 = (enc3 & 3) << 6 | enc4;
+ buf.push(chr1);
+ if (enc3 !== 64) {
+ buf.push(chr2);
+ }
+ if (enc4 !== 64) {
+ buf.push(chr3);
+ }
+ chr1 = chr2 = chr3 = '';
+ enc1 = enc2 = enc3 = enc4 = '';
+ if (!(i < input.length)) {
+ break;
}
}
- doc[add](pre + "DOMContentLoaded", init, false);
- doc[add](pre + "readystatechange", init, false);
- return win[add](pre + "load", init, false);
+ return buf;
+ }
+ }]);
+
+ return ExifRestore;
+}();
+
+ExifRestore.initClass();
+
+/*
+ * contentloaded.js
+ *
+ * Author: Diego Perini (diego.perini at gmail.com)
+ * Summary: cross-browser wrapper for DOMContentLoaded
+ * Updated: 20101020
+ * License: MIT
+ * Version: 1.2
+ *
+ * URL:
+ * http://javascript.nwbox.com/ContentLoaded/
+ * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
+ */
+
+// @win window reference
+// @fn function reference
+var contentLoaded = function contentLoaded(win, fn) {
+ var done = false;
+ var top = true;
+ var doc = win.document;
+ var root = doc.documentElement;
+ var add = doc.addEventListener ? "addEventListener" : "attachEvent";
+ var rem = doc.addEventListener ? "removeEventListener" : "detachEvent";
+ var pre = doc.addEventListener ? "" : "on";
+ var init = function init(e) {
+ if (e.type === "readystatechange" && doc.readyState !== "complete") {
+ return;
+ }
+ (e.type === "load" ? win : doc)[rem](pre + e.type, init, false);
+ if (!done && (done = true)) {
+ return fn.call(win, e.type || e);
}
};
- Dropzone._autoDiscoverFunction = function() {
- if (Dropzone.autoDiscover) {
- return Dropzone.discover();
+ var poll = function poll() {
+ try {
+ root.doScroll("left");
+ } catch (e) {
+ setTimeout(poll, 50);
+ return;
}
+ return init("poll");
};
- contentLoaded(window, Dropzone._autoDiscoverFunction);
+ if (doc.readyState !== "complete") {
+ if (doc.createEventObject && root.doScroll) {
+ try {
+ top = !win.frameElement;
+ } catch (error) {}
+ if (top) {
+ poll();
+ }
+ }
+ doc[add](pre + "DOMContentLoaded", init, false);
+ doc[add](pre + "readystatechange", init, false);
+ return win[add](pre + "load", init, false);
+ }
+};
-}).call(this);
+// As a single function to be able to write tests.
+Dropzone._autoDiscoverFunction = function () {
+ if (Dropzone.autoDiscover) {
+ return Dropzone.discover();
+ }
+};
+contentLoaded(window, Dropzone._autoDiscoverFunction);
+
+function __guard__(value, transform) {
+ return typeof value !== 'undefined' && value !== null ? transform(value) : undefined;
+}
+function __guardMethod__(obj, methodName, transform) {
+ if (typeof obj !== 'undefined' && obj !== null && typeof obj[methodName] === 'function') {
+ return transform(obj, methodName);
+ } else {
+ return undefined;
+ }
+}
diff --git a/Resources/public/js/vendor/galleria/galleria-1.4.5.min.js b/Resources/public/js/vendor/galleria/galleria-1.4.5.min.js
deleted file mode 100644
index 3248f8ef..00000000
--- a/Resources/public/js/vendor/galleria/galleria-1.4.5.min.js
+++ /dev/null
@@ -1,3 +0,0 @@
-(function($,window,Galleria,undef){var doc=window.document,$doc=$(doc),$win=$(window),protoArray=Array.prototype,VERSION=1.45,DEBUG=true,TIMEOUT=3e4,DUMMY=false,NAV=navigator.userAgent.toLowerCase(),HASH=window.location.hash.replace(/#\//,""),PROT=window.location.protocol=="file:"?"http:":window.location.protocol,M=Math,F=function(){},FALSE=function(){return false},IE=function(){var v=3,div=doc.createElement("div"),all=div.getElementsByTagName("i");do{div.innerHTML=""}while(all[0]);return v>4?v:doc.documentMode||undef}(),DOM=function(){return{html:doc.documentElement,body:doc.body,head:doc.getElementsByTagName("head")[0],title:doc.title}},IFRAME=window.parent!==window.self,_eventlist="data ready thumbnail loadstart loadfinish image play pause progress "+"fullscreen_enter fullscreen_exit idle_enter idle_exit rescale "+"lightbox_open lightbox_close lightbox_image",_events=function(){var evs=[];$.each(_eventlist.split(" "),function(i,ev){evs.push(ev);if(/_/.test(ev)){evs.push(ev.replace(/_/g,""))}});return evs}(),_legacyOptions=function(options){var n;if(typeof options!=="object"){return options}$.each(options,function(key,value){if(/^[a-z]+_/.test(key)){n="";$.each(key.split("_"),function(i,k){n+=i>0?k.substr(0,1).toUpperCase()+k.substr(1):k});options[n]=value;delete options[key]}});return options},_patchEvent=function(type){if($.inArray(type,_events)>-1){return Galleria[type.toUpperCase()]}return type},_video={youtube:{reg:/https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i,embed:function(){return PROT+"//www.youtube.com/embed/"+this.id},get_thumb:function(data){return PROT+"//img.youtube.com/vi/"+this.id+"/default.jpg"},get_image:function(data){return PROT+"//img.youtube.com/vi/"+this.id+"/hqdefault.jpg"}},vimeo:{reg:/https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i,embed:function(){return PROT+"//player.vimeo.com/video/"+this.id},getUrl:function(){return PROT+"//vimeo.com/api/v2/video/"+this.id+".json?callback=?"},get_thumb:function(data){return data[0].thumbnail_medium},get_image:function(data){return data[0].thumbnail_large}},dailymotion:{reg:/https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/,embed:function(){return PROT+"//www.dailymotion.com/embed/video/"+this.id},getUrl:function(){return"https://api.dailymotion.com/video/"+this.id+"?fields=thumbnail_240_url,thumbnail_720_url&callback=?"},get_thumb:function(data){return data.thumbnail_240_url},get_image:function(data){return data.thumbnail_720_url}},_inst:[]},Video=function(type,id){for(var i=0;i<_video._inst.length;i++){if(_video._inst[i].id===id&&_video._inst[i].type==type){return _video._inst[i]}}this.type=type;this.id=id;this.readys=[];_video._inst.push(this);var self=this;$.extend(this,_video[type]);_videoThumbs=function(data){self.data=data;$.each(self.readys,function(i,fn){fn(self.data)});self.readys=[]};if(this.hasOwnProperty("getUrl")){$.getJSON(this.getUrl(),_videoThumbs)}else{window.setTimeout(_videoThumbs,400)}this.getMedia=function(type,callback,fail){fail=fail||F;var self=this;var success=function(data){callback(self["get_"+type](data))};try{if(self.data){success(self.data)}else{self.readys.push(success)}}catch(e){fail()}}},_videoTest=function(url){var match;for(var v in _video){match=url&&_video[v].reg&&url.match(_video[v].reg);if(match&&match.length){return{id:match[2],provider:v}}}return false},_nativeFullscreen={support:function(){var html=DOM().html;return!IFRAME&&(html.requestFullscreen||html.msRequestFullscreen||html.mozRequestFullScreen||html.webkitRequestFullScreen)}(),callback:F,enter:function(instance,callback,elem){this.instance=instance;this.callback=callback||F;elem=elem||DOM().html;if(elem.requestFullscreen){elem.requestFullscreen()}else if(elem.msRequestFullscreen){elem.msRequestFullscreen()}else if(elem.mozRequestFullScreen){elem.mozRequestFullScreen()}else if(elem.webkitRequestFullScreen){elem.webkitRequestFullScreen()}},exit:function(callback){this.callback=callback||F;if(doc.exitFullscreen){doc.exitFullscreen()}else if(doc.msExitFullscreen){doc.msExitFullscreen()}else if(doc.mozCancelFullScreen){doc.mozCancelFullScreen()}else if(doc.webkitCancelFullScreen){doc.webkitCancelFullScreen()}},instance:null,listen:function(){if(!this.support){return}var handler=function(){if(!_nativeFullscreen.instance){return}var fs=_nativeFullscreen.instance._fullscreen;if(doc.fullscreen||doc.mozFullScreen||doc.webkitIsFullScreen||doc.msFullscreenElement&&doc.msFullscreenElement!==null){fs._enter(_nativeFullscreen.callback)}else{fs._exit(_nativeFullscreen.callback)}};doc.addEventListener("fullscreenchange",handler,false);doc.addEventListener("MSFullscreenChange",handler,false);doc.addEventListener("mozfullscreenchange",handler,false);doc.addEventListener("webkitfullscreenchange",handler,false)}},_galleries=[],_instances=[],_hasError=false,_canvas=false,_pool=[],_loadedThemes=[],_themeLoad=function(theme){_loadedThemes.push(theme);$.each(_pool,function(i,instance){if(instance._options.theme==theme.name||!instance._initialized&&!instance._options.theme){instance.theme=theme;instance._init.call(instance)}})},Utils=function(){return{clearTimer:function(id){$.each(Galleria.get(),function(){this.clearTimer(id)})},addTimer:function(id){$.each(Galleria.get(),function(){this.addTimer(id)})},array:function(obj){return protoArray.slice.call(obj,0)},create:function(className,nodeName){nodeName=nodeName||"div";var elem=doc.createElement(nodeName);elem.className=className;return elem},removeFromArray:function(arr,elem){$.each(arr,function(i,el){if(el==elem){arr.splice(i,1);return false}});return arr},getScriptPath:function(src){src=src||$("script:last").attr("src");var slices=src.split("/");if(slices.length==1){return""}slices.pop();return slices.join("/")+"/"},animate:function(){var transition=function(style){var props="transition WebkitTransition MozTransition OTransition".split(" "),i;if(window.opera){return false}for(i=0;props[i];i++){if(typeof style[props[i]]!=="undefined"){return props[i]}}return false}((doc.body||doc.documentElement).style);var endEvent={MozTransition:"transitionend",OTransition:"oTransitionEnd",WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[transition];var easings={_default:[.25,.1,.25,1],galleria:[.645,.045,.355,1],galleriaIn:[.55,.085,.68,.53],galleriaOut:[.25,.46,.45,.94],ease:[.25,0,.25,1],linear:[.25,.25,.75,.75],"ease-in":[.42,0,1,1],"ease-out":[0,0,.58,1],"ease-in-out":[.42,0,.58,1]};var setStyle=function(elem,value,suffix){var css={};suffix=suffix||"transition";$.each("webkit moz ms o".split(" "),function(){css["-"+this+"-"+suffix]=value});elem.css(css)};var clearStyle=function(elem){setStyle(elem,"none","transition");if(Galleria.WEBKIT&&Galleria.TOUCH){setStyle(elem,"translate3d(0,0,0)","transform");if(elem.data("revert")){elem.css(elem.data("revert"));elem.data("revert",null)}}};var change,strings,easing,syntax,revert,form,css;return function(elem,to,options){options=$.extend({duration:400,complete:F,stop:false},options);elem=$(elem);if(!options.duration){elem.css(to);options.complete.call(elem[0]);return}if(!transition){elem.animate(to,options);return}if(options.stop){elem.off(endEvent);clearStyle(elem)}change=false;$.each(to,function(key,val){css=elem.css(key);if(Utils.parseValue(css)!=Utils.parseValue(val)){change=true}elem.css(key,css)});if(!change){window.setTimeout(function(){options.complete.call(elem[0])},options.duration);return}strings=[];easing=options.easing in easings?easings[options.easing]:easings._default;syntax=" "+options.duration+"ms"+" cubic-bezier("+easing.join(",")+")";window.setTimeout(function(elem,endEvent,to,syntax){return function(){elem.one(endEvent,function(elem){return function(){clearStyle(elem);options.complete.call(elem[0])}}(elem));if(Galleria.WEBKIT&&Galleria.TOUCH){revert={};form=[0,0,0];$.each(["left","top"],function(i,m){if(m in to){form[i]=Utils.parseValue(to[m])-Utils.parseValue(elem.css(m))+"px";revert[m]=to[m];delete to[m]}});if(form[0]||form[1]){elem.data("revert",revert);strings.push("-webkit-transform"+syntax);setStyle(elem,"translate3d("+form.join(",")+")","transform")}}$.each(to,function(p,val){strings.push(p+syntax)});setStyle(elem,strings.join(","));elem.css(to)}}(elem,endEvent,to,syntax),2)}}(),removeAlpha:function(elem){if(elem instanceof jQuery){elem=elem[0]}if(IE<9&&elem){var style=elem.style,currentStyle=elem.currentStyle,filter=currentStyle&¤tStyle.filter||style.filter||"";if(/alpha/.test(filter)){style.filter=filter.replace(/alpha\([^)]*\)/i,"")}}},forceStyles:function(elem,styles){elem=$(elem);if(elem.attr("style")){elem.data("styles",elem.attr("style")).removeAttr("style")}elem.css(styles)},revertStyles:function(){$.each(Utils.array(arguments),function(i,elem){elem=$(elem);elem.removeAttr("style");elem.attr("style","");if(elem.data("styles")){elem.attr("style",elem.data("styles")).data("styles",null)}})},moveOut:function(elem){Utils.forceStyles(elem,{position:"absolute",left:-1e4})},moveIn:function(){Utils.revertStyles.apply(Utils,Utils.array(arguments))},hide:function(elem,speed,callback){callback=callback||F;var $elem=$(elem);elem=$elem[0];if(!$elem.data("opacity")){$elem.data("opacity",$elem.css("opacity"))}var style={opacity:0};if(speed){var complete=IE<9&&elem?function(){Utils.removeAlpha(elem);elem.style.visibility="hidden";callback.call(elem)}:callback;Utils.animate(elem,style,{duration:speed,complete:complete,stop:true})}else{if(IE<9&&elem){Utils.removeAlpha(elem);elem.style.visibility="hidden"}else{$elem.css(style)}}},show:function(elem,speed,callback){callback=callback||F;var $elem=$(elem);elem=$elem[0];var saved=parseFloat($elem.data("opacity"))||1,style={opacity:saved};if(speed){if(IE<9){$elem.css("opacity",0);elem.style.visibility="visible"}var complete=IE<9&&elem?function(){if(style.opacity==1){Utils.removeAlpha(elem)}callback.call(elem)}:callback;Utils.animate(elem,style,{duration:speed,complete:complete,stop:true})}else{if(IE<9&&style.opacity==1&&elem){Utils.removeAlpha(elem);elem.style.visibility="visible"}else{$elem.css(style)}}},wait:function(options){Galleria._waiters=Galleria._waiters||[];options=$.extend({until:FALSE,success:F,error:function(){Galleria.raise("Could not complete wait function.")},timeout:3e3},options);var start=Utils.timestamp(),elapsed,now,tid,fn=function(){now=Utils.timestamp();elapsed=now-start;Utils.removeFromArray(Galleria._waiters,tid);if(options.until(elapsed)){options.success();return false}if(typeof options.timeout=="number"&&now>=start+options.timeout){options.error();return false}Galleria._waiters.push(tid=window.setTimeout(fn,10))};Galleria._waiters.push(tid=window.setTimeout(fn,10))},toggleQuality:function(img,force){if(IE!==7&&IE!==8||!img||img.nodeName.toUpperCase()!="IMG"){return}if(typeof force==="undefined"){force=img.style.msInterpolationMode==="nearest-neighbor"}img.style.msInterpolationMode=force?"bicubic":"nearest-neighbor"},insertStyleTag:function(styles,id){if(id&&$("#"+id).length){return}var style=doc.createElement("style");if(id){style.id=id}DOM().head.appendChild(style);if(style.styleSheet){style.styleSheet.cssText=styles}else{var cssText=doc.createTextNode(styles);style.appendChild(cssText)}},loadScript:function(url,callback){var done=false,script=$("").attr({src:url,async:true}).get(0);script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){done=true;script.onload=script.onreadystatechange=null;if(typeof callback==="function"){callback.call(this,this)}}};DOM().head.appendChild(script)},parseValue:function(val){if(typeof val==="number"){return val}else if(typeof val==="string"){var arr=val.match(/\-?\d|\./g);return arr&&arr.constructor===Array?arr.join("")*1:0}else{return 0}},timestamp:function(){return(new Date).getTime()},loadCSS:function(href,id,callback){var link,length;$("link[rel=stylesheet]").each(function(){if(new RegExp(href).test(this.href)){link=this;return false}});if(typeof id==="function"){callback=id;id=undef}callback=callback||F;if(link){callback.call(link,link);return link}length=doc.styleSheets.length;if($("#"+id).length){$("#"+id).attr("href",href);length--}else{link=$(" ").attr({rel:"stylesheet",href:href,id:id}).get(0);var styles=$('link[rel="stylesheet"], style');if(styles.length){styles.get(0).parentNode.insertBefore(link,styles[0])}else{DOM().head.appendChild(link)}if(IE&&length>=31){Galleria.raise("You have reached the browser stylesheet limit (31)",true);return}}if(typeof callback==="function"){var $loader=$("").attr("id","galleria-loader").hide().appendTo(DOM().body);Utils.wait({until:function(){return $loader.height()==1},success:function(){$loader.remove();callback.call(link,link)},error:function(){$loader.remove();Galleria.raise("Theme CSS could not load after 20 sec. "+(Galleria.QUIRK?"Your browser is in Quirks Mode, please add a correct doctype.":"Please download the latest theme at http://galleria.io/customer/."),true)},timeout:5e3})}return link}}}(),_playIcon=function(container){var css=".galleria-videoicon{width:60px;height:60px;position:absolute;top:50%;left:50%;z-index:1;"+"margin:-30px 0 0 -30px;cursor:pointer;background:#000;background:rgba(0,0,0,.8);border-radius:3px;-webkit-transition:all 150ms}"+".galleria-videoicon i{width:0px;height:0px;border-style:solid;border-width:10px 0 10px 16px;display:block;"+"border-color:transparent transparent transparent #ffffff;margin:20px 0 0 22px}.galleria-image:hover .galleria-videoicon{background:#000}";Utils.insertStyleTag(css,"galleria-videoicon");return $(Utils.create("galleria-videoicon")).html(" ").appendTo(container).click(function(){$(this).siblings("img").mouseup()})},_transitions=function(){var _slide=function(params,complete,fade,door){var easing=this.getOptions("easing"),distance=this.getStageWidth(),from={left:distance*(params.rewind?-1:1)},to={left:0};if(fade){from.opacity=0;to.opacity=1}else{from.opacity=1}$(params.next).css(from);Utils.animate(params.next,to,{duration:params.speed,complete:function(elems){return function(){complete();elems.css({left:0})}}($(params.next).add(params.prev)),queue:false,easing:easing});if(door){params.rewind=!params.rewind}if(params.prev){from={left:0};to={left:distance*(params.rewind?1:-1)};if(fade){from.opacity=1;to.opacity=0}$(params.prev).css(from);Utils.animate(params.prev,to,{duration:params.speed,queue:false,easing:easing,complete:function(){$(this).css("opacity",0)}})}};return{active:false,init:function(effect,params,complete){if(_transitions.effects.hasOwnProperty(effect)){_transitions.effects[effect].call(this,params,complete)}},effects:{fade:function(params,complete){$(params.next).css({opacity:0,left:0});Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete});if(params.prev){$(params.prev).css("opacity",1).show();Utils.animate(params.prev,{opacity:0},{duration:params.speed})}},flash:function(params,complete){$(params.next).css({opacity:0,left:0});if(params.prev){Utils.animate(params.prev,{opacity:0},{duration:params.speed/2,complete:function(){Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete})}})}else{Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete})}},pulse:function(params,complete){if(params.prev){$(params.prev).hide()}$(params.next).css({opacity:0,left:0}).show();Utils.animate(params.next,{opacity:1},{duration:params.speed,complete:complete})},slide:function(params,complete){_slide.apply(this,Utils.array(arguments))},fadeslide:function(params,complete){_slide.apply(this,Utils.array(arguments).concat([true]))},doorslide:function(params,complete){_slide.apply(this,Utils.array(arguments).concat([false,true]))}}}}();_nativeFullscreen.listen();$.event.special["click:fast"]={propagate:true,add:function(handleObj){var getCoords=function(e){if(e.touches&&e.touches.length){var touch=e.touches[0];return{x:touch.pageX,y:touch.pageY}}};var def={touched:false,touchdown:false,coords:{x:0,y:0},evObj:{}};$(this).data({clickstate:def,timer:0}).on("touchstart.fast",function(e){window.clearTimeout($(this).data("timer"));$(this).data("clickstate",{touched:true,touchdown:true,coords:getCoords(e.originalEvent),evObj:e})}).on("touchmove.fast",function(e){var coords=getCoords(e.originalEvent),state=$(this).data("clickstate"),distance=Math.max(Math.abs(state.coords.x-coords.x),Math.abs(state.coords.y-coords.y));if(distance>6){$(this).data("clickstate",$.extend(state,{touchdown:false}))}}).on("touchend.fast",function(e){var $this=$(this),state=$this.data("clickstate");if(state.touchdown){handleObj.handler.call(this,e)}$this.data("timer",window.setTimeout(function(){$this.data("clickstate",def)},400))}).on("click.fast",function(e){var state=$(this).data("clickstate");if(state.touched){return false}$(this).data("clickstate",def);handleObj.handler.call(this,e)})},remove:function(){$(this).off("touchstart.fast touchmove.fast touchend.fast click.fast")}};$win.on("orientationchange",function(){$(this).resize()});Galleria=function(){var self=this;this._options={};this._playing=false;this._playtime=5e3;this._active=null;this._queue={length:0};this._data=[];this._dom={};this._thumbnails=[];this._layers=[];this._initialized=false;this._firstrun=false;this._stageWidth=0;this._stageHeight=0;this._target=undef;this._binds=[];this._id=parseInt(M.random()*1e4,10);var divs="container stage images image-nav image-nav-left image-nav-right "+"info info-text info-title info-description "+"thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right "+"loader counter tooltip",spans="current total";$.each(divs.split(" "),function(i,elemId){self._dom[elemId]=Utils.create("galleria-"+elemId)});$.each(spans.split(" "),function(i,elemId){self._dom[elemId]=Utils.create("galleria-"+elemId,"span")});var keyboard=this._keyboard={keys:{UP:38,DOWN:40,LEFT:37,RIGHT:39,RETURN:13,ESCAPE:27,BACKSPACE:8,SPACE:32},map:{},bound:false,press:function(e){var key=e.keyCode||e.which;if(key in keyboard.map&&typeof keyboard.map[key]==="function"){keyboard.map[key].call(self,e)}},attach:function(map){var key,up;for(key in map){if(map.hasOwnProperty(key)){up=key.toUpperCase();if(up in keyboard.keys){keyboard.map[keyboard.keys[up]]=map[key]}else{keyboard.map[up]=map[key]}}}if(!keyboard.bound){keyboard.bound=true;$doc.on("keydown",keyboard.press)}},detach:function(){keyboard.bound=false;keyboard.map={};$doc.off("keydown",keyboard.press)}};var controls=this._controls={0:undef,1:undef,active:0,swap:function(){controls.active=controls.active?0:1},getActive:function(){return self._options.swipe?controls.slides[self._active]:controls[controls.active]},getNext:function(){return self._options.swipe?controls.slides[self.getNext(self._active)]:controls[1-controls.active]},slides:[],frames:[],layers:[]};var carousel=this._carousel={next:self.$("thumb-nav-right"),prev:self.$("thumb-nav-left"),width:0,current:0,max:0,hooks:[],update:function(){var w=0,h=0,hooks=[0];$.each(self._thumbnails,function(i,thumb){if(thumb.ready){w+=thumb.outerWidth||$(thumb.container).outerWidth(true);var containerWidth=$(thumb.container).width();w+=containerWidth-M.floor(containerWidth);hooks[i+1]=w;h=M.max(h,thumb.outerHeight||$(thumb.container).outerHeight(true))}});self.$("thumbnails").css({width:w,height:h});carousel.max=w;carousel.hooks=hooks;carousel.width=self.$("thumbnails-list").width();carousel.setClasses();self.$("thumbnails-container").toggleClass("galleria-carousel",w>carousel.width);carousel.width=self.$("thumbnails-list").width()},bindControls:function(){var i;carousel.next.on("click:fast",function(e){e.preventDefault();if(self._options.carouselSteps==="auto"){for(i=carousel.current;icarousel.width){carousel.set(i-2);break}}}else{carousel.set(carousel.current+self._options.carouselSteps)}});carousel.prev.on("click:fast",function(e){e.preventDefault();if(self._options.carouselSteps==="auto"){for(i=carousel.current;i>=0;i--){if(carousel.hooks[carousel.current]-carousel.hooks[i]>carousel.width){carousel.set(i+2);break}else if(i===0){carousel.set(0);break}}}else{carousel.set(carousel.current-self._options.carouselSteps)}})},set:function(i){i=M.max(i,0);while(carousel.hooks[i-1]+carousel.width>=carousel.max&&i>=0){i--}carousel.current=i;carousel.animate()},getLast:function(i){return(i||carousel.current)-1},follow:function(i){if(i===0||i===carousel.hooks.length-2){carousel.set(i);return}var last=carousel.current;while(carousel.hooks[last]-carousel.hooks[carousel.current]last){carousel.set(i-last+carousel.current+2)}},setClasses:function(){carousel.prev.toggleClass("disabled",!carousel.current);carousel.next.toggleClass("disabled",carousel.hooks[carousel.current]+carousel.width>=carousel.max)},animate:function(to){carousel.setClasses();var num=carousel.hooks[carousel.current]*-1;if(isNaN(num)){return}self.$("thumbnails").css("left",function(){return $(this).css("left")});Utils.animate(self.get("thumbnails"),{left:num},{duration:self._options.carouselSpeed,easing:self._options.easing,queue:false})}};var tooltip=this._tooltip={initialized:false,open:false,timer:"tooltip"+self._id,swapTimer:"swap"+self._id,init:function(){tooltip.initialized=true;var css=".galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;"+"opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}";Utils.insertStyleTag(css,"galleria-tooltip");self.$("tooltip").css({opacity:.8,visibility:"visible",display:"none"})},move:function(e){var mouseX=self.getMousePosition(e).x,mouseY=self.getMousePosition(e).y,$elem=self.$("tooltip"),x=mouseX,y=mouseY,height=$elem.outerHeight(true)+1,width=$elem.outerWidth(true),limitY=height+15;var maxX=self.$("container").width()-width-2,maxY=self.$("container").height()-height-2;if(!isNaN(x)&&!isNaN(y)){x+=10;y-=height+8;x=M.max(0,M.min(maxX,x));y=M.max(0,M.min(maxY,y));if(mouseY7){exs=IE<9?"background:#000;filter:alpha(opacity=0);":"background:rgba(0,0,0,0);"}else{exs="z-index:99999"}cssMap.nextholder+=exs;cssMap.prevholder+=exs;$.each(cssMap,function(key,value){css+=".galleria-"+prefix+key+"{"+value+"}"});css+=".galleria-"+prefix+"box.iframe .galleria-"+prefix+"prevholder,"+".galleria-"+prefix+"box.iframe .galleria-"+prefix+"nextholder{"+"width:100px;height:100px;top:50%;margin-top:-70px}";Utils.insertStyleTag(css,"galleria-lightbox");$.each(elems.split(" "),function(i,elemId){self.addElement("lightbox-"+elemId);el[elemId]=lightbox.elems[elemId]=self.get("lightbox-"+elemId)});lightbox.image=new Galleria.Picture;$.each({box:"shadow content close prevholder nextholder",info:"title counter",content:"info image",prevholder:"prev",nextholder:"next"},function(key,val){var arr=[];$.each(val.split(" "),function(i,prop){arr.push(prefix+prop)});appends[prefix+key]=arr});self.append(appends);$(el.image).append(lightbox.image.container);$(DOM().body).append(el.overlay,el.box);hover($(el.close).on("click:fast",lightbox.hide).html("×"));$.each(["Prev","Next"],function(i,dir){var $d=$(el[dir.toLowerCase()]).html(/v/.test(dir)?"‹ ":" ›"),$e=$(el[dir.toLowerCase()+"holder"]);$e.on("click:fast",function(){lightbox["show"+dir]()});if(IE<8||Galleria.TOUCH){$d.show();return}$e.hover(function(){$d.show()},function(e){$d.stop().fadeOut(200)})});$(el.overlay).on("click:fast",lightbox.hide);if(Galleria.IPAD){self._options.lightboxTransitionSpeed=0}},rescale:function(event){var width=M.min($win.width()-40,lightbox.width),height=M.min($win.height()-60,lightbox.height),ratio=M.min(width/lightbox.width,height/lightbox.height),destWidth=M.round(lightbox.width*ratio)+40,destHeight=M.round(lightbox.height*ratio)+60,to={width:destWidth,height:destHeight,"margin-top":M.ceil(destHeight/2)*-1,"margin-left":M.ceil(destWidth/2)*-1};if(event){$(lightbox.elems.box).css(to)}else{$(lightbox.elems.box).animate(to,{duration:self._options.lightboxTransitionSpeed,easing:self._options.easing,complete:function(){var image=lightbox.image,speed=self._options.lightboxFadeSpeed;self.trigger({type:Galleria.LIGHTBOX_IMAGE,imageTarget:image.image});$(image.container).show();$(image.image).animate({opacity:1},speed);Utils.show(lightbox.elems.info,speed)}})}},hide:function(){lightbox.image.image=null;$win.off("resize",lightbox.rescale);$(lightbox.elems.box).hide().find("iframe").remove();Utils.hide(lightbox.elems.info);self.detachKeyboard();self.attachKeyboard(lightbox.keymap);lightbox.keymap=false;Utils.hide(lightbox.elems.overlay,200,function(){$(this).hide().css("opacity",self._options.overlayOpacity);self.trigger(Galleria.LIGHTBOX_CLOSE)})},showNext:function(){lightbox.show(self.getNext(lightbox.active))},showPrev:function(){lightbox.show(self.getPrev(lightbox.active))},show:function(index){lightbox.active=index=typeof index==="number"?index:self.getIndex()||0;if(!lightbox.initialized){lightbox.init()}self.trigger(Galleria.LIGHTBOX_OPEN);if(!lightbox.keymap){lightbox.keymap=$.extend({},self._keyboard.map);self.attachKeyboard({escape:lightbox.hide,right:lightbox.showNext,left:lightbox.showPrev})}$win.off("resize",lightbox.rescale);var data=self.getData(index),total=self.getDataLength(),n=self.getNext(index),ndata,p,i;Utils.hide(lightbox.elems.info);try{for(i=self._options.preload;i>0;i--){p=new Galleria.Picture;ndata=self.getData(n);p.preload(ndata.big?ndata.big:ndata.image);n=self.getNext(n)}}catch(e){}lightbox.image.isIframe=data.iframe&&!data.image;$(lightbox.elems.box).toggleClass("iframe",lightbox.image.isIframe);$(lightbox.image.container).find(".galleria-videoicon").remove();lightbox.image.load(data.big||data.image||data.iframe,function(image){if(image.isIframe){var cw=$(window).width(),ch=$(window).height();if(image.video&&self._options.maxVideoSize){var r=M.min(self._options.maxVideoSize/cw,self._options.maxVideoSize/ch);if(r<1){cw*=r;ch*=r}}lightbox.width=cw;lightbox.height=ch}else{lightbox.width=image.original.width;lightbox.height=image.original.height}$(image.image).css({width:image.isIframe?"100%":"100.1%",height:image.isIframe?"100%":"100.1%",top:0,bottom:0,zIndex:99998,opacity:0,visibility:"visible"}).parent().height("100%");lightbox.elems.title.innerHTML=data.title||"";lightbox.elems.counter.innerHTML=index+1+" / "+total;$win.resize(lightbox.rescale);lightbox.rescale();if(data.image&&data.iframe){$(lightbox.elems.box).addClass("iframe");if(data.video){var $icon=_playIcon(image.container).hide();window.setTimeout(function(){$icon.fadeIn(200)},200)}$(image.image).css("cursor","pointer").mouseup(function(data,image){return function(e){$(lightbox.image.container).find(".galleria-videoicon").remove();e.preventDefault();image.isIframe=true;image.load(data.iframe+(data.video?"&autoplay=1":""),{width:"100%",height:IE<8?$(lightbox.image.container).height():"100%"})}}(data,image))}});$(lightbox.elems.overlay).show().css("visibility","visible");$(lightbox.elems.box).show()}};var _timer=this._timer={trunk:{},add:function(id,fn,delay,loop){id=id||(new Date).getTime();loop=loop||false;this.clear(id);if(loop){var old=fn;fn=function(){old();_timer.add(id,fn,delay)}}this.trunk[id]=window.setTimeout(fn,delay)},clear:function(id){var del=function(i){window.clearTimeout(this.trunk[i]);delete this.trunk[i]},i;if(!!id&&id in this.trunk){del.call(this,id)}else if(typeof id==="undefined"){for(i in this.trunk){if(this.trunk.hasOwnProperty(i)){del.call(this,i)}}}}};return this};Galleria.prototype={constructor:Galleria,init:function(target,options){options=_legacyOptions(options);this._original={target:target,options:options,data:null};this._target=this._dom.target=target.nodeName?target:$(target).get(0);this._original.html=this._target.innerHTML;_instances.push(this);if(!this._target){Galleria.raise("Target not found",true);return}this._options={autoplay:false,carousel:true,carouselFollow:true,carouselSpeed:400,carouselSteps:"auto",clicknext:false,dailymotion:{foreground:"%23EEEEEE",highlight:"%235BCEC5",background:"%23222222",logo:0,hideInfos:1},dataConfig:function(elem){return{}},dataSelector:"img",dataSort:false,dataSource:this._target,debug:undef,dummy:undef,easing:"galleria",extend:function(options){},fullscreenCrop:undef,fullscreenDoubleTap:true,fullscreenTransition:undef,height:0,idleMode:true,idleTime:3e3,idleSpeed:200,imageCrop:false,imageMargin:0,imagePan:false,imagePanSmoothness:12,imagePosition:"50%",imageTimeout:undef,initialTransition:undef,keepSource:false,layerFollow:true,lightbox:false,lightboxFadeSpeed:200,lightboxTransitionSpeed:200,linkSourceImages:true,maxScaleRatio:undef,maxVideoSize:undef,minScaleRatio:undef,overlayOpacity:.85,overlayBackground:"#0b0b0b",pauseOnInteraction:true,popupLinks:false,preload:2,queue:true,responsive:true,show:0,showInfo:true,showCounter:true,showImagenav:true,swipe:"auto",theme:null,thumbCrop:true,thumbEventType:"click:fast",thumbMargin:0,thumbQuality:"auto",thumbDisplayOrder:true,thumbPosition:"50%",thumbnails:true,touchTransition:undef,transition:"fade",transitionInitial:undef,transitionSpeed:400,trueFullscreen:true,useCanvas:false,variation:"",videoPoster:true,vimeo:{title:0,byline:0,portrait:0,color:"aaaaaa"},wait:5e3,width:"auto",youtube:{modestbranding:1,autohide:1,color:"white",hd:1,rel:0,showinfo:0}};this._options.initialTransition=this._options.initialTransition||this._options.transitionInitial;if(options){if(options.debug===false){DEBUG=false}if(typeof options.imageTimeout==="number"){TIMEOUT=options.imageTimeout}if(typeof options.dummy==="string"){DUMMY=options.dummy}if(typeof options.theme=="string"){this._options.theme=options.theme}}$(this._target).children().hide();if(Galleria.QUIRK){Galleria.raise("Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML and add a correct doctype.")}if(_loadedThemes.length){if(this._options.theme){for(var i=0;i<_loadedThemes.length;i++){if(this._options.theme===_loadedThemes[i].name){this.theme=_loadedThemes[i];break}}}else{this.theme=_loadedThemes[0]}}if(typeof this.theme=="object"){this._init()}else{_pool.push(this)}return this},_init:function(){var self=this,options=this._options;if(this._initialized){Galleria.raise("Init failed: Gallery instance already initialized.");return this}this._initialized=true;if(!this.theme){Galleria.raise("Init failed: No theme found.",true);return this}$.extend(true,options,this.theme.defaults,this._original.options,Galleria.configure.options);options.swipe=function(s){if(s=="enforced"){return true}if(s===false||s=="disabled"){return false}return!!Galleria.TOUCH}(options.swipe);if(options.swipe){options.clicknext=false;options.imagePan=false}(function(can){if(!("getContext"in can)){can=null;return}_canvas=_canvas||{elem:can,context:can.getContext("2d"),cache:{},length:0}})(doc.createElement("canvas"));this.bind(Galleria.DATA,function(){if(window.screen&&window.screen.width&&Array.prototype.forEach){this._data.forEach(function(data){var density="devicePixelRatio"in window?window.devicePixelRatio:1,m=M.max(window.screen.width,window.screen.height);if(m*density<1024){data.big=data.image}})}this._original.data=this._data;this.get("total").innerHTML=this.getDataLength();var $container=this.$("container");if(self._options.height<2){self._userRatio=self._ratio=self._options.height}var num={width:0,height:0};var testHeight=function(){return self.$("stage").height()};Utils.wait({until:function(){num=self._getWH();$container.width(num.width).height(num.height);return testHeight()&&num.width&&num.height>50},success:function(){self._width=num.width;self._height=num.height;self._ratio=self._ratio||num.height/num.width;if(Galleria.WEBKIT){window.setTimeout(function(){self._run()},1)}else{self._run()}},error:function(){if(testHeight()){Galleria.raise("Could not extract sufficient width/height of the gallery container. Traced measures: width:"+num.width+"px, height: "+num.height+"px.",true)}else{Galleria.raise("Could not extract a stage height from the CSS. Traced height: "+testHeight()+"px.",true)}},timeout:typeof this._options.wait=="number"?this._options.wait:false})});this.append({"info-text":["info-title","info-description"],info:["info-text"],"image-nav":["image-nav-right","image-nav-left"],stage:["images","loader","counter","image-nav"],"thumbnails-list":["thumbnails"],"thumbnails-container":["thumb-nav-left","thumbnails-list","thumb-nav-right"],container:["stage","thumbnails-container","info","tooltip"]});Utils.hide(this.$("counter").append(this.get("current"),doc.createTextNode(" / "),this.get("total")));this.setCounter("–");Utils.hide(self.get("tooltip"));this.$("container").addClass([Galleria.TOUCH?"touch":"notouch",this._options.variation,"galleria-theme-"+this.theme.name].join(" "));if(!this._options.swipe){$.each(new Array(2),function(i){var image=new Galleria.Picture;$(image.container).css({position:"absolute",top:0,left:0}).prepend(self._layers[i]=$(Utils.create("galleria-layer")).css({position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:2})[0]);self.$("images").append(image.container);self._controls[i]=image;var frame=new Galleria.Picture;frame.isIframe=true;$(frame.container).attr("class","galleria-frame").css({position:"absolute",top:0,left:0,zIndex:4,background:"#000",display:"none"}).appendTo(image.container);self._controls.frames[i]=frame})}this.$("images").css({position:"relative",top:0,left:0,width:"100%",height:"100%"});if(options.swipe){this.$("images").css({position:"absolute",top:0,left:0,width:0,height:"100%"});this.finger=new Galleria.Finger(this.get("stage"),{onchange:function(page){self.pause().show(page)},oncomplete:function(page){var index=M.max(0,M.min(parseInt(page,10),self.getDataLength()-1)),data=self.getData(index);$(self._thumbnails[index].container).addClass("active").siblings(".active").removeClass("active");if(!data){return}self.$("images").find(".galleria-frame").css("opacity",0).hide().find("iframe").remove();if(self._options.carousel&&self._options.carouselFollow){self._carousel.follow(index)}}});this.bind(Galleria.RESCALE,function(){this.finger.setup()});this.$("stage").on("click",function(e){var data=self.getData();if(!data){return}if(data.iframe){if(self.isPlaying()){self.pause()}var frame=self._controls.frames[self._active],w=self._stageWidth,h=self._stageHeight;if($(frame.container).find("iframe").length){return}$(frame.container).css({width:w,height:h,opacity:0}).show().animate({opacity:1},200);window.setTimeout(function(){frame.load(data.iframe+(data.video?"&autoplay=1":""),{width:w,height:h},function(frame){self.$("container").addClass("videoplay");frame.scale({width:self._stageWidth,height:self._stageHeight,iframelimit:data.video?self._options.maxVideoSize:undef})})},100);return}if(data.link){if(self._options.popupLinks){var win=window.open(data.link,"_blank")}else{window.location.href=data.link}return}});this.bind(Galleria.IMAGE,function(e){self.setCounter(e.index);self.setInfo(e.index);var next=this.getNext(),prev=this.getPrev();var preloads=[prev,next];preloads.push(this.getNext(next),this.getPrev(prev),self._controls.slides.length-1);var filtered=[];$.each(preloads,function(i,val){if($.inArray(val,filtered)==-1){filtered.push(val)}});$.each(filtered,function(i,loadme){var d=self.getData(loadme),img=self._controls.slides[loadme],src=self.isFullscreen()&&d.big?d.big:d.image||d.iframe;if(d.iframe&&!d.image){img.isIframe=true}if(!img.ready){self._controls.slides[loadme].load(src,function(img){if(!img.isIframe){$(img.image).css("visibility","hidden")}self._scaleImage(img,{complete:function(img){if(!img.isIframe){$(img.image).css({opacity:0,visibility:"visible"}).animate({opacity:1},200)}}})})}})})}this.$("thumbnails, thumbnails-list").css({overflow:"hidden",position:"relative"});this.$("image-nav-right, image-nav-left").on("click:fast",function(e){if(options.pauseOnInteraction){self.pause()}var fn=/right/.test(this.className)?"next":"prev";self[fn]()}).on("click",function(e){e.preventDefault();if(options.clicknext||options.swipe){e.stopPropagation()}});$.each(["info","counter","image-nav"],function(i,el){if(options["show"+el.substr(0,1).toUpperCase()+el.substr(1).replace(/-/,"")]===false){Utils.moveOut(self.get(el.toLowerCase()))}});this.load();if(!options.keepSource&&!IE){this._target.innerHTML=""}if(this.get("errors")){this.appendChild("target","errors")}this.appendChild("target","container");if(options.carousel){var count=0,show=options.show;this.bind(Galleria.THUMBNAIL,function(){this.updateCarousel();if(++count==this.getDataLength()&&typeof show=="number"&&show>0){this._carousel.follow(show)}})}if(options.responsive){$win.on("resize",function(){if(!self.isFullscreen()){self.resize()}})}if(options.fullscreenDoubleTap){this.$("stage").on("touchstart",function(){var last,cx,cy,lx,ly,now,getData=function(e){return e.originalEvent.touches?e.originalEvent.touches[0]:e};self.$("stage").on("touchmove",function(){last=0});return function(e){if(/(-left|-right)/.test(e.target.className)){return}now=Utils.timestamp();cx=getData(e).pageX;cy=getData(e).pageY;if(e.originalEvent.touches.length<2&&now-last<300&&cx-lx<20&&cy-ly<20){self.toggleFullscreen();e.preventDefault();return}last=now;lx=cx;ly=cy}}())}$.each(Galleria.on.binds,function(i,bind){if($.inArray(bind.hash,self._binds)==-1){self.bind(bind.type,bind.callback)}});return this},addTimer:function(){this._timer.add.apply(this._timer,Utils.array(arguments));return this},clearTimer:function(){this._timer.clear.apply(this._timer,Utils.array(arguments));return this},_getWH:function(){var $container=this.$("container"),$target=this.$("target"),self=this,num={},arr;$.each(["width","height"],function(i,m){if(self._options[m]&&typeof self._options[m]==="number"){num[m]=self._options[m]}else{arr=[Utils.parseValue($container.css(m)),Utils.parseValue($target.css(m)),$container[m](),$target[m]()];if(!self["_"+m]){arr.splice(arr.length,Utils.parseValue($container.css("min-"+m)),Utils.parseValue($target.css("min-"+m)))}num[m]=M.max.apply(M,arr)}});if(self._userRatio){num.height=num.width*self._userRatio}return num},_createThumbnails:function(push){this.get("total").innerHTML=this.getDataLength();var src,thumb,data,$container,self=this,o=this._options,i=push?this._data.length-push.length:0,chunk=i,thumbchunk=[],loadindex=0,gif=IE<8?"http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif":"data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D",active=function(){var a=self.$("thumbnails").find(".active");if(!a.length){return false}return a.find("img").attr("src")}(),optval=typeof o.thumbnails==="string"?o.thumbnails.toLowerCase():null,getStyle=function(prop){return doc.defaultView&&doc.defaultView.getComputedStyle?doc.defaultView.getComputedStyle(thumb.container,null)[prop]:$container.css(prop)},fake=function(image,index,container){return function(){$(container).append(image);self.trigger({type:Galleria.THUMBNAIL,thumbTarget:image,index:index,galleriaData:self.getData(index)})}},onThumbEvent=function(e){if(o.pauseOnInteraction){self.pause()}var index=$(e.currentTarget).data("index");if(self.getIndex()!==index){self.show(index)}e.preventDefault()},thumbComplete=function(thumb,callback){$(thumb.container).css("visibility","visible");self.trigger({type:Galleria.THUMBNAIL,thumbTarget:thumb.image,index:thumb.data.order,galleriaData:self.getData(thumb.data.order)});if(typeof callback=="function"){callback.call(self,thumb)}},onThumbLoad=function(thumb,callback){thumb.scale({width:thumb.data.width,height:thumb.data.height,crop:o.thumbCrop,margin:o.thumbMargin,canvas:o.useCanvas,position:o.thumbPosition,complete:function(thumb){var top=["left","top"],arr=["Width","Height"],m,css,data=self.getData(thumb.index);$.each(arr,function(i,measure){m=measure.toLowerCase();if(o.thumbCrop!==true||o.thumbCrop===m){css={};css[m]=thumb[m];$(thumb.container).css(css);css={};css[top[i]]=0;$(thumb.image).css(css)}thumb["outer"+measure]=$(thumb.container)["outer"+measure](true)});Utils.toggleQuality(thumb.image,o.thumbQuality===true||o.thumbQuality==="auto"&&thumb.original.widthself._thumbnails.length-1){return}var thumb=self._thumbnails[ind],data=thumb.data,callback=function(){if(++loaded==arr.length&&typeof complete=="function"){complete.call(self)}},thumbload=$(thumb.container).data("thumbload");if(thumb.video){thumbload.call(self,thumb,callback)}else{thumb.load(data.src,function(thumb){thumbload.call(self,thumb,callback)})}});return this},lazyLoadChunks:function(size,delay){var len=this.getDataLength(),i=0,n=0,arr=[],temp=[],self=this;delay=delay||0;for(;i50},success:function(){_galleries.push(self);if(self._options.swipe){var $images=self.$("images").width(self.getDataLength()*self._stageWidth);$.each(new Array(self.getDataLength()),function(i){var image=new Galleria.Picture,data=self.getData(i);$(image.container).css({position:"absolute",top:0,left:self._stageWidth*i}).prepend(self._layers[i]=$(Utils.create("galleria-layer")).css({position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:2})[0]).appendTo($images);if(data.video){_playIcon(image.container)}self._controls.slides.push(image);var frame=new Galleria.Picture;frame.isIframe=true;$(frame.container).attr("class","galleria-frame").css({position:"absolute",top:0,left:0,zIndex:4,background:"#000",display:"none"}).appendTo(image.container);self._controls.frames.push(frame)});self.finger.setup()}Utils.show(self.get("counter"));if(self._options.carousel){self._carousel.bindControls()}if(self._options.autoplay){self.pause();if(typeof self._options.autoplay==="number"){self._playtime=self._options.autoplay}self._playing=true}if(self._firstrun){if(self._options.autoplay){self.trigger(Galleria.PLAY)}if(typeof self._options.show==="number"){self.show(self._options.show)}return}self._firstrun=true;if(Galleria.History){Galleria.History.change(function(value){if(isNaN(value)){window.history.go(-1)}else{self.show(value,undef,true)}})}self.trigger(Galleria.READY);self.theme.init.call(self,self._options);$.each(Galleria.ready.callbacks,function(i,fn){if(typeof fn=="function"){fn.call(self,self._options)}});self._options.extend.call(self,self._options);if(/^[0-9]{1,4}$/.test(HASH)&&Galleria.History){self.show(HASH,undef,true)}else if(self._data[self._options.show]){self.show(self._options.show)}if(self._options.autoplay){self.trigger(Galleria.PLAY)}},error:function(){Galleria.raise("Stage width or height is too small to show the gallery. Traced measures: width:"+self._stageWidth+"px, height: "+self._stageHeight+"px.",true)}})},load:function(source,selector,config){var self=this,o=this._options;this._data=[];this._thumbnails=[];this.$("thumbnails").empty();if(typeof selector==="function"){config=selector;selector=null}source=source||o.dataSource;selector=selector||o.dataSelector;config=config||o.dataConfig;if($.isPlainObject(source)){source=[source]}if($.isArray(source)){if(this.validate(source)){this._data=source}else{Galleria.raise("Load failed: JSON Array not valid.")}}else{selector+=",.video,.iframe";$(source).find(selector).each(function(i,elem){elem=$(elem);var data={},parent=elem.parent(),href=parent.attr("href"),rel=parent.attr("rel");if(href&&(elem[0].nodeName=="IMG"||elem.hasClass("video"))&&_videoTest(href)){data.video=href}else if(href&&elem.hasClass("iframe")){data.iframe=href}else{data.image=data.big=href}if(rel){data.big=rel}$.each("big title description link layer image".split(" "),function(i,val){if(elem.data(val)){data[val]=elem.data(val).toString()}});if(!data.big){data.big=data.image}self._data.push($.extend({title:elem.attr("title")||"",thumb:elem.attr("src"),image:elem.attr("src"),big:elem.attr("src"),description:elem.attr("alt")||"",link:elem.attr("longdesc"),original:elem.get(0)},data,config(elem)))})}if(typeof o.dataSort=="function"){protoArray.sort.call(this._data,o.dataSort)}else if(o.dataSort=="random"){this._data.sort(function(){return M.round(M.random())-.5})}if(this.getDataLength()){this._parseData(function(){this.trigger(Galleria.DATA)})}return this},_parseData:function(callback){var self=this,current,ready=false,onload=function(){var complete=true;$.each(self._data,function(i,data){if(data.loading){complete=false;return false}});if(complete&&!ready){ready=true;callback.call(self)}};$.each(this._data,function(i,data){current=self._data[i];if("thumb"in data===false){current.thumb=data.image}if(!data.big){current.big=data.image}if("video"in data){var result=_videoTest(data.video);if(result){current.iframe=new Video(result.provider,result.id).embed()+function(){if(typeof self._options[result.provider]=="object"){var str="?",arr=[];$.each(self._options[result.provider],function(key,val){arr.push(key+"="+val)});if(result.provider=="youtube"){arr=["wmode=opaque"].concat(arr)}return str+arr.join("&")}return""}();if(!current.thumb||!current.image){$.each(["thumb","image"],function(i,type){if(type=="image"&&!self._options.videoPoster){current.image=undef;return}var video=new Video(result.provider,result.id);if(!current[type]){current.loading=true;video.getMedia(type,function(current,type){return function(src){current[type]=src;if(type=="image"&&!current.big){current.big=current.image}delete current.loading;onload()}}(current,type))}})}}}});onload();return this},destroy:function(){this.$("target").data("galleria",null);this.$("container").off("galleria");this.get("target").innerHTML=this._original.html;this.clearTimer();Utils.removeFromArray(_instances,this);Utils.removeFromArray(_galleries,this);if(Galleria._waiters.length){$.each(Galleria._waiters,function(i,w){if(w)window.clearTimeout(w)})}return this},splice:function(){var self=this,args=Utils.array(arguments);window.setTimeout(function(){protoArray.splice.apply(self._data,args);self._parseData(function(){self._createThumbnails()})},2);return self},push:function(){var self=this,args=Utils.array(arguments);if(args.length==1&&args[0].constructor==Array){args=args[0]}window.setTimeout(function(){protoArray.push.apply(self._data,args);self._parseData(function(){self._createThumbnails(args)})},2);return self},_getActive:function(){return this._controls.getActive()},validate:function(data){return true},bind:function(type,fn){type=_patchEvent(type);this.$("container").on(type,this.proxy(fn));return this},unbind:function(type){type=_patchEvent(type);this.$("container").off(type);return this},trigger:function(type){type=typeof type==="object"?$.extend(type,{scope:this}):{type:_patchEvent(type),scope:this};this.$("container").trigger(type);return this},addIdleState:function(elem,styles,from,hide){this._idle.add.apply(this._idle,Utils.array(arguments));return this},removeIdleState:function(elem){this._idle.remove.apply(this._idle,Utils.array(arguments));return this},enterIdleMode:function(){this._idle.hide();return this},exitIdleMode:function(){this._idle.showAll();return this},enterFullscreen:function(callback){this._fullscreen.enter.apply(this,Utils.array(arguments));return this},exitFullscreen:function(callback){this._fullscreen.exit.apply(this,Utils.array(arguments));return this},toggleFullscreen:function(callback){this._fullscreen[this.isFullscreen()?"exit":"enter"].apply(this,Utils.array(arguments));return this},bindTooltip:function(elem,value){this._tooltip.bind.apply(this._tooltip,Utils.array(arguments));return this},defineTooltip:function(elem,value){this._tooltip.define.apply(this._tooltip,Utils.array(arguments));return this},refreshTooltip:function(elem){this._tooltip.show.apply(this._tooltip,Utils.array(arguments));return this},openLightbox:function(){this._lightbox.show.apply(this._lightbox,Utils.array(arguments));return this},closeLightbox:function(){this._lightbox.hide.apply(this._lightbox,Utils.array(arguments));return this},hasVariation:function(variation){return $.inArray(variation,this._options.variation.split(/\s+/))>-1},getActiveImage:function(){var active=this._getActive();return active?active.image:undef},getActiveThumb:function(){return this._thumbnails[this._active].image||undef},getMousePosition:function(e){return{x:e.pageX-this.$("container").offset().left,y:e.pageY-this.$("container").offset().top}},addPan:function(img){if(this._options.imageCrop===false){return}img=$(img||this.getActiveImage());var self=this,x=img.width()/2,y=img.height()/2,destX=parseInt(img.css("left"),10),destY=parseInt(img.css("top"),10),curX=destX||0,curY=destY||0,distX=0,distY=0,active=false,ts=Utils.timestamp(),cache=0,move=0,position=function(dist,cur,pos){if(dist>0){move=M.round(M.max(dist*-1,M.min(0,cur)));if(cache!==move){cache=move;if(IE===8){img.parent()["scroll"+pos](move*-1)}else{var css={};css[pos.toLowerCase()]=move;img.css(css)}}}},calculate=function(e){if(Utils.timestamp()-ts<50){return}active=true;x=self.getMousePosition(e).x;y=self.getMousePosition(e).y},loop=function(e){if(!active){return}distX=img.width()-self._stageWidth;distY=img.height()-self._stageHeight;destX=x/self._stageWidth*distX*-1;destY=y/self._stageHeight*distY*-1;curX+=(destX-curX)/self._options.imagePanSmoothness;curY+=(destY-curY)/self._options.imagePanSmoothness;position(distY,curY,"Top");position(distX,curX,"Left")};if(IE===8){img.parent().scrollTop(curY*-1).scrollLeft(curX*-1);img.css({top:0,left:0})}this.$("stage").off("mousemove",calculate).on("mousemove",calculate);this.addTimer("pan"+self._id,loop,50,true);return this},proxy:function(fn,scope){if(typeof fn!=="function"){return F}scope=scope||this;return function(){return fn.apply(scope,Utils.array(arguments))}},getThemeName:function(){return this.theme.name},removePan:function(){this.$("stage").off("mousemove");this.clearTimer("pan"+this._id);return this},addElement:function(id){var dom=this._dom;$.each(Utils.array(arguments),function(i,blueprint){dom[blueprint]=Utils.create("galleria-"+blueprint)});return this},attachKeyboard:function(map){this._keyboard.attach.apply(this._keyboard,Utils.array(arguments));return this},detachKeyboard:function(){this._keyboard.detach.apply(this._keyboard,Utils.array(arguments));return this},appendChild:function(parentID,childID){this.$(parentID).append(this.get(childID)||childID);
-return this},prependChild:function(parentID,childID){this.$(parentID).prepend(this.get(childID)||childID);return this},remove:function(elemID){this.$(Utils.array(arguments).join(",")).remove();return this},append:function(data){var i,j;for(i in data){if(data.hasOwnProperty(i)){if(data[i].constructor===Array){for(j=0;data[i][j];j++){this.appendChild(i,data[i][j])}}else{this.appendChild(i,data[i])}}}return this},_scaleImage:function(image,options){image=image||this._controls.getActive();if(!image){return}var complete,scaleLayer=function(img){$(img.container).children(":first").css({top:M.max(0,Utils.parseValue(img.image.style.top)),left:M.max(0,Utils.parseValue(img.image.style.left)),width:Utils.parseValue(img.image.width),height:Utils.parseValue(img.image.height)})};options=$.extend({width:this._stageWidth,height:this._stageHeight,crop:this._options.imageCrop,max:this._options.maxScaleRatio,min:this._options.minScaleRatio,margin:this._options.imageMargin,position:this._options.imagePosition,iframelimit:this._options.maxVideoSize},options);if(this._options.layerFollow&&this._options.imageCrop!==true){if(typeof options.complete=="function"){complete=options.complete;options.complete=function(){complete.call(image,image);scaleLayer(image)}}else{options.complete=scaleLayer}}else{$(image.container).children(":first").css({top:0,left:0})}image.scale(options);return this},updateCarousel:function(){this._carousel.update();return this},resize:function(measures,complete){if(typeof measures=="function"){complete=measures;measures=undef}measures=$.extend({width:0,height:0},measures);var self=this,$container=this.$("container");$.each(measures,function(m,val){if(!val){$container[m]("auto");measures[m]=self._getWH()[m]}});$.each(measures,function(m,val){$container[m](val)});return this.rescale(complete)},rescale:function(width,height,complete){var self=this;if(typeof width==="function"){complete=width;width=undef}var scale=function(){self._stageWidth=width||self.$("stage").width();self._stageHeight=height||self.$("stage").height();if(self._options.swipe){$.each(self._controls.slides,function(i,img){self._scaleImage(img);$(img.container).css("left",self._stageWidth*i)});self.$("images").css("width",self._stageWidth*self.getDataLength())}else{self._scaleImage()}if(self._options.carousel){self.updateCarousel()}var frame=self._controls.frames[self._controls.active];if(frame){self._controls.frames[self._controls.active].scale({width:self._stageWidth,height:self._stageHeight,iframelimit:self._options.maxVideoSize})}self.trigger(Galleria.RESCALE);if(typeof complete==="function"){complete.call(self)}};scale.call(self);return this},refreshImage:function(){this._scaleImage();if(this._options.imagePan){this.addPan()}return this},_preload:function(){if(this._options.preload){var p,i,n=this.getNext(),ndata;try{for(i=this._options.preload;i>0;i--){p=new Galleria.Picture;ndata=this.getData(n);p.preload(this.isFullscreen()&&ndata.big?ndata.big:ndata.image);n=this.getNext(n)}}catch(e){}}},show:function(index,rewind,_history){var swipe=this._options.swipe;if(!swipe&&(this._queue.length>3||index===false||!this._options.queue&&this._queue.stalled)){return}index=M.max(0,M.min(parseInt(index,10),this.getDataLength()-1));rewind=typeof rewind!=="undefined"?!!rewind:index1){return}if(data.iframe){if(self.isPlaying()){self.pause()}var frame=self._controls.frames[self._controls.active],w=self._stageWidth,h=self._stageHeight;$(frame.container).css({width:w,height:h,opacity:0}).show().animate({opacity:1},200);window.setTimeout(function(){frame.load(data.iframe+(data.video?"&autoplay=1":""),{width:w,height:h},function(frame){self.$("container").addClass("videoplay");frame.scale({width:self._stageWidth,height:self._stageHeight,iframelimit:data.video?self._options.maxVideoSize:undef})})},100);return}if(self._options.clicknext&&!Galleria.TOUCH){if(self._options.pauseOnInteraction){self.pause()}self.next();return}if(data.link){if(self._options.popupLinks){win=window.open(data.link,"_blank")}else{window.location.href=data.link}return}if(self._options.lightbox){self.openLightbox()}})}self._playCheck();self.trigger({type:Galleria.IMAGE,index:queue.index,imageTarget:next.image,thumbTarget:thumb.image,galleriaData:data});protoArray.shift.call(self._queue);self._queue.stalled=false;if(self._queue.length){self._show()}}}(data,next,active,queue,thumb);if(this._options.carousel&&this._options.carouselFollow){this._carousel.follow(queue.index)}self._preload();Utils.show(next.container);next.isIframe=data.iframe&&!data.image;$(self._thumbnails[queue.index].container).addClass("active").siblings(".active").removeClass("active");self.trigger({type:Galleria.LOADSTART,cached:cached,index:queue.index,rewind:queue.rewind,imageTarget:next.image,thumbTarget:thumb.image,galleriaData:data});self._queue.stalled=true;next.load(src,function(next){var layer=$(self._layers[1-self._controls.active]).html(data.layer||"").hide();self._scaleImage(next,{complete:function(next){if("image"in active){Utils.toggleQuality(active.image,false)}Utils.toggleQuality(next.image,false);self.removePan();self.setInfo(queue.index);self.setCounter(queue.index);if(data.layer){layer.show();if(data.iframe&&data.image||data.link||self._options.lightbox||self._options.clicknext){layer.css("cursor","pointer").off("mouseup").mouseup(mousetrigger)}}if(data.video&&data.image){_playIcon(next.container)}var transition=self._options.transition;$.each({initial:active.image===null,touch:Galleria.TOUCH,fullscreen:self.isFullscreen()},function(type,arg){if(arg&&self._options[type+"Transition"]!==undef){transition=self._options[type+"Transition"];return false}});if(transition in _transitions.effects===false){complete()}else{var params={prev:active.container,next:next.container,rewind:queue.rewind,speed:self._options.transitionSpeed||400};_transitions.active=true;_transitions.init.call(self,transition,params,complete)}self.trigger({type:Galleria.LOADFINISH,cached:cached,index:queue.index,rewind:queue.rewind,imageTarget:next.image,thumbTarget:self._thumbnails[queue.index].image,galleriaData:self.getData(queue.index)})}})})},getNext:function(base){base=typeof base==="number"?base:this.getIndex();return base===this.getDataLength()-1?0:base+1},getPrev:function(base){base=typeof base==="number"?base:this.getIndex();return base===0?this.getDataLength()-1:base-1},next:function(){if(this.getDataLength()>1){this.show(this.getNext(),false)}return this},prev:function(){if(this.getDataLength()>1){this.show(this.getPrev(),true)}return this},get:function(elemId){return elemId in this._dom?this._dom[elemId]:null},getData:function(index){return index in this._data?this._data[index]:this._data[this._active]},getDataLength:function(){return this._data.length},getIndex:function(){return typeof this._active==="number"?this._active:false},getStageHeight:function(){return this._stageHeight},getStageWidth:function(){return this._stageWidth},getOptions:function(key){return typeof key==="undefined"?this._options:this._options[key]},setOptions:function(key,value){if(typeof key==="object"){$.extend(this._options,key)}else{this._options[key]=value}return this},play:function(delay){this._playing=true;this._playtime=delay||this._playtime;this._playCheck();this.trigger(Galleria.PLAY);return this},pause:function(){this._playing=false;this.trigger(Galleria.PAUSE);return this},playToggle:function(delay){return this._playing?this.pause():this.play(delay)},isPlaying:function(){return this._playing},isFullscreen:function(){return this._fullscreen.active},_playCheck:function(){var self=this,played=0,interval=20,now=Utils.timestamp(),timer_id="play"+this._id;if(this._playing){this.clearTimer(timer_id);var fn=function(){played=Utils.timestamp()-now;if(played>=self._playtime&&self._playing){self.clearTimer(timer_id);self.next();return}if(self._playing){self.trigger({type:Galleria.PROGRESS,percent:M.ceil(played/self._playtime*100),seconds:M.floor(played/1e3),milliseconds:played});self.addTimer(timer_id,fn,interval)}};self.addTimer(timer_id,fn,interval)}},setPlaytime:function(delay){this._playtime=delay;return this},setIndex:function(val){this._active=val;return this},setCounter:function(index){if(typeof index==="number"){index++}else if(typeof index==="undefined"){index=this.getIndex()+1}this.get("current").innerHTML=index;if(IE){var count=this.$("counter"),opacity=count.css("opacity");if(parseInt(opacity,10)===1){Utils.removeAlpha(count[0])}else{this.$("counter").css("opacity",opacity)}}return this},setInfo:function(index){var self=this,data=this.getData(index);$.each(["title","description"],function(i,type){var elem=self.$("info-"+type);if(!!data[type]){elem[data[type].length?"show":"hide"]().html(data[type])}else{elem.empty().hide()}});return this},hasInfo:function(index){var check="title description".split(" "),i;for(i=0;check[i];i++){if(!!this.getData(index)[check[i]]){return true}}return false},jQuery:function(str){var self=this,ret=[];$.each(str.split(","),function(i,elemId){elemId=$.trim(elemId);if(self.get(elemId)){ret.push(elemId)}});var jQ=$(self.get(ret.shift()));$.each(ret,function(i,elemId){jQ=jQ.add(self.get(elemId))});return jQ},$:function(str){return this.jQuery.apply(this,Utils.array(arguments))}};$.each(_events,function(i,ev){var type=/_/.test(ev)?ev.replace(/_/g,""):ev;Galleria[ev.toUpperCase()]="galleria."+type});$.extend(Galleria,{IE9:IE===9,IE8:IE===8,IE7:IE===7,IE6:IE===6,IE:IE,WEBKIT:/webkit/.test(NAV),CHROME:/chrome/.test(NAV),SAFARI:/safari/.test(NAV)&&!/chrome/.test(NAV),QUIRK:IE&&doc.compatMode&&doc.compatMode==="BackCompat",MAC:/mac/.test(navigator.platform.toLowerCase()),OPERA:!!window.opera,IPHONE:/iphone/.test(NAV),IPAD:/ipad/.test(NAV),ANDROID:/android/.test(NAV),TOUCH:"ontouchstart"in doc});Galleria.addTheme=function(theme){if(!theme.name){Galleria.raise("No theme name specified")}if(typeof theme.defaults!=="object"){theme.defaults={}}else{theme.defaults=_legacyOptions(theme.defaults)}var css=false,reg;if(typeof theme.css==="string"){$("link").each(function(i,link){reg=new RegExp(theme.css);if(reg.test(link.href)){css=true;_themeLoad(theme);return false}});if(!css){$(function(){var retryCount=0;var tryLoadCss=function(){$("script").each(function(i,script){reg=new RegExp("galleria\\."+theme.name.toLowerCase()+"\\.");if(reg.test(script.src)){css=script.src.replace(/[^\/]*$/,"")+theme.css;window.setTimeout(function(){Utils.loadCSS(css,"galleria-theme-"+theme.name,function(){_themeLoad(theme)})},1)}});if(!css){if(retryCount++>5){Galleria.raise("No theme CSS loaded")}else{window.setTimeout(tryLoadCss,500)}}};tryLoadCss()})}}else{_themeLoad(theme)}return theme};Galleria.loadTheme=function(src,options){if($("script").filter(function(){return $(this).attr("src")==src}).length){return}var loaded=false,err;$(window).load(function(){if(!loaded){err=window.setTimeout(function(){if(!loaded){Galleria.raise("Galleria had problems loading theme at "+src+". Please check theme path or load manually.",true)}},2e4)}});Utils.loadScript(src,function(){loaded=true;window.clearTimeout(err)});return Galleria};Galleria.get=function(index){if(!!_instances[index]){return _instances[index]}else if(typeof index!=="number"){return _instances}else{Galleria.raise("Gallery index "+index+" not found")}};Galleria.configure=function(key,value){var opts={};if(typeof key=="string"&&value){opts[key]=value;key=opts}else{$.extend(opts,key)}Galleria.configure.options=opts;$.each(Galleria.get(),function(i,instance){instance.setOptions(opts)});return Galleria};Galleria.configure.options={};Galleria.on=function(type,callback){if(!type){return}callback=callback||F;var hash=type+callback.toString().replace(/\s/g,"")+Utils.timestamp();$.each(Galleria.get(),function(i,instance){instance._binds.push(hash);instance.bind(type,callback)});Galleria.on.binds.push({type:type,callback:callback,hash:hash});return Galleria};Galleria.on.binds=[];Galleria.run=function(selector,options){if($.isFunction(options)){options={extend:options}}$(selector||"#galleria").galleria(options);return Galleria};Galleria.addTransition=function(name,fn){_transitions.effects[name]=fn;return Galleria};Galleria.utils=Utils;Galleria.log=function(){var args=Utils.array(arguments);if("console"in window&&"log"in window.console){try{return window.console.log.apply(window.console,args)}catch(e){$.each(args,function(){window.console.log(this)})}}else{return window.alert(args.join(" "))}};Galleria.ready=function(fn){if(typeof fn!="function"){return Galleria}$.each(_galleries,function(i,gallery){fn.call(gallery,gallery._options)});Galleria.ready.callbacks.push(fn);return Galleria};Galleria.ready.callbacks=[];Galleria.raise=function(msg,fatal){var type=fatal?"Fatal error":"Error",css={color:"#fff",position:"absolute",top:0,left:0,zIndex:1e5},echo=function(msg){var html=''+(fatal?""+type+": ":"")+msg+"
";$.each(_instances,function(){var cont=this.$("errors"),target=this.$("target");if(!cont.length){target.css("position","relative");cont=this.addElement("errors").appendChild("target","errors").$("errors").css(css)}cont.append(html)});if(!_instances.length){$("").css($.extend(css,{position:"fixed"})).append(html).appendTo(DOM().body)}};if(DEBUG){echo(msg);if(fatal){throw new Error(type+": "+msg)}}else if(fatal){if(_hasError){return}_hasError=true;fatal=false;echo("Gallery could not load.")}};Galleria.version=VERSION;Galleria.getLoadedThemes=function(){return $.map(_loadedThemes,function(theme){return theme.name})};Galleria.requires=function(version,msg){msg=msg||"You need to upgrade Galleria to version "+version+" to use one or more components.";if(Galleria.version
",{src:src,frameborder:0,id:id,allowfullscreen:true,css:{visibility:"hidden"}})[0];if(size){$(iframe).css(size)}$(this.container).find("iframe,img").remove();this.container.appendChild(this.image);$("#"+id).load(function(self,callback){return function(){window.setTimeout(function(){$(self.image).css("visibility","visible");if(typeof callback=="function"){callback.call(self,self)}},10)}}(this,callback));return this.container}this.image=new Image;if(Galleria.IE8){$(this.image).css("filter","inherit")}if(!Galleria.IE&&!Galleria.CHROME&&!Galleria.SAFARI){$(this.image).css("image-rendering","optimizequality")}var reload=false,resort=false,$container=$(this.container),$image=$(this.image),onerror=function(){if(!reload){reload=true;window.setTimeout(function(image,src){return function(){image.attr("src",src+(src.indexOf("?")>-1?"&":"?")+Utils.timestamp())}}($(this),src),50)}else{if(DUMMY){$(this).attr("src",DUMMY)}else{Galleria.raise("Image not found: "+src)}}},onload=function(self,callback,src){return function(){var complete=function(){$(this).off("load");self.original=size||{height:this.height,width:this.width};if(Galleria.HAS3D){this.style.MozTransform=this.style.webkitTransform="translate3d(0,0,0)"}$container.append(this);self.cache[src]=src;if(typeof callback=="function"){window.setTimeout(function(){callback.call(self,self)},1)}};if(!this.width||!this.height){(function(img){Utils.wait({until:function(){return img.width&&img.height},success:function(){complete.call(img)},error:function(){if(!resort){$(new Image).load(onload).attr("src",img.src);resort=true}else{Galleria.raise("Could not extract width/height from image: "+img.src+". Traced measures: width:"+img.width+"px, height: "+img.height+"px.")}},timeout:100})})(this)}else{complete.call(this)}}}(this,callback,src);$container.find("iframe,img").remove();$image.css("display","block");Utils.hide(this.image);$.each("minWidth minHeight maxWidth maxHeight".split(" "),function(i,prop){$image.css(prop,/min/.test(prop)?"0":"none")});$image.load(onload).on("error",onerror).attr("src",src);return this.container},scale:function(options){var self=this;options=$.extend({width:0,height:0,min:undef,max:undef,margin:0,complete:F,position:"center",crop:false,canvas:false,iframelimit:undef},options);if(this.isIframe){var cw=options.width,ch=options.height,nw,nh;if(options.iframelimit){var r=M.min(options.iframelimit/cw,options.iframelimit/ch);if(r<1){nw=cw*r;nh=ch*r;$(this.image).css({top:ch/2-nh/2,left:cw/2-nw/2,position:"absolute"})}else{$(this.image).css({top:0,left:0})}}$(this.image).width(nw||cw).height(nh||ch).removeAttr("width").removeAttr("height");$(this.container).width(cw).height(ch);options.complete.call(self,self);try{if(this.image.contentWindow){$(this.image.contentWindow).trigger("resize")}}catch(e){}return this.container}if(!this.image){return this.container}var width,height,$container=$(self.container),data;Utils.wait({until:function(){width=options.width||$container.width()||Utils.parseValue($container.css("width"));height=options.height||$container.height()||Utils.parseValue($container.css("height"));return width&&height},success:function(){var newWidth=(width-options.margin*2)/self.original.width,newHeight=(height-options.margin*2)/self.original.height,min=M.min(newWidth,newHeight),max=M.max(newWidth,newHeight),cropMap={true:max,width:newWidth,height:newHeight,false:min,landscape:self.original.width>self.original.height?max:min,portrait:self.original.width0&&has3d!=="none"}();var requestFrame=function(){var r="RequestAnimationFrame";return window.requestAnimationFrame||window["webkit"+r]||window["moz"+r]||window["o"+r]||window["ms"+r]||function(callback){window.setTimeout(callback,1e3/60)}}();var Finger=function(elem,options){this.config={start:0,duration:500,onchange:function(){},oncomplete:function(){},easing:function(x,t,b,c,d){return-c*((t=t/d-1)*t*t*t-1)+b}};this.easeout=function(x,t,b,c,d){return c*((t=t/d-1)*t*t*t*t+1)+b};if(!elem.children.length){return}var self=this;$.extend(this.config,options);this.elem=elem;this.child=elem.children[0];this.to=this.pos=0;this.touching=false;this.start={};this.index=this.config.start;this.anim=0;this.easing=this.config.easing;if(!has3d){this.child.style.position="absolute";this.elem.style.position="relative"}$.each(["ontouchstart","ontouchmove","ontouchend","setup"],function(i,fn){self[fn]=function(caller){return function(){caller.apply(self,arguments)}}(self[fn])});this.setX=function(){var style=self.child.style;if(!has3d){style.left=self.pos+"px";return}style.MozTransform=style.webkitTransform=style.transform="translate3d("+self.pos+"px,0,0)";return};$(elem).on("touchstart",this.ontouchstart);$(window).on("resize",this.setup);$(window).on("orientationchange",this.setup);this.setup();(function animloop(){requestFrame(animloop);self.loop.call(self)})()};Finger.prototype={constructor:Finger,setup:function(){this.width=$(this.elem).width();this.length=M.ceil($(this.child).width()/this.width);if(this.index!==0){this.index=M.max(0,M.min(this.index,this.length-1));this.pos=this.to=-this.width*this.index}},setPosition:function(pos){this.pos=pos;this.to=pos},ontouchstart:function(e){var touch=e.originalEvent.touches;this.start={pageX:touch[0].pageX,pageY:touch[0].pageY,time:+new Date};this.isScrolling=null;this.touching=true;this.deltaX=0;$doc.on("touchmove",this.ontouchmove);$doc.on("touchend",this.ontouchend)},ontouchmove:function(e){var touch=e.originalEvent.touches;if(touch&&touch.length>1||e.scale&&e.scale!==1){return}this.deltaX=touch[0].pageX-this.start.pageX;if(this.isScrolling===null){this.isScrolling=!!(this.isScrolling||M.abs(this.deltaX)0||this.index==this.length-1&&this.deltaX<0?M.abs(this.deltaX)/this.width+1.8:1;this.to=this.deltaX-this.index*this.width}e.stopPropagation()},ontouchend:function(e){this.touching=false;var isValidSlide=+new Date-this.start.time<250&&M.abs(this.deltaX)>40||M.abs(this.deltaX)>this.width/2,isPastBounds=!this.index&&this.deltaX>0||this.index==this.length-1&&this.deltaX<0;if(!this.isScrolling){this.show(this.index+(isValidSlide&&!isPastBounds?this.deltaX<0?1:-1:0))}$doc.off("touchmove",this.ontouchmove);$doc.off("touchend",this.ontouchend)},show:function(index){if(index!=this.index){this.config.onchange.call(this,index)}else{this.to=-(index*this.width)}},moveTo:function(index){if(index!=this.index){this.pos=this.to=-(index*this.width);this.index=index}},loop:function(){var distance=this.to-this.pos,factor=1;if(this.width&&distance){factor=M.max(.5,M.min(1.5,M.abs(distance/this.width)))}if(this.touching||M.abs(distance)<=1){this.pos=this.to;distance=0;if(this.anim&&!this.touching){this.config.oncomplete(this.index)}this.anim=0;this.easing=this.config.easing}else{if(!this.anim){this.anim={start:this.pos,time:+new Date,distance:distance,factor:factor,destination:this.to}}var elapsed=+new Date-this.anim.time;var duration=this.config.duration*this.anim.factor;if(elapsed>duration||this.anim.destination!=this.to){this.anim=0;this.easing=this.easeout;return}this.pos=this.easing(null,elapsed,this.anim.start,this.anim.distance,duration)}this.setX()}};return Finger}();$.fn.galleria=function(options){var selector=this.selector;if(!$(this).length){$(function(){if($(selector).length){$(selector).galleria(options)}else{Galleria.utils.wait({until:function(){return $(selector).length},success:function(){$(selector).galleria(options)},error:function(){Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".')},timeout:5e3})}});return this}return this.each(function(){if($.data(this,"galleria")){$.data(this,"galleria").destroy();$(this).find("*").hide()}$.data(this,"galleria",(new Galleria).init(this,options))})};if(typeof module==="object"&&module&&typeof module.exports==="object"){module.exports=Galleria}else{window.Galleria=Galleria;if(typeof define==="function"&&define.amd){define("galleria",["jquery"],function(){return Galleria})}}})(jQuery,this);
\ No newline at end of file
diff --git a/Resources/public/js/vendor/galleria/galleria-1.4.5.js b/Resources/public/js/vendor/galleria/galleria.js
similarity index 99%
rename from Resources/public/js/vendor/galleria/galleria-1.4.5.js
rename to Resources/public/js/vendor/galleria/galleria.js
index 86366a3c..6e3a27f4 100644
--- a/Resources/public/js/vendor/galleria/galleria-1.4.5.js
+++ b/Resources/public/js/vendor/galleria/galleria.js
@@ -1,7 +1,8 @@
/**
- * Galleria v 1.4.5 2016-09-04
+ * Galleria v1.5.7 2017-05-10
* http://galleria.io
*
+ * Copyright (c) 2010 - 2016 worse is better UG
* Licensed under the MIT license
* https://raw.github.com/worseisbetter/galleria/master/LICENSE
*
@@ -20,7 +21,7 @@ var doc = window.document,
protoArray = Array.prototype,
// internal constants
- VERSION = 1.45,
+ VERSION = 1.57,
DEBUG = true,
TIMEOUT = 30000,
DUMMY = false,
@@ -30,6 +31,10 @@ var doc = window.document,
M = Math,
F = function(){},
FALSE = function() { return false; },
+ MOBILE = !(
+ ( window.screen.width > 1279 && window.devicePixelRatio == 1 ) || // there are not so many mobile devices with more than 1280px and pixelRatio equal to 1 (i.e. retina displays are equal to 2...)
+ ( window.screen.width > 1000 && window.innerWidth < (window.screen.width * .9) ) // this checks in the end if a user is using a resized browser window which is not common on mobile devices
+ ),
IE = (function() {
var v = 3,
@@ -868,7 +873,7 @@ var doc = window.document,
Utils.wait({
until: function() {
- return $loader.height() == 1;
+ return $loader.height() > 0;
},
success: function() {
$loader.remove();
@@ -1087,7 +1092,7 @@ $.event.special['click:fast'] = {
}).on('touchstart.fast', function(e) {
window.clearTimeout($(this).data('timer'));
$(this).data('clickstate', {
- touched: true,
+ touched: true,
touchdown: true,
coords: getCoords(e.originalEvent),
evObj: e
@@ -1095,9 +1100,9 @@ $.event.special['click:fast'] = {
}).on('touchmove.fast', function(e) {
var coords = getCoords(e.originalEvent),
state = $(this).data('clickstate'),
- distance = Math.max(
- Math.abs(state.coords.x - coords.x),
- Math.abs(state.coords.y - coords.y)
+ distance = Math.max(
+ Math.abs(state.coords.x - coords.x),
+ Math.abs(state.coords.y - coords.y)
);
if ( distance > 6 ) {
$(this).data('clickstate', $.extend(state, {
@@ -2757,7 +2762,7 @@ Galleria.prototype = {
// legacy patch
if( s === false || s == 'disabled' ) { return false; }
-
+
return !!Galleria.TOUCH;
}( options.swipe ));
@@ -3565,12 +3570,14 @@ Galleria.prototype = {
}
},
thumbload = $( thumb.container ).data( 'thumbload' );
- if ( thumb.video ) {
- thumbload.call( self, thumb, callback );
- } else {
- thumb.load( data.src , function( thumb ) {
- thumbload.call( self, thumb, callback );
- });
+ if (thumbload) {
+ if ( thumb.video ) {
+ thumbload.call( self, thumb, callback );
+ } else {
+ thumb.load( data.src , function( thumb ) {
+ thumbload.call( self, thumb, callback );
+ });
+ }
}
});
@@ -4022,7 +4029,7 @@ Galleria.prototype = {
this.clearTimer();
Utils.removeFromArray( _instances, this );
Utils.removeFromArray( _galleries, this );
- if ( Galleria._waiters.length ) {
+ if ( Galleria._waiters !== undefined && Galleria._waiters.length ) {
$.each( Galleria._waiters, function( i, w ) {
if ( w ) window.clearTimeout( w );
});
@@ -5654,7 +5661,7 @@ $.extend( Galleria, {
IPHONE: /iphone/.test( NAV ),
IPAD: /ipad/.test( NAV ),
ANDROID: /android/.test( NAV ),
- TOUCH: ('ontouchstart' in doc)
+ TOUCH: ( 'ontouchstart' in doc ) && MOBILE // rule out false positives on Win10
});
@@ -5682,6 +5689,11 @@ Galleria.addTheme = function( theme ) {
Galleria.raise('No theme name specified');
}
+ // make sure it's compatible
+ if ( !theme.version || parseInt(Galleria.version*10) > parseInt(theme.version*10) ) {
+ Galleria.raise('This version of Galleria requires '+theme.name+' theme version '+parseInt(Galleria.version*10)/10+' or later', true);
+ }
+
if ( typeof theme.defaults !== 'object' ) {
theme.defaults = {};
} else {
@@ -5689,7 +5701,7 @@ Galleria.addTheme = function( theme ) {
}
var css = false,
- reg;
+ reg, reg2;
if ( typeof theme.css === 'string' ) {
@@ -5723,8 +5735,8 @@ Galleria.addTheme = function( theme ) {
$('script').each(function (i, script) {
// look for the theme script
reg = new RegExp('galleria\\.' + theme.name.toLowerCase() + '\\.');
- if (reg.test(script.src)) {
-
+ reg2 = new RegExp('galleria\\.io\\/theme\\/' + theme.name.toLowerCase() + '\\/(\\d*\\.*)?(\\d*\\.*)?(\\d*\\/)?js');
+ if (reg.test(script.src) || reg2.test(script.src)) {
// we have a match
css = script.src.replace(/[^\/]*$/, '') + theme.css;
@@ -5779,7 +5791,7 @@ Galleria.loadTheme = function( src, options ) {
err;
// start listening for the timeout onload
- $( window ).load( function() {
+ $( window ).on('load', function() {
if ( !loaded ) {
// give it another 20 seconds
err = window.setTimeout(function() {
@@ -6156,7 +6168,7 @@ Galleria.Picture.prototype = {
*/
preload: function( src ) {
- $( new Image() ).load((function(src, cache) {
+ $( new Image() ).on( 'load', (function(src, cache) {
return function() {
cache[ src ] = src;
};
@@ -6200,7 +6212,7 @@ Galleria.Picture.prototype = {
this.container.appendChild( this.image );
- $('#'+id).load( (function( self, callback ) {
+ $('#'+id).on( 'load', (function( self, callback ) {
return function() {
window.setTimeout(function() {
$( self.image ).css( 'visibility', 'visible' );
@@ -6297,7 +6309,7 @@ Galleria.Picture.prototype = {
},
error: function() {
if ( !resort ) {
- $(new Image()).load( onload ).attr( 'src', img.src );
+ $(new Image()).on( 'load', onload ).attr( 'src', img.src );
resort = true;
} else {
Galleria.raise('Could not extract width/height from image: ' + img.src +
@@ -6328,7 +6340,7 @@ Galleria.Picture.prototype = {
});
// begin load and insert in cache when done
- $image.load( onload ).on( 'error', onerror ).attr( 'src', src );
+ $image.on( 'load', onload ).on( 'error', onerror ).attr( 'src', src );
// return the container
return this.container;
diff --git a/Resources/public/js/vendor/galleria/galleria.min.js b/Resources/public/js/vendor/galleria/galleria.min.js
new file mode 100644
index 00000000..cfda735c
--- /dev/null
+++ b/Resources/public/js/vendor/galleria/galleria.min.js
@@ -0,0 +1,13 @@
+/**
+ * Galleria - v1.5.7 2017-05-10
+ * https://galleria.io
+ *
+ * Copyright (c) 2010 - 2017 worse is better UG
+ * Licensed under the MIT License.
+ * https://raw.github.com/worseisbetter/galleria/master/LICENSE
+ *
+ */
+
+!function(a,b,c,d){var e=b.document,f=a(e),g=a(b),h=Array.prototype,i=1.57,j=!0,k=3e4,l=!1,m=navigator.userAgent.toLowerCase(),n=b.location.hash.replace(/#\//,""),o="file:"==b.location.protocol?"http:":b.location.protocol,p=Math,q=function(){},r=function(){return!1},s=!(b.screen.width>1279&&1==b.devicePixelRatio||b.screen.width>1e3&&b.innerWidth<.9*b.screen.width),t=function(){var a=3,b=e.createElement("div"),c=b.getElementsByTagName("i");do b.innerHTML="";while(c[0]);return a>4?a:e.documentMode||d}(),u=function(){return{html:e.documentElement,body:e.body,head:e.getElementsByTagName("head")[0],title:e.title}},v=b.parent!==b.self,w="data ready thumbnail loadstart loadfinish image play pause progress fullscreen_enter fullscreen_exit idle_enter idle_exit rescale lightbox_open lightbox_close lightbox_image",x=function(){var b=[];return a.each(w.split(" "),function(a,c){b.push(c),/_/.test(c)&&b.push(c.replace(/_/g,""))}),b}(),y=function(b){var c;return"object"!=typeof b?b:(a.each(b,function(d,e){/^[a-z]+_/.test(d)&&(c="",a.each(d.split("_"),function(a,b){c+=a>0?b.substr(0,1).toUpperCase()+b.substr(1):b}),b[c]=e,delete b[d])}),b)},z=function(b){return a.inArray(b,x)>-1?c[b.toUpperCase()]:b},A={youtube:{reg:/https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i,embed:function(){return o+"//www.youtube.com/embed/"+this.id},get_thumb:function(a){return o+"//img.youtube.com/vi/"+this.id+"/default.jpg"},get_image:function(a){return o+"//img.youtube.com/vi/"+this.id+"/hqdefault.jpg"}},vimeo:{reg:/https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i,embed:function(){return o+"//player.vimeo.com/video/"+this.id},getUrl:function(){return o+"//vimeo.com/api/v2/video/"+this.id+".json?callback=?"},get_thumb:function(a){return a[0].thumbnail_medium},get_image:function(a){return a[0].thumbnail_large}},dailymotion:{reg:/https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/,embed:function(){return o+"//www.dailymotion.com/embed/video/"+this.id},getUrl:function(){return"https://api.dailymotion.com/video/"+this.id+"?fields=thumbnail_240_url,thumbnail_720_url&callback=?"},get_thumb:function(a){return a.thumbnail_240_url},get_image:function(a){return a.thumbnail_720_url}},_inst:[]},B=function(c,d){for(var e=0;e=h+d.timeout?(d.error(),!1):void c._waiters.push(g=b.setTimeout(i,10))};c._waiters.push(g=b.setTimeout(i,10))},toggleQuality:function(a,b){7!==t&&8!==t||!a||"IMG"!=a.nodeName.toUpperCase()||("undefined"==typeof b&&(b="nearest-neighbor"===a.style.msInterpolationMode),a.style.msInterpolationMode=b?"bicubic":"nearest-neighbor")},insertStyleTag:function(b,c){if(!c||!a("#"+c).length){var d=e.createElement("style");if(c&&(d.id=c),u().head.appendChild(d),d.styleSheet)d.styleSheet.cssText=b;else{var f=e.createTextNode(b);d.appendChild(f)}}},loadScript:function(b,c){var d=!1,e=a("
-
+
-
+
@@ -44,7 +44,7 @@ Galleria Flickr Plugin Demo
-
+
-
+
@@ -90,7 +90,7 @@ Galleria History Plugin
-
+
-
+
@@ -43,7 +43,7 @@ Galleria Picasa Plugin Demo
-->
+
+
+
+
+
+
+