Multiple ORMs for all database

This commit is contained in:
Nicolas Le Goff
2014-10-16 20:00:27 +02:00
parent 007d83fe57
commit 9a3e92ed9c
252 changed files with 2901 additions and 2417 deletions

View File

@@ -8,14 +8,14 @@ services:
- mysql
- memcached
- redis
- elasticsearch
before_script:
- node --version
- npm --version
- travis_retry npm install
- echo '' > ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini
- phpenv config-rm xdebug.ini
- sh -c 'if [ $(php -r "echo PHP_MINOR_VERSION;") -le 4 ]; then echo "extension = apc.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi;'
- echo 'session.cache_limiter = ""' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini
- echo 'extension="redis.so"' > ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/redis.ini
- echo 'extension="memcache.so"' > ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/memcache.ini
- echo 'extension="memcached.so"' > ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/memcached.ini
@@ -42,19 +42,17 @@ matrix:
- php: 5.6
script:
- travis_retry composer install --dev --prefer-source -vvv
- travis_retry grunt install-assets -vvv
- travis_retry composer install --optimize-autoloader --dev --prefer-source
- travis_retry grunt install-assets
- bin/developer assets:compile-less
- bin/developer system:uninstall
- bin/setup system:install --email=test@phraseanet.com --password=test --db-user=root --db-template=fr --db-password= --databox=db_test --appbox=ab_test --server-name=http://127.0.0.1 -y;
- sh -c " if [ '$SETUP_MODE' = 'update' ]; then
bin/setup system:install --email=test@phraseanet.com --password=test --db-user=root --db-template=fr --db-password= --databox=db_test --appbox=ab_test --server-name=http://127.0.0.1 -y -v;
bin/developer ini:reset --email=test@phraseanet.com --password=test --run-patches -v;
bin/developer ini:reset --email=test@phraseanet.com --password=test --run-patches --no-setup-dbs;
php resources/hudson/cleanupSubdefs.php;
fi"
- sh -c " if [ '$SETUP_MODE' = 'install' ]; then
bin/setup system:install --email=test@phraseanet.com --password=test --db-user=root --db-template=fr --db-password= --databox=db_test --appbox=ab_test --server-name=http://127.0.0.1 -y -v;
bin/developer ini:setup-tests-dbs -v;
fi"
- php resources/hudson/cleanupSubdefs.php
- bin/developer ini:setup-tests-dbs
- bin/developer phraseanet:regenerate-sqlite
- bin/developer phraseanet:generate-js-fixtures
- ./node_modules/.bin/grunt test
- bin/phpunit

View File

@@ -69,8 +69,8 @@ $cli = new CLI("
if ($cli['configuration.store']->isSetup()) {
$helpers = [
'db' => new ConnectionHelper($cli['EM']->getConnection()),
'em' => new EntityManagerHelper($cli['EM'])
'db' => new ConnectionHelper($cli['orm.em']->getConnection()),
'em' => new EntityManagerHelper($cli['orm.em'])
];
$helperSet = $cli['console']->getHelperSet();

View File

@@ -33,6 +33,7 @@
"dailymotion/sdk" : "~1.5",
"data-uri/data-uri" : "~0.1.0",
"doctrine/orm" : "~2.4.0",
"doctrine/dbal" : "~2.4.0",
"elasticsearch/elasticsearch" : "~1.0",
"facebook/php-sdk" : "~3.0",
"gedmo/doctrine-extensions" : "~2.3.0",
@@ -73,7 +74,8 @@
"vierbergenlars/php-semver" : "~2.1",
"zend/gdata" : "~1.12.1",
"doctrine/migrations" : "1.0.x-dev@dev",
"willdurand/negotiation" : "~1.3"
"willdurand/negotiation" : "~1.3",
"dflydev/doctrine-orm-service-provider" : "~1.0"
},
"require-dev": {
"phpunit/phpunit" : "~3.7",

188
composer.lock generated
View File

@@ -4,16 +4,22 @@
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "86aef118cbe2bc82e25dba935f07b8e4",
"hash": "08521ddcfec6abfd89f8f51837239233",
"packages": [
{
"name": "alchemy-fr/tcpdf-clone",
"version": "6.0.039",
"source": {
"type": "git",
"url": "https://github.com/alchemy-fr/tcpdf-clone",
"url": "https://github.com/alchemy-fr/tcpdf-clone.git",
"reference": "2ba0248a7187f1626df6c128750650416267f0e7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/alchemy-fr/tcpdf-clone/zipball/2ba0248a7187f1626df6c128750650416267f0e7",
"reference": "2ba0248a7187f1626df6c128750650416267f0e7",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
@@ -60,6 +66,10 @@
"qrcode",
"tcpdf"
],
"support": {
"source": "https://github.com/alchemy-fr/tcpdf-clone/tree/6.0.039",
"issues": "https://github.com/alchemy-fr/tcpdf-clone/issues"
},
"time": "2013-10-13 16:11:17"
},
{
@@ -103,7 +113,7 @@
"homepage": "http://www.lickmychip.com/"
},
{
"name": "Nicolas Le Goff",
"name": "nlegoff",
"email": "legoff.n@gmail.com"
},
{
@@ -545,6 +555,68 @@
],
"time": "2014-08-22 15:01:57"
},
{
"name": "dflydev/doctrine-orm-service-provider",
"version": "v1.0.6",
"source": {
"type": "git",
"url": "https://github.com/dflydev/dflydev-doctrine-orm-service-provider.git",
"reference": "a55b92ac5111b8cb2aca19623f10301bab373718"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/dflydev/dflydev-doctrine-orm-service-provider/zipball/a55b92ac5111b8cb2aca19623f10301bab373718",
"reference": "a55b92ac5111b8cb2aca19623f10301bab373718",
"shasum": ""
},
"require": {
"doctrine/orm": "~2.3",
"php": ">=5.3.3",
"pimple/pimple": "1.*@dev"
},
"require-dev": {
"cilex/cilex": "1.*@dev",
"cilex/console-service-provider": "@dev",
"silex/silex": "1.*@dev"
},
"suggest": {
"dflydev/psr0-resource-locator-service-provider": "1.0.*@dev"
},
"type": "library",
"autoload": {
"psr-0": {
"Dflydev\\Cilex\\Provider\\DoctrineOrm": "src",
"Dflydev\\Pimple\\Provider\\DoctrineOrm": "src",
"Dflydev\\Silex\\Provider\\DoctrineOrm": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Dragonfly Development Inc.",
"email": "info@dflydev.com",
"homepage": "http://dflydev.com"
},
{
"name": "Beau Simensen",
"email": "beau@dflydev.com",
"homepage": "http://beausimensen.com"
}
],
"description": "Doctrine ORM Service Provider",
"homepage": "http://dflydev.com/projects/doctrine-orm-service-provider/",
"keywords": [
"cilex",
"doctrine",
"orm",
"pimple",
"silex"
],
"time": "2014-07-24 19:35:45"
},
{
"name": "doctrine/annotations",
"version": "v1.2.1",
@@ -830,38 +902,30 @@
},
{
"name": "doctrine/dbal",
"version": "v2.5.0",
"version": "v2.4.4",
"source": {
"type": "git",
"url": "https://github.com/doctrine/dbal.git",
"reference": "71140662c0a954602e81271667b6e03d9f53ea34"
"reference": "a370e5b95e509a7809d11f3d280acfc9310d464b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/dbal/zipball/71140662c0a954602e81271667b6e03d9f53ea34",
"reference": "71140662c0a954602e81271667b6e03d9f53ea34",
"url": "https://api.github.com/repos/doctrine/dbal/zipball/a370e5b95e509a7809d11f3d280acfc9310d464b",
"reference": "a370e5b95e509a7809d11f3d280acfc9310d464b",
"shasum": ""
},
"require": {
"doctrine/common": ">=2.4,<2.6-dev",
"doctrine/common": "~2.4",
"php": ">=5.3.2"
},
"require-dev": {
"phpunit/phpunit": "4.*",
"symfony/console": "2.*"
"phpunit/phpunit": "3.7.*",
"symfony/console": "~2.0"
},
"suggest": {
"symfony/console": "For helpful console commands such as SQL execution and import of files."
},
"bin": [
"bin/doctrine-dbal"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.5.x-dev"
}
},
"autoload": {
"psr-0": {
"Doctrine\\DBAL\\": "lib/"
@@ -897,7 +961,7 @@
"persistence",
"queryobject"
],
"time": "2014-12-04 21:57:15"
"time": "2015-01-12 21:57:01"
},
{
"name": "doctrine/inflector",
@@ -1074,16 +1138,16 @@
},
{
"name": "doctrine/orm",
"version": "v2.4.6",
"version": "v2.4.7",
"source": {
"type": "git",
"url": "https://github.com/doctrine/doctrine2.git",
"reference": "bebacf79d8d4dae9168f0f9bc6811e6c2cb6a4d9"
"reference": "2bc4ff3cab2ae297bcd05f2e619d42e6a7ca9e68"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/doctrine2/zipball/bebacf79d8d4dae9168f0f9bc6811e6c2cb6a4d9",
"reference": "bebacf79d8d4dae9168f0f9bc6811e6c2cb6a4d9",
"url": "https://api.github.com/repos/doctrine/doctrine2/zipball/2bc4ff3cab2ae297bcd05f2e619d42e6a7ca9e68",
"reference": "2bc4ff3cab2ae297bcd05f2e619d42e6a7ca9e68",
"shasum": ""
},
"require": {
@@ -1143,7 +1207,7 @@
"database",
"orm"
],
"time": "2014-10-06 13:22:50"
"time": "2014-12-16 13:45:01"
},
{
"name": "elasticsearch/elasticsearch",
@@ -1207,13 +1271,13 @@
"version": "v1.0.0",
"source": {
"type": "git",
"url": "https://github.com/igorw/evenement",
"reference": "v1.0.0"
"url": "https://github.com/igorw/evenement.git",
"reference": "fa966683e7df3e5dd5929d984a44abfbd6bafe8d"
},
"dist": {
"type": "zip",
"url": "https://github.com/igorw/evenement/zipball/v1.0.0",
"reference": "v1.0.0",
"url": "https://api.github.com/repos/igorw/evenement/zipball/fa966683e7df3e5dd5929d984a44abfbd6bafe8d",
"reference": "fa966683e7df3e5dd5929d984a44abfbd6bafe8d",
"shasum": ""
},
"require": {
@@ -1240,19 +1304,19 @@
"keywords": [
"event-dispatcher"
],
"time": "2012-05-30 08:01:08"
"time": "2012-05-30 15:01:08"
},
{
"name": "facebook/php-sdk",
"version": "v3.2.3",
"source": {
"type": "git",
"url": "https://github.com/facebook/facebook-php-sdk.git",
"url": "https://github.com/facebookarchive/facebook-php-sdk.git",
"reference": "6714042fa2f5979d4c64c7d11fb4bcab16bdf6cb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/facebook/facebook-php-sdk/zipball/6714042fa2f5979d4c64c7d11fb4bcab16bdf6cb",
"url": "https://api.github.com/repos/facebookarchive/facebook-php-sdk/zipball/6714042fa2f5979d4c64c7d11fb4bcab16bdf6cb",
"reference": "6714042fa2f5979d4c64c7d11fb4bcab16bdf6cb",
"shasum": ""
},
@@ -1286,6 +1350,7 @@
"facebook",
"sdk"
],
"abandoned": "facebook/php-sdk-v4",
"time": "2013-11-19 23:11:14"
},
{
@@ -1370,16 +1435,16 @@
},
{
"name": "goodby/csv",
"version": "1.1.0",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/goodby/csv.git",
"reference": "da672802985d196cae767da29b11618a676496b0"
"reference": "66c376b3bd51bc90fd680bfdf3708c9a22b9d081"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/goodby/csv/zipball/da672802985d196cae767da29b11618a676496b0",
"reference": "da672802985d196cae767da29b11618a676496b0",
"url": "https://api.github.com/repos/goodby/csv/zipball/66c376b3bd51bc90fd680bfdf3708c9a22b9d081",
"reference": "66c376b3bd51bc90fd680bfdf3708c9a22b9d081",
"shasum": ""
},
"require": {
@@ -1423,7 +1488,7 @@
"export",
"import"
],
"time": "2013-11-22 19:10:34"
"time": "2015-01-14 03:58:50"
},
{
"name": "guzzle/guzzle",
@@ -2243,7 +2308,7 @@
],
"authors": [
{
"name": "Stephen Clay",
"name": "Steve Clay",
"email": "steve@mrclay.org",
"homepage": "http://www.mrclay.org/",
"role": "Developer"
@@ -2429,21 +2494,21 @@
"source": {
"type": "git",
"url": "https://github.com/romainneutron/Imagine-Silex-Service-Provider.git",
"reference": "0.1.2"
"reference": "a8a7862ae90419f2b23746cd8436c2310e4eb084"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/romainneutron/Imagine-Silex-Service-Provider/zipball/0.1.2",
"reference": "0.1.2",
"url": "https://api.github.com/repos/romainneutron/Imagine-Silex-Service-Provider/zipball/a8a7862ae90419f2b23746cd8436c2310e4eb084",
"reference": "a8a7862ae90419f2b23746cd8436c2310e4eb084",
"shasum": ""
},
"require": {
"imagine/imagine": "*",
"php": ">=5.3.3",
"silex/silex": ">=1.0,<2.0"
"silex/silex": "~1.0"
},
"require-dev": {
"symfony/browser-kit": ">=2.0,<3.0"
"symfony/browser-kit": "~2.0"
},
"type": "library",
"autoload": {
@@ -2957,7 +3022,7 @@
"metadata"
],
"support": {
"source": "https://github.com/alchemy-fr/PHPExiftool/tree/0.4.1-mwg-metadata-copy"
"source": "https://github.com/alchemy-fr/PHPExiftool/tree/dev"
},
"time": "2014-10-08 16:09:02"
},
@@ -3550,7 +3615,7 @@
},
{
"name": "Phraseanet Team",
"email": "support@alchemy.fr",
"email": "info@alchemy.fr",
"homepage": "http://www.phraseanet.com/"
}
],
@@ -3597,7 +3662,9 @@
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Chris Corbyn"
@@ -3821,12 +3888,12 @@
"source": {
"type": "git",
"url": "https://github.com/twigphp/Twig-extensions.git",
"reference": "c0ab818595338dd5569369bfce2552d02cec5d50"
"reference": "8cf4b9fe04077bd54fc73f4fde83347040c3b8cd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/twigphp/Twig-extensions/zipball/c0ab818595338dd5569369bfce2552d02cec5d50",
"reference": "c0ab818595338dd5569369bfce2552d02cec5d50",
"url": "https://api.github.com/repos/twigphp/Twig-extensions/zipball/8cf4b9fe04077bd54fc73f4fde83347040c3b8cd",
"reference": "8cf4b9fe04077bd54fc73f4fde83347040c3b8cd",
"shasum": ""
},
"require": {
@@ -4248,12 +4315,12 @@
"source": {
"type": "git",
"url": "https://github.com/minkphp/MinkBrowserKitDriver.git",
"reference": "63960c8fcad4529faad1ff33e950217980baa64c"
"reference": "aed8f4a596b79014a75254c3e337511c33e38cbd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/minkphp/MinkBrowserKitDriver/zipball/63960c8fcad4529faad1ff33e950217980baa64c",
"reference": "63960c8fcad4529faad1ff33e950217980baa64c",
"url": "https://api.github.com/repos/minkphp/MinkBrowserKitDriver/zipball/aed8f4a596b79014a75254c3e337511c33e38cbd",
"reference": "aed8f4a596b79014a75254c3e337511c33e38cbd",
"shasum": ""
},
"require": {
@@ -4354,12 +4421,12 @@
"source": {
"type": "git",
"url": "https://github.com/minkphp/MinkGoutteDriver.git",
"reference": "fa1b073b48761464feb0b05e6825da44b20118d8"
"reference": "2bf327b4166694ecaa8ae7f956cb6ae252ecf03e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/minkphp/MinkGoutteDriver/zipball/fa1b073b48761464feb0b05e6825da44b20118d8",
"reference": "fa1b073b48761464feb0b05e6825da44b20118d8",
"url": "https://api.github.com/repos/minkphp/MinkGoutteDriver/zipball/2bf327b4166694ecaa8ae7f956cb6ae252ecf03e",
"reference": "2bf327b4166694ecaa8ae7f956cb6ae252ecf03e",
"shasum": ""
},
"require": {
@@ -4406,12 +4473,12 @@
"source": {
"type": "git",
"url": "https://github.com/minkphp/MinkSelenium2Driver.git",
"reference": "bcf1b537de37db6db0822d9e7bd97e600fd7a476"
"reference": "8018fee80bf6573f909ece3e0dfc07d0eb352210"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/minkphp/MinkSelenium2Driver/zipball/bcf1b537de37db6db0822d9e7bd97e600fd7a476",
"reference": "bcf1b537de37db6db0822d9e7bd97e600fd7a476",
"url": "https://api.github.com/repos/minkphp/MinkSelenium2Driver/zipball/8018fee80bf6573f909ece3e0dfc07d0eb352210",
"reference": "8018fee80bf6573f909ece3e0dfc07d0eb352210",
"shasum": ""
},
"require": {
@@ -4464,12 +4531,12 @@
"source": {
"type": "git",
"url": "https://github.com/FriendsOfPHP/Goutte.git",
"reference": "06a5451288ffddd204b10fa6c6f9ab2b86dd515d"
"reference": "794b196e76bdd37b5155cdecbad311f0a3b07625"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/FriendsOfPHP/Goutte/zipball/06a5451288ffddd204b10fa6c6f9ab2b86dd515d",
"reference": "06a5451288ffddd204b10fa6c6f9ab2b86dd515d",
"url": "https://api.github.com/repos/FriendsOfPHP/Goutte/zipball/794b196e76bdd37b5155cdecbad311f0a3b07625",
"reference": "794b196e76bdd37b5155cdecbad311f0a3b07625",
"shasum": ""
},
"require": {
@@ -4967,6 +5034,7 @@
"behat/gherkin": 20
},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=5.4"
},

View File

@@ -129,7 +129,9 @@ use Alchemy\Phrasea\Twig\Fit;
use Alchemy\Phrasea\Twig\Camelize;
use Alchemy\Phrasea\Twig\BytesConverter;
use Alchemy\Phrasea\Utilities\CachedTranslator;
use Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider;
use FFMpeg\FFMpegServiceProvider;
use Gedmo\DoctrineExtensions as GedmoExtension;
use Monolog\Logger;
use Monolog\Processor\IntrospectionProcessor;
use Neutron\Silex\Provider\ImagineServiceProvider;
@@ -143,6 +145,7 @@ use PHPExiftool\PHPExiftoolServiceProvider;
use Silex\Application as SilexApplication;
use Silex\Application\UrlGeneratorTrait;
use Silex\Application\TranslationTrait;
use Silex\Provider\DoctrineServiceProvider;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\MonologServiceProvider;
use Silex\Provider\SessionServiceProvider;
@@ -157,7 +160,6 @@ use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Unoconv\UnoconvServiceProvider;
use XPDF\PdfToText;
use XPDF\XPDFServiceProvider;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
@@ -198,144 +200,77 @@ class Application extends SilexApplication
$this->environment = $environment;
$this->setupApplicationPaths($this);
$this['charset'] = 'UTF-8';
mb_internal_encoding($this['charset']);
!defined('JETON_MAKE_SUBDEF') ? define('JETON_MAKE_SUBDEF', 0x01) : '';
!defined('JETON_WRITE_META_DOC') ? define('JETON_WRITE_META_DOC', 0x02) : '';
!defined('JETON_WRITE_META_SUBDEF') ? define('JETON_WRITE_META_SUBDEF', 0x04) : '';
!defined('JETON_WRITE_META') ? define('JETON_WRITE_META', 0x06) : '';
$this->setupCharset();
$this->setupApplicationPaths();
$this->setupConstants();
$this['debug'] = $this->share(function (Application $app) {
return Application::ENV_PROD !== $app->getEnvironment();
});
if ($this['debug'] === true) {
if ($this['debug']) {
ini_set('log_errors', 'on');
ini_set('error_log', $this['root.path'].'/logs/php_error.log');
}
$this->register(new ConfigurationServiceProvider());
$this->register(new MonologServiceProvider());
$this->setupMonolog();
$this->register(new FilesystemServiceProvider());
$this->register(new CacheServiceProvider());
$this->register(new CacheConnectionServiceProvider());
$this->register(new PhraseanetServiceProvider());
$this->register(new ConfigurationTesterServiceProvider());
$this->register(new ORMServiceProvider());
$this->register(new DoctrineServiceProvider(), $this['dbs.service.conf']);
$this->setupDBAL();
$this->register(new DoctrineOrmServiceProvider(), $this['orm.service.conf']);
$this->setupOrms();
$this->register(new BasketMiddlewareProvider());
$this->register(new TokenMiddlewareProvider());
$this->register(new ApiApplicationMiddlewareProvider());
$this->register(new ACLServiceProvider());
$this->register(new APIServiceProvider());
$this->register(new AuthenticationManagerServiceProvider());
$this->register(new BorderManagerServiceProvider());
$this->register(new BrowserServiceProvider());
$this->register(new FilesystemServiceProvider());
$this->register(new ConfigurationServiceProvider());
$this->register(new ConfigurationTesterServiceProvider);
$this->register(new ConvertersServiceProvider());
$this->register(new CSVServiceProvider());
$this->register(new RegistrationServiceProvider());
$this->register(new CacheServiceProvider());
$this->register(new CacheConnectionServiceProvider());
$this->register(new ImagineServiceProvider());
$this->setUpImagine();
$this->register(new JMSSerializerServiceProvider());
$this->register(new FFMpegServiceProvider());
$this->register(new FeedServiceProvider());
$this->register(new FtpServiceProvider());
$this->register(new GeonamesServiceProvider());
$this['geonames.server-uri'] = $this->share(function (Application $app) {
return $app['conf']->get(['registry', 'webservices', 'geonames-server'], 'http://geonames.alchemyasp.com/');
});
$this->setupGeonames();
$this->register(new MediaAlchemystServiceProvider());
$this['media-alchemyst.configuration'] = $this->share(function (Application $app) {
$configuration = [];
foreach ([
'swftools.pdf2swf.binaries' => 'pdf2swf_binary',
'swftools.swfrender.binaries' => 'swf_render_binary',
'swftools.swfextract.binaries' => 'swf_extract_binary',
'unoconv.binaries' => 'unoconv_binary',
'mp4box.binaries' => 'mp4box_binary',
'gs.binaries' => 'ghostscript_binary',
'ffmpeg.ffmpeg.binaries' => 'ffmpeg_binary',
'ffmpeg.ffprobe.binaries' => 'ffprobe_binary',
'ffmpeg.ffmpeg.timeout' => 'ffmpeg_timeout',
'ffmpeg.ffprobe.timeout' => 'ffprobe_timeout',
'gs.timeout' => 'gs_timeout',
'mp4box.timeout' => 'mp4box_timeout',
'swftools.timeout' => 'swftools_timeout',
'unoconv.timeout' => 'unoconv_timeout',
] as $parameter => $key) {
if ($this['conf']->has(['main', 'binaries', $key])) {
$configuration[$parameter] = $this['conf']->get(['main', 'binaries', $key]);
}
}
$configuration['ffmpeg.threads'] = $app['conf']->get(['registry', 'executables', 'ffmpeg-threads']) ?: null;
$configuration['imagine.driver'] = $app['conf']->get(['registry', 'executables', 'imagine-driver']) ?: null;
return $configuration;
});
$this['media-alchemyst.logger'] = $this->share(function (Application $app) {
return $app['monolog'];
});
$this->setupMediaAlchemyst();
$this->register(new MediaVorusServiceProvider());
$this->register(new MonologServiceProvider());
$this['monolog.name'] = 'Phraseanet logger';
$this['monolog.handler'] = $this->share(function () {
return new NullHandler();
});
$this['monolog'] = $this->share($this->extend('monolog', function (Logger $monolog) {
$monolog->pushProcessor(new IntrospectionProcessor());
return $monolog;
}));
$this->register(new MP4BoxServiceProvider());
$this->register(new NotificationDelivererServiceProvider());
$this->register(new ORMServiceProvider());
$this->register(new RepositoriesServiceProvider());
$this->register(new ManipulatorServiceProvider());
$this->register(new InstallerServiceProvider());
$this->register(new PhraseanetServiceProvider());
$this->register(new PhraseaVersionServiceProvider());
$this->register(new PHPExiftoolServiceProvider());
$this->register(new RandomGeneratorServiceProvider());
$this->register(new ReCaptchaServiceProvider());
$this->register(new SubdefServiceProvider());
$this->register(new ZippyServiceProvider());
$this['recaptcha.public-key'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'webservices', 'captcha-enabled'])) {
return $app['conf']->get(['registry', 'webservices', 'recaptcha-public-key']);
}
});
$this['recaptcha.private-key'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'webservices', 'captcha-enabled'])) {
return $app['conf']->get(['registry', 'webservices', 'recaptcha-private-key']);
}
});
$this->setupRecaptacha();
$this->register(new SearchEngineServiceProvider());
$this->register(new SessionHandlerServiceProvider());
$this->register(new SessionServiceProvider(), [
'session.test' => $this->getEnvironment() === static::ENV_TEST,
'session.storage.options' => ['cookie_lifetime' => 0]
]);
$this['session.storage.test'] = $this->share(function ($app) {
return new MockArraySessionStorage();
});
$this['session.storage.handler'] = $this->share(function ($app) {
if (!$this['phraseanet.configuration-tester']->isInstalled()) {
return new NullSessionHandler();
}
return $this['session.storage.handler.factory']->create($app['conf']);
});
$this->setupSession();
$this->register(new SerializerServiceProvider());
$this->register(new ServiceControllerServiceProvider());
$this->register(new SwiftmailerServiceProvider());
$this->setupSwiftMailer();
$this->register(new TasksServiceProvider());
$this->register(new TemporaryFilesystemServiceProvider());
$this->register(new TokensServiceProvider());
@@ -344,180 +279,39 @@ class Application extends SilexApplication
'cache' => $this->share(function($app) {return $app['cache.path'].'/twig';}),
],
]);
$this->setupTwig();
$this->register(new TranslationServiceProvider(), [
'locale_fallbacks' => ['fr'],
'translator.cache-options' => [
'debug' => $this['debug'],
'cache_dir' => $this->share(function($app) {return $app['cache.path'].'/translations';}),
'cache_dir' => $this->share(function($app) {
return $app['cache.path'].'/translations';
}),
],
]);
$this['translator'] = $this->share($this->extend('translator', function (CachedTranslator $translator, $app) {
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.fr.xlf', 'fr', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.fr.xlf', 'fr', 'validators');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.en.xlf', 'en', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.en.xlf', 'en', 'validators');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.de.xlf', 'de', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.de.xlf', 'de', 'validators');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.nl.xlf', 'nl', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.nl.xlf', 'nl', 'validators');
return $translator;
}));
$this->setupTranslation();
$this->register(new FormServiceProvider());
$this['form.type.extensions'] = $this->share($this->extend('form.type.extensions', function ($extensions) {
$extensions[] = new HelpTypeExtension();
return $extensions;
}));
$this->setupTwig();
$this->setupForm();
$this->register(new UnoconvServiceProvider());
$this->register(new UrlGeneratorServiceProvider());
$this->setupUrlGenerator();
$this->register(new UnicodeServiceProvider());
$this->register(new ValidatorServiceProvider());
$this->register(new XPDFServiceProvider());
$this->setupXpdf();
$this->register(new FileServeServiceProvider());
$this->register(new ManipulatorServiceProvider());
$this->register(new PluginServiceProvider());
$this->register(new PhraseaEventServiceProvider());
$this->register(new ContentNegotiationServiceProvider());
$this->register(new LocaleServiceProvider());
$this->setupEventDispatcher();
$this['phraseanet.exception_handler'] = $this->share(function ($app) {
$handler = PhraseaExceptionHandler::register($app['debug']);
$handler->setTranslator($app['translator']);
return $handler;
});
$this['swiftmailer.transport'] = $this->share(function ($app) {
if ($app['conf']->get(['registry', 'email', 'smtp-enabled'])) {
$transport = new \Swift_Transport_EsmtpTransport(
$app['swiftmailer.transport.buffer'],
[$app['swiftmailer.transport.authhandler']],
$app['swiftmailer.transport.eventdispatcher']
);
$encryption = null;
if (in_array($app['conf']->get(['registry', 'email', 'smtp-secure-mode']), ['ssl', 'tls'])) {
$encryption = $app['conf']->get(['registry', 'email', 'smtp-secure-mode']);
}
$options = $app['swiftmailer.options'] = array_replace([
'host' => $app['conf']->get(['registry', 'email', 'smtp-host']),
'port' => $app['conf']->get(['registry', 'email', 'smtp-port']),
'username' => $app['conf']->get(['registry', 'email', 'smtp-user']),
'password' => $app['conf']->get(['registry', 'email', 'smtp-password']),
'encryption' => $encryption,
'auth_mode' => null,
], $app['swiftmailer.options']);
$transport->setHost($options['host']);
$transport->setPort($options['port']);
// tls or ssl
$transport->setEncryption($options['encryption']);
if ($app['conf']->get(['registry', 'email', 'smtp-auth-enabled'])) {
$transport->setUsername($options['username']);
$transport->setPassword($options['password']);
$transport->setAuthMode($options['auth_mode']);
}
} else {
$transport = new \Swift_Transport_MailTransport(
new \Swift_Transport_SimpleMailInvoker(),
$app['swiftmailer.transport.eventdispatcher']
);
}
return $transport;
});
$this['imagine.factory'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'executables', 'imagine-driver']) != '') {
return $app['conf']->get(['registry', 'executables', 'imagine-driver']);
}
if (class_exists('\Gmagick')) {
return 'gmagick';
}
if (class_exists('\Imagick')) {
return 'imagick';
}
if (extension_loaded('gd')) {
return 'gd';
}
throw new \RuntimeException('No Imagine driver available');
});
$app = $this;
$this['phraseanet.logger'] = $this->protect(function ($databox) use ($app) {
try {
return \Session_Logger::load($app, $databox);
} catch (\Exception_Session_LoggerNotFound $e) {
return \Session_Logger::create($app, $databox, $app['browser']);
}
});
$this['date-formatter'] = $this->share(function (Application $app) {
return new \phraseadate($app);
});
$this['xpdf.pdftotext'] = $this->share(
$this->extend('xpdf.pdftotext', function (PdfToText $pdftotext, Application $app) {
if ($app['conf']->get(['registry', 'executables', 'pdf-max-pages'])) {
$pdftotext->setPageQuantity($app['conf']->get(['registry', 'executables', 'pdf-max-pages']));
}
return $pdftotext;
})
);
$this['dispatcher'] = $this->share(
$this->extend('dispatcher', function ($dispatcher, Application $app) {
$dispatcher->addListener(KernelEvents::RESPONSE, [$app, 'addUTF8Charset'], -128);
$dispatcher->addSubscriber($app['phraseanet.logout-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.locale-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.content-negotiation-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.maintenance-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.cookie-disabler-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.session-manager-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.record-edit-subscriber']);
$dispatcher->addSubscriber(new PhraseaInstallSubscriber($app));
$dispatcher->addSubscriber(new FeedEntrySubscriber($app));
$dispatcher->addSubscriber(new RegistrationSubscriber($app));
$dispatcher->addSubscriber(new BridgeSubscriber($app));
$dispatcher->addSubscriber(new ExportSubscriber($app));
$dispatcher->addSubscriber(new OrderSubscriber($app));
$dispatcher->addSubscriber(new BasketSubscriber($app));
$dispatcher->addSubscriber(new LazaretSubscriber($app));
$dispatcher->addSubscriber(new ValidationSubscriber($app));
return $dispatcher;
})
);
$this['log.channels'] = ['monolog', 'task-manager.logger'];
$this->register(new LocaleServiceProvider());
$this->mount('/include/minify/', new Minifier());
$this->mount('/permalink/', new Permalink());
$this->mount('/lightbox/', new Lightbox());
$app['plugins.directory'] = $app->share(function () {
$dir = __DIR__ . '/../../../plugins';
if (is_dir($dir)) {
return realpath($dir);
}
return $dir;
});
}
/**
@@ -526,7 +320,7 @@ class Application extends SilexApplication
public function loadPlugins()
{
call_user_func(function ($app) {
require $app['plugins.directory'] . '/services.php';
require $app['plugin.path'] . '/services.php';
}, $this);
}
@@ -575,40 +369,13 @@ class Application extends SilexApplication
return $this->redirect($this->url($route, $parameters));
}
public function addUTF8Charset(FilterResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$event->getResponse()->setCharset('UTF-8');
}
private function setupUrlGenerator()
{
$this['url_generator'] = $this->share($this->extend('url_generator', function ($urlGenerator, $app) {
if ($app['configuration.store']->isSetup()) {
$data = parse_url($app['conf']->get('servername'));
if (isset($data['scheme'])) {
$urlGenerator->getContext()->setScheme($data['scheme']);
}
if (isset($data['host'])) {
$urlGenerator->getContext()->setHost($data['host']);
}
}
return $urlGenerator;
}));
}
public function setupTwig()
{
$this['twig'] = $this->share(
$this->extend('twig', function ($twig, $app) {
$twig->setCache($app['cache.path'].'/twig');
$paths = require $app['plugins.directory'] . '/twig-paths.php';
$paths = require $app['plugin.path'] . '/twig-paths.php';
if ($app['browser']->isTablet() || $app['browser']->isMobile()) {
$paths[] = $app['root.path'] . '/config/templates/mobile';
@@ -831,6 +598,9 @@ class Application extends SilexApplication
return [];
}
/**
* Mount all controllers
*/
public function bindRoutes()
{
$this->mount('/', new Root());
@@ -897,6 +667,11 @@ class Application extends SilexApplication
$this->mount('/thesaurus', new Thesaurus());
$this->mount('/xmlhttp', new ThesaurusXMLHttp());
$this->mount('/include/minify/', new Minifier());
$this->mount('/permalink/', new Permalink());
$this->mount('/lightbox/', new Lightbox());
}
/**
@@ -919,38 +694,42 @@ class Application extends SilexApplication
return static::$flashTypes;
}
private function setupApplicationPaths(Application $app)
private function setupApplicationPaths()
{
// app root path
$this['root.path'] = realpath(__DIR__ . '/../../..');
// temporary resources default path such as download zip, quarantined documents etc ..
$this['tmp.path'] = $this['root.path'].'/tmp';
// plugin path
$this['plugin.path'] = $dir = $this['root.path'].'/plugins';
// cache path for dev env
$this['cache.dev.path'] = $app->share(function() use ($app) {
$path = sys_get_temp_dir().'/'.md5($app['root.path']);
$this['cache.dev.path'] = $this->share(function() {
$path = sys_get_temp_dir().'/'.md5($this['root.path']);
// ensure path is created
$app['filesystem']->mkdir($path);
$this['filesystem']->mkdir($path);
return $path;
});
// cache path (twig, minify, translations, configuration, doctrine metas serializer metas, profiler etc ...)
$this['cache.path'] = $app->share(function() use ($app) {
// if ($app->getEnvironment() !== Application::ENV_PROD) {
$this['cache.path'] = $this->share(function() {
// if ($this->getEnvironment() !== Application::ENV_PROD) {
// return $this['cache.dev.path'];
// }
$path = $app['root.path'].'/cache';
if ($app['phraseanet.configuration']->isSetup()) {
$path = $app['conf']->get(['main', 'storage', 'cache'], $path);
$defaultPath = $path = $this['root.path'].'/cache';
if ($this['phraseanet.configuration']->isSetup()) {
$path = $this['conf']->get(['main', 'storage', 'cache'], $path);
}
$path = $path ?: $defaultPath;
// ensure path is created
$app['filesystem']->mkdir($path);
$this['filesystem']->mkdir($path);
return $path;
});
$app['cache.paths'] = $app->share(function() use ($app) {
$this['cache.paths'] = $this->share(function() {
return array(
self::ENV_DEV => $this['cache.path'],
self::ENV_TEST => $this['cache.path'],
@@ -959,51 +738,357 @@ class Application extends SilexApplication
});
// log path
$this['log.path'] = $app->share(function() use ($app) {
$path = $this['root.path'].'/logs';
if ($app['phraseanet.configuration']->isSetup()) {
return $app['conf']->get(['main', 'storage', 'log'], $path);
$this['log.path'] = $this->share(function() {
$defaultPath = $path = $this['root.path'].'/logs';
if ($this['phraseanet.configuration']->isSetup()) {
return $this['conf']->get(['main', 'storage', 'log'], $path);
}
$path = $path ?: $defaultPath;
// ensure path is created
$app['filesystem']->mkdir($path);
$this['filesystem']->mkdir($path);
return $path;
});
// temporary download file path (zip file)
$this['tmp.download.path'] = $app->share(function() use ($app) {
$path = $this['tmp.path'].'/download';
if ($app['phraseanet.configuration']->isSetup()) {
return $app['conf']->get(['main', 'storage', 'download'], $path);
$this['tmp.download.path'] = $this->share(function() {
$defaultPath = $path = $this['tmp.path'].'/download';
if ($this['phraseanet.configuration']->isSetup()) {
return $this['conf']->get(['main', 'storage', 'download'], $path);
}
$path = $path ?: $defaultPath;
// ensure path is created
$app['filesystem']->mkdir($path);
$this['filesystem']->mkdir($path);
return $path;
});
// quarantined file path
$this['tmp.lazaret.path'] = $app->share(function() use ($app) {
$path = $this['tmp.path'].'/lazaret';
if ($app['phraseanet.configuration']->isSetup()) {
return $app['conf']->get(['main', 'storage', 'quarantine'], $path);
$this['tmp.lazaret.path'] = $this->share(function() {
$defaultPath = $path = $this['tmp.path'].'/lazaret';
if ($this['phraseanet.configuration']->isSetup()) {
return $this['conf']->get(['main', 'storage', 'quarantine'], $path);
}
$path = $path ?: $defaultPath;
// ensure path is created
$app['filesystem']->mkdir($path);
$this['filesystem']->mkdir($path);
return $path;
});
// document caption file path
$this['tmp.caption.path'] = $app->share(function() use ($app) {
$path = $this['tmp.path'].'/caption';
if ($app['phraseanet.configuration']->isSetup()) {
return $app['conf']->get(['main', 'storage', 'caption'], $path);
$this['tmp.caption.path'] = $this->share(function() {
$defaultPath = $path = $this['tmp.path'].'/caption';
if ($this['phraseanet.configuration']->isSetup()) {
return $this['conf']->get(['main', 'storage', 'caption'], $path);
}
$path = $path ?: $defaultPath;
// ensure path is created
$app['filesystem']->mkdir($path);
$this['filesystem']->mkdir($path);
return $path;
});
}
private function setupXpdf()
{
$this['xpdf.pdftotext'] = $this->share(
$this->extend('xpdf.pdftotext', function (PdfToText $pdftotext, Application $app) {
if ($app['conf']->get(['registry', 'executables', 'pdf-max-pages'])) {
$pdftotext->setPageQuantity($app['conf']->get(['registry', 'executables', 'pdf-max-pages']));
}
return $pdftotext;
})
);
}
private function setupForm()
{
$this['form.type.extensions'] = $this->share($this->extend('form.type.extensions', function ($extensions, Application $app) {
$extensions[] = new HelpTypeExtension();
return $extensions;
}));
}
private function setUpImagine()
{
$this['imagine.factory'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'executables', 'imagine-driver']) != '') {
return $app['conf']->get(['registry', 'executables', 'imagine-driver']);
}
if (class_exists('\Gmagick')) {
return 'gmagick';
}
if (class_exists('\Imagick')) {
return 'imagick';
}
if (extension_loaded('gd')) {
return 'gd';
}
throw new \RuntimeException('No Imagine driver available');
});
}
private function setupTranslation()
{
$this['translator'] = $this->share($this->extend('translator', function (CachedTranslator $translator, Application $app) {
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.fr.xlf', 'fr', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.fr.xlf', 'fr', 'validators');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.en.xlf', 'en', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.en.xlf', 'en', 'validators');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.de.xlf', 'de', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.de.xlf', 'de', 'validators');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/messages.nl.xlf', 'nl', 'messages');
$translator->addResource('xlf', __DIR__.'/../../../resources/locales/validators.nl.xlf', 'nl', 'validators');
return $translator;
}));
}
private function setupOrms()
{
$this['orm.ems'] = $this->share($this->extend('orm.ems', function ($ems, $app) {
GedmoExtension::registerAnnotations();
foreach ($ems->keys() as $key) {
$app['orm.annotation.register']($key);
$connection = $ems[$key]->getConnection();
$app['connection.pool.manager']->add($connection);
$types = $app['orm.ems.options'][$key]['types'];
$app['dbal.type.register']($connection, $types);
}
return $ems;
}));
}
private function setupSession()
{
$this['session.storage.test'] = $this->share(function (Application $app) {
return new MockArraySessionStorage();
});
$this['session.storage.handler'] = $this->share(function (Application $app) {
if (!$this['phraseanet.configuration-tester']->isInstalled()) {
return new NullSessionHandler();
}
return $this['session.storage.handler.factory']->create($app['conf']);
});
}
private function setupRecaptacha()
{
$this['recaptcha.public-key'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'webservices', 'captcha-enabled'])) {
return $app['conf']->get(['registry', 'webservices', 'recaptcha-public-key']);
}
});
$this['recaptcha.private-key'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'webservices', 'captcha-enabled'])) {
return $app['conf']->get(['registry', 'webservices', 'recaptcha-private-key']);
}
});
}
private function setupGeonames()
{
$this['geonames.server-uri'] = $this->share(function (Application $app) {
return $app['conf']->get(['registry', 'webservices', 'geonames-server'], 'http://geonames.alchemyasp.com/');
});
}
private function setupDBAL()
{
$this['dbs.config'] = $this->share($this->extend('dbs.config', function ($configs, $app) {
if ($app->getEnvironment() !== self::ENV_DEV) {
return $configs;
}
foreach($configs->keys() as $service) {
$app['dbal.config.register.loggers']($configs[$service]);
}
return $configs;
}));
$this['dbs.event_manager'] = $this->share($this->extend('dbs.event_manager', function ($eventManagers, $app) {
foreach ($eventManagers->keys() as $name) {
$app['dbal.evm.register.listeners']($eventManagers[$name]);
}
return $eventManagers;
}));
}
private function setupMediaAlchemyst()
{
$this['media-alchemyst.configuration'] = $this->share(function (Application $app) {
$configuration = [];
foreach ([
'swftools.pdf2swf.binaries' => 'pdf2swf_binary',
'swftools.swfrender.binaries' => 'swf_render_binary',
'swftools.swfextract.binaries' => 'swf_extract_binary',
'unoconv.binaries' => 'unoconv_binary',
'mp4box.binaries' => 'mp4box_binary',
'gs.binaries' => 'ghostscript_binary',
'ffmpeg.ffmpeg.binaries' => 'ffmpeg_binary',
'ffmpeg.ffprobe.binaries' => 'ffprobe_binary',
'ffmpeg.ffmpeg.timeout' => 'ffmpeg_timeout',
'ffmpeg.ffprobe.timeout' => 'ffprobe_timeout',
'gs.timeout' => 'gs_timeout',
'mp4box.timeout' => 'mp4box_timeout',
'swftools.timeout' => 'swftools_timeout',
'unoconv.timeout' => 'unoconv_timeout',
] as $parameter => $key) {
if ($this['conf']->has(['main', 'binaries', $key])) {
$configuration[$parameter] = $this['conf']->get(['main', 'binaries', $key]);
}
}
$configuration['ffmpeg.threads'] = $app['conf']->get(['registry', 'executables', 'ffmpeg-threads']) ?: null;
$configuration['imagine.driver'] = $app['conf']->get(['registry', 'executables', 'imagine-driver']) ?: null;
return $configuration;
});
$this['media-alchemyst.logger'] = $this->share(function (Application $app) {
return $app['monolog'];
});
}
private function setupUrlGenerator()
{
$this['url_generator'] = $this->share($this->extend('url_generator', function ($urlGenerator, Application $app) {
if ($app['configuration.store']->isSetup()) {
$data = parse_url($app['conf']->get('servername'));
if (isset($data['scheme'])) {
$urlGenerator->getContext()->setScheme($data['scheme']);
}
if (isset($data['host'])) {
$urlGenerator->getContext()->setHost($data['host']);
}
}
return $urlGenerator;
}));
}
private function setupSwiftMailer()
{
$this['swiftmailer.transport'] = $this->share(function (Application $app) {
if ($app['conf']->get(['registry', 'email', 'smtp-enabled'])) {
$transport = new \Swift_Transport_EsmtpTransport(
$app['swiftmailer.transport.buffer'],
[$app['swiftmailer.transport.authhandler']],
$app['swiftmailer.transport.eventdispatcher']
);
$encryption = null;
if (in_array($app['conf']->get(['registry', 'email', 'smtp-secure-mode']), ['ssl', 'tls'])) {
$encryption = $app['conf']->get(['registry', 'email', 'smtp-secure-mode']);
}
$options = $app['swiftmailer.options'] = array_replace([
'host' => $app['conf']->get(['registry', 'email', 'smtp-host']),
'port' => $app['conf']->get(['registry', 'email', 'smtp-port']),
'username' => $app['conf']->get(['registry', 'email', 'smtp-user']),
'password' => $app['conf']->get(['registry', 'email', 'smtp-password']),
'encryption' => $encryption,
'auth_mode' => null,
], $app['swiftmailer.options']);
$transport->setHost($options['host']);
$transport->setPort($options['port']);
// tls or ssl
$transport->setEncryption($options['encryption']);
if ($app['conf']->get(['registry', 'email', 'smtp-auth-enabled'])) {
$transport->setUsername($options['username']);
$transport->setPassword($options['password']);
$transport->setAuthMode($options['auth_mode']);
}
} else {
$transport = new \Swift_Transport_MailTransport(
new \Swift_Transport_SimpleMailInvoker(),
$app['swiftmailer.transport.eventdispatcher']
);
}
return $transport;
});
}
private function setupMonolog()
{
$this['monolog.name'] = 'phraseanet';
$this['monolog.handler'] = $this->share(function () {
return new NullHandler();
});
$this['monolog'] = $this->share($this->extend('monolog', function (Logger $logger) {
$logger->pushProcessor(new IntrospectionProcessor());
return $logger;
}));
}
private function setupEventDispatcher()
{
$this['dispatcher'] = $this->share(
$this->extend('dispatcher', function ($dispatcher, Application $app) {
//$dispatcher->addListener(KernelEvents::RESPONSE, [$app, 'addUTF8Charset'], -128);
$dispatcher->addSubscriber($app['phraseanet.logout-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.locale-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.content-negotiation-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.maintenance-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.cookie-disabler-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.session-manager-subscriber']);
$dispatcher->addSubscriber($app['phraseanet.record-edit-subscriber']);
$dispatcher->addSubscriber(new PhraseaInstallSubscriber($app));
$dispatcher->addSubscriber(new FeedEntrySubscriber($app));
$dispatcher->addSubscriber(new RegistrationSubscriber($app));
$dispatcher->addSubscriber(new BridgeSubscriber($app));
$dispatcher->addSubscriber(new ExportSubscriber($app));
$dispatcher->addSubscriber(new OrderSubscriber($app));
$dispatcher->addSubscriber(new BasketSubscriber($app));
$dispatcher->addSubscriber(new LazaretSubscriber($app));
$dispatcher->addSubscriber(new ValidationSubscriber($app));
return $dispatcher;
})
);
}
private function setupConstants()
{
if (!defined('JETON_MAKE_SUBDEF')) {
define('JETON_MAKE_SUBDEF', 0x01);
}
if (!defined('JETON_WRITE_META_DOC')) {
define('JETON_WRITE_META_DOC', 0x02);
}
if (!defined('JETON_WRITE_META_SUBDEF')) {
define('JETON_WRITE_META_SUBDEF', 0x04);
}
if (!defined('JETON_WRITE_META')) {
define('JETON_WRITE_META', 0x06);
}
}
private function setupCharset()
{
$this['charset'] = 'UTF-8';
mb_internal_encoding($this['charset']);
}
}

View File

@@ -68,7 +68,7 @@ return call_user_func(function ($environment = PhraseaApplication::ENV_PROD) {
if ($app['phraseanet.configuration-tester']->isInstalled()) {
$app->register(new DoctrineProfilerServiceProvider());
$app['db'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getConnection();
return $app['orm.em']->getConnection();
});
}
}

View File

@@ -129,7 +129,7 @@ class Manager
$visa = new Visa();
foreach ($this->checkers as $checker) {
$visa->addResponse($checker->check($this->app['EM'], $file));
$visa->addResponse($checker->check($this->app['orm.em'], $file));
}
return $visa;
@@ -361,7 +361,7 @@ class Manager
$lazaretFile->setSession($session);
$this->app['EM']->persist($lazaretFile);
$this->app['orm.em']->persist($lazaretFile);
foreach ($file->getAttributes() as $fileAttribute) {
$attribute = new LazaretAttribute();
@@ -370,7 +370,7 @@ class Manager
$attribute->setLazaretFile($lazaretFile);
$lazaretFile->addAttribute($attribute);
$this->app['EM']->persist($attribute);
$this->app['orm.em']->persist($attribute);
}
foreach ($visa->getResponses() as $response) {
@@ -382,11 +382,11 @@ class Manager
$lazaretFile->addCheck($check);
$this->app['EM']->persist($check);
$this->app['orm.em']->persist($check);
}
}
$this->app['EM']->flush();
$this->app['orm.em']->flush();
return $lazaretFile;
}

View File

@@ -137,7 +137,7 @@ class CLI extends Application
parent::loadPlugins();
call_user_func(function ($cli) {
require $cli['plugins.directory'] . '/commands.php';
require $cli['plugin.path'] . '/commands.php';
}, $this);
}
}

View File

@@ -49,11 +49,11 @@ class ComposerInstall extends Command
try {
if ($input->getOption('no-dev')) {
$output->write("Installing dependencies <info>without</info> developer packages ");
$output->write("Installing composer dependencies <info>without</info> developer packages ");
$composer->command(array_merge($commands, ['--no-dev']));
$output->writeln("<comment>OK</comment>");
} else {
$output->write("Installing dependencies <info>with</info> developer packages ");
$output->write("Installing composer dependencies <info>with</info> developer packages ");
$composer->command(array_merge($commands, ['--dev']));
$output->writeln("<comment>OK</comment>");
}

View File

@@ -36,6 +36,7 @@ class IniReset extends Command
->addOption('db-name', null, InputOption::VALUE_OPTIONAL, 'Databox name to reset, in case of multiple databox are mounted', null)
->addOption('dependencies', null, InputOption::VALUE_NONE, 'Fetch dependencies', null)
->addOption('run-patches', null, InputOption::VALUE_NONE, 'Reset in v3.1 states & apply all patches', null)
->addOption('no-setup-dbs', null, InputOption::VALUE_NONE, 'Do not create dbs for setup tests used in phpunit test suite', null)
;
}
@@ -114,7 +115,7 @@ class IniReset extends Command
// get data paths
$dataPath = $this->container['conf']->get(['main', 'storage', 'subdefs'], $this->container['root.path'].'/datas');
$schema = $this->container['EM']->getConnection()->getSchemaManager();
$schema = $this->container['orm.em']->getConnection()->getSchemaManager();
$output->writeln('Creating database "'.$dbs['ab'].'"...<info>OK</info>');
$schema->dropAndCreateDatabase($dbs['ab']);
$output->writeln('Creating database "'.$dbName.'"...<info>OK</info>');
@@ -176,6 +177,7 @@ class IniReset extends Command
$conf['main']['database']['port']
);
$process = new Process($cmd);
$process->setTimeout(300);
$process->run(function ($type, $buffer) {
if ('err' === $type) {
echo 'ERR > ' . $buffer;
@@ -206,26 +208,38 @@ class IniReset extends Command
$output->writeln('Mounting database "'.$databox->get_dbname().'"...<info>OK</info>');
}
$output->writeln('Upgrading from v3.1 to v'.Version::getNumber());
if ($input->getOption('run-patches') || false === $this->container['phraseanet.configuration']->isUpToDate()) {
if ($input->getOption('run-patches')) {
$output->write(sprintf('Upgrading... from version <info>3.1.21</info> to <info>%s</info>', Version::getNumber()), true);
} else {
$output->write(sprintf('Upgrading... from version <info>%s</info> to <info>%s</info>', $this->app['phraseanet.appbox']->get_version(), Version::getNumber()), true);
}
$cmd = 'php ' . __DIR__ . '/../../../../../bin/setup system:upgrade -y -f -v';
$process = new Process($cmd);
$process->setTimeout(600);
$process->run(function ($type, $buffer) {
if ('err' === $type) {
echo 'ERR > ' . $buffer;
}
});
})
;
if (false === $process->isSuccessful()) {
$output->writeln('<error>Failed to execute the following command "'.$cmd.'"</error>');
$output->writeln('<error>Failed to execute the following command "' . $cmd . '"</error>');
return 1;
}
}
if (!$input->getOption('no-setup-dbs')) {
// create setup dbs
$command = $this->getApplication()->find('ini:setup-tests-dbs');
$input = new ArrayInput(array(
'command' => 'ini:setup-tests-dbs'
));
$command->run($input, $output);
}
$this->container['conf']->set(['main', 'storage', 'subdefs'], $dataPath);

View File

@@ -30,12 +30,13 @@ class JsFixtures extends Command
protected function doExecute(InputInterface $input, OutputInterface $output)
{
$dbRefPath = sys_get_temp_dir() . '/db-ref.sqlite';
if (!file_exists($dbRefPath)) {
if (!file_exists($this->container['db.fixture.info']['path'])) {
throw new RuntimeException('You must generate sqlite db first, run "bin/console phraseanet:regenerate-sqlite" command.');
}
copy($dbRefPath, sys_get_temp_dir().'/db.sqlite');
$this->container['orm.em'] = $this->container->extend('orm.em', function($em, $app) {
return $app['orm.ems'][$app['db.fixture.hash.key']];
});
$sbasId = current($this->container['phraseanet.appbox']->get_databoxes())->get_sbas_id();
$this->writeResponse($output, 'GET', '/login/', '/home/login/index.html');
@@ -55,6 +56,7 @@ class JsFixtures extends Command
private function deleteUser(User $user)
{
$user = $this->container['orm.em']->find('Phraseanet:User', $user->getId());
$this->container['manipulator.user']->delete($user);
}
@@ -103,6 +105,9 @@ class JsFixtures extends Command
{
$environment = Application::ENV_TEST;
$app = require __DIR__ . '/../../Application/Root.php';
$app['orm.em'] = $app->extend('orm.em', function($em, $app) {
return $app['orm.ems'][$app['db.fixture.hash.key']];
});
$user = $this->createUser($app);

View File

@@ -25,7 +25,6 @@ use Alchemy\Phrasea\Model\Entities\FeedPublisher;
use Alchemy\Phrasea\Model\Entities\FeedToken;
use Alchemy\Phrasea\Model\Entities\LazaretSession;
use Alchemy\Phrasea\Model\Entities\Registration;
use Alchemy\Phrasea\Model\Entities\Session;
use Alchemy\Phrasea\Model\Entities\Task;
use Alchemy\Phrasea\Model\Entities\Token;
use Alchemy\Phrasea\Model\Entities\User;
@@ -36,7 +35,6 @@ use Alchemy\Phrasea\Model\Entities\UsrListOwner;
use Alchemy\Phrasea\Model\Entities\UsrList;
use Alchemy\Phrasea\Model\Entities\UsrListEntry;
use Alchemy\Phrasea\Model\Entities\StoryWZ;
use Alchemy\Phrasea\Core\Provider\ORMServiceProvider;
use Alchemy\Phrasea\Model\Entities\WebhookEvent;
use Alchemy\Phrasea\Model\Entities\WebhookEventDelivery;
use Alchemy\Phrasea\Model\Manipulator\TokenManipulator;
@@ -61,60 +59,55 @@ class RegenerateSqliteDb extends Command
{
$fs = new Filesystem();
$source = sys_get_temp_dir().'/db-ref.sqlite';
$target = sys_get_temp_dir().'/db-ref.sqlite.bkp';
$json = sys_get_temp_dir().'/fixtures.json';
$renamed = false;
$json = sprintf('%s/fixtures.json', sys_get_temp_dir());
if (is_file($source)) {
$renamed = true;
$fs->rename($source, $target, true);
if ($fs->exists($json)) {
$fs->remove($json);
}
try {
$dbParams = [
'driver' => 'pdo_sqlite',
'path' => $source,
'charset' => 'UTF8',
];
$this->container['orm.em'] = $this->container->extend('orm.em', function($em, $app) {
return $app['orm.ems'][$app['db.fixture.hash.key']];
});
$this->container->register(new ORMServiceProvider());
$this->container['EM.dbal-conf'] = $dbParams;
$em = $this->container['orm.em'];
$metadatas = $this->container['EM']->getMetadataFactory()->getAllMetadata();
$schemaTool = new SchemaTool($this->container['EM']);
$schemaTool->createSchema($metadatas);
if ($fs->exists($em->getConnection()->getParams()['path'])) {
$fs->remove($em->getConnection()->getParams()['path']);
}
$schemaTool = new SchemaTool($em);
$schemaTool->createSchema($em->getMetadataFactory()->getAllMetadata());
$fixtures = [];
$DI = new \Pimple();
$this->generateUsers($this->container['EM'], $DI);
$this->generateUsers($em, $DI);
$this->insertOauthApps($DI);
$this->insertOauthAccounts($DI);
$this->insertNativeApps();
$this->generateCollection($DI);
$this->generateRecord($DI);
$this->insertTwoTasks($this->container['EM']);
$this->insertTwoBasket($this->container['EM'], $DI);
$this->insertOneStoryInWz($this->container['EM'], $DI);
$this->insertUsrLists($this->container['EM'], $DI);
$this->insertOnePrivateFeed($this->container['EM'], $DI);
$this->insertOnePublicFeed($this->container['EM'], $DI);
$this->insertOneExtraFeed($this->container['EM'], $DI);
$this->insertOneAggregateToken($this->container['EM'], $DI);
$this->insertLazaretFiles($this->container['EM'], $DI);
$this->insertAuthFailures($this->container['EM'], $DI);
$this->insertOneRegistration($DI, $this->container['EM'], $DI['user_alt1'], $DI['coll'], 'now', 'registration_1');
$this->insertOneRegistration($DI, $this->container['EM'], $DI['user_alt2'], $DI['coll'], '-3 months', 'registration_2');
$this->insertOneRegistration($DI, $this->container['EM'], $DI['user_notAdmin'], $DI['coll'], 'now', 'registration_3');
$this->insertTwoTokens($this->container['EM'], $DI);
$this->insertOneInvalidToken($this->container['EM'], $DI);
$this->insertOneValidationToken($this->container['EM'], $DI);
$this->insertWebhookEvent($this->container['EM'], $DI);
$this->insertWebhookEventDelivery($this->container['EM'], $DI);
$this->insertTwoTasks($em);
$this->insertTwoBasket($em, $DI);
$this->insertOneStoryInWz($em, $DI);
$this->insertUsrLists($em, $DI);
$this->insertOnePrivateFeed($em, $DI);
$this->insertOnePublicFeed($em, $DI);
$this->insertOneExtraFeed($em, $DI);
$this->insertOneAggregateToken($em, $DI);
$this->insertLazaretFiles($em, $DI);
$this->insertAuthFailures($em, $DI);
$this->insertOneRegistration($DI, $em, $DI['user_alt1'], $DI['coll'], 'now', 'registration_1');
$this->insertOneRegistration($DI, $em, $DI['user_alt2'], $DI['coll'], '-3 months', 'registration_2');
$this->insertOneRegistration($DI, $em, $DI['user_notAdmin'], $DI['coll'], 'now', 'registration_3');
$this->insertTwoTokens($em, $DI);
$this->insertOneInvalidToken($em, $DI);
$this->insertOneValidationToken($em, $DI);
$this->insertWebhookEvent($em, $DI);
$this->insertWebhookEventDelivery($em, $DI);
$this->container['EM']->flush();
$em->flush();
$fixtures['basket']['basket_1'] = $DI['basket_1']->getId();
$fixtures['basket']['basket_2'] = $DI['basket_2']->getId();
@@ -178,16 +171,7 @@ class RegenerateSqliteDb extends Command
$fixtures['feed']['private']['token'] = $DI['feed_private_token']->getId();
$fixtures['webhook']['event'] = $DI['event_webhook_1']->getId();
} catch (\Exception $e) {
$output->writeln("<error>".$e->getMessage()."</error>");
if ($renamed) {
$fs->remove($source);
$fs->rename($target, $source);
}
throw $e;
}
$fs->remove($target);
$fs->dumpFile($json, json_encode($fixtures, defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0));
return 0;
@@ -195,25 +179,30 @@ class RegenerateSqliteDb extends Command
private function insertOauthApps(\Pimple $DI)
{
if (null === $DI['api-app-user'] = $this->container['repo.api-applications']->findOneByName('api-app-user')) {
$DI['api-app-user'] = $this->container['manipulator.api-application']->create(
'test application for user',
'test-web',
ApiApplication::WEB_TYPE,
'an api application description',
'',
'http://website.com/',
$DI['user'],
'http://callback.com/callback/'
);
}
if (null === $DI['api-app-user-not-admin'] = $this->container['repo.api-applications']->findOneByName('test-desktop')) {
$DI['api-app-user-not-admin'] = $this->container['manipulator.api-application']->create(
'test application for user',
'test-desktop',
ApiApplication::WEB_TYPE,
'an api application description',
'',
'http://website.com/',
$DI['user_notAdmin'],
'http://callback.com/callback/'
);
}
}
public function insertOauthAccounts(\Pimple $DI)
{
$DI['api-app-acc-user'] = $this->container['manipulator.api-account']->create($DI['api-app-user'], $DI['user']);

View File

@@ -44,22 +44,22 @@ class SetupTestsDbs extends Command
$dbs[] = $settings['database']['ab_name'];
$dbs[] = $settings['database']['db_name'];
$schema = $this->container['EM']->getConnection()->getSchemaManager();
$schema = $this->container['orm.em']->getConnection()->getSchemaManager();
foreach($dbs as $name) {
$output->writeln('Creating database "'.$name.'"...<info>OK</info>');
$schema->dropAndCreateDatabase($name);
}
$this->container['EM']->getConnection()->executeUpdate('
$this->container['orm.em']->getConnection()->executeUpdate('
GRANT ALL PRIVILEGES ON '.$settings['database']['ab_name'].'.* TO \''.$settings['database']['user'].'\'@\''.$settings['database']['host'].'\' IDENTIFIED BY \''.$settings['database']['password'].'\' WITH GRANT OPTION
');
$this->container['EM']->getConnection()->executeUpdate('
$this->container['orm.em']->getConnection()->executeUpdate('
GRANT ALL PRIVILEGES ON '.$settings['database']['db_name'].'.* TO \''.$settings['database']['user'].'\'@\''.$settings['database']['host'].'\' IDENTIFIED BY \''.$settings['database']['password'].'\' WITH GRANT OPTION
');
$this->container['EM']->getConnection()->executeUpdate('SET @@global.sql_mode= ""');
$this->container['orm.em']->getConnection()->executeUpdate('SET @@global.sql_mode= ""');
return 0;
}

View File

@@ -40,7 +40,7 @@ class AddPlugin extends AbstractPluginCommand
$manifest = $this->container['plugins.plugins-validator']->validatePlugin($temporaryDir);
$output->writeln(" <comment>OK</comment> found <info>".$manifest->getName()."</info>");
$targetDir = $this->container['plugins.directory'] . DIRECTORY_SEPARATOR . $manifest->getName();
$targetDir = $this->container['plugin.path'] . DIRECTORY_SEPARATOR . $manifest->getName();
$output->write("Setting up composer...");
$this->container['plugins.composer-installer']->install($temporaryDir);

View File

@@ -40,7 +40,7 @@ class RemovePlugin extends AbstractPluginCommand
$this->container['plugins.assets-manager']->remove($name);
$output->writeln(" <comment>OK</comment>");
$path = $this->container['plugins.directory'] . DIRECTORY_SEPARATOR . $name;
$path = $this->container['plugin.path'] . DIRECTORY_SEPARATOR . $name;
$output->write("Removing <info>$name</info>...");
$this->container['filesystem']->remove($path);

View File

@@ -83,7 +83,7 @@ class RecordAdd extends Command
$file = new File($this->container, $media, $collection, $originalName);
$session = new LazaretSession();
$this->container['EM']->persist($session);
$this->container['orm.em']->persist($session);
$forceBehavior = null;

View File

@@ -127,7 +127,7 @@ class Install extends Command
private function getABConn(InputInterface $input, OutputInterface $output, DialogHelper $dialog)
{
$abConn = null;
$abConn = $info = null;
if (!$input->getOption('appbox')) {
$output->writeln("\n<info>--- Database credentials ---</info>\n");
@@ -138,14 +138,15 @@ class Install extends Command
$dbPassword = $dialog->askHiddenResponse($output, "DB password (hidden) : ");
$abName = $dialog->ask($output, "DB name (phraseanet) : ", 'phraseanet');
try {
$abConn = $this->container['dbal.provider']->get([
$info = [
'host' => $hostname,
'port' => $port,
'user' => $dbUser,
'password' => $dbPassword,
'dbname' => $abName,
]);
];
try {
$abConn = $this->container['dbal.provider']($info);
$abConn->connect();
$output->writeln("\n\t<info>Application-Box : Connection successful !</info>\n");
} catch (\Exception $e) {
@@ -153,23 +154,31 @@ class Install extends Command
}
} while (!$abConn);
} else {
$abConn = $this->container['dbal.provider']->get([
$info = [
'host' => $input->getOption('db-host'),
'port' => $input->getOption('db-port'),
'user' => $input->getOption('db-user'),
'password' => $input->getOption('db-password'),
'dbname' => $input->getOption('appbox'),
]);
];
$abConn = $this->container['dbal.provider']($info);
$abConn->connect();
$output->writeln("\n\t<info>Application-Box : Connection successful !</info>\n");
}
// add dbs.option & orm.options services to use orm.em later
if ($abConn && $info) {
$this->container['dbs.options'] = array_merge($this->container['db.options.from_info']($info), $this->container['dbs.options']);
$this->container['orm.ems.options'] = array_merge($this->container['orm.em.options.from_info']($info), $this->container['orm.ems.options']);
}
return $abConn;
}
private function getDBConn(InputInterface $input, OutputInterface $output, Connection $abConn, DialogHelper $dialog)
{
$dbConn = $template = null;
$dbConn = $template = $info = null;
if (!$input->getOption('databox')) {
do {
$retry = false;
@@ -177,13 +186,15 @@ class Install extends Command
if ($dbName) {
try {
$dbConn = $this->container['dbal.provider']->get([
$info = [
'host' => $abConn->getHost(),
'port' => $abConn->getPort(),
'user' => $abConn->getUsername(),
'password' => $abConn->getPassword(),
'dbname' => $dbName,
]);
];
$dbConn = $this->container['dbal.provider']($info);
$dbConn->connect();
$output->writeln("\n\t<info>Data-Box : Connection successful !</info>\n");
@@ -200,18 +211,26 @@ class Install extends Command
}
} while ($retry);
} else {
$dbConn = $this->container['dbal.provider']->get([
$info = [
'host' => $input->getOption('db-host'),
'port' => $input->getOption('db-port'),
'user' => $input->getOption('db-user'),
'password' => $input->getOption('db-password'),
'dbname' => $input->getOption('databox'),
]);
];
$dbConn = $this->container['dbal.provider']($info);
$dbConn->connect();
$output->writeln("\n\t<info>Data-Box : Connection successful !</info>\n");
$template = $input->getOption('db-template') ? : 'en';
}
// add dbs.option & orm.options services to use orm.em later
if ($dbConn && $info) {
$this->container['dbs.options'] = array_merge($this->container['db.options.from_info']($info), $this->container['dbs.options']);
$this->container['orm.ems.options'] = array_merge($this->container['orm.em.options.from_info']($info), $this->container['orm.ems.options']);
}
return [$dbConn, $template];
}

View File

@@ -26,8 +26,8 @@ class PluginsReset extends Command
protected function doExecute(InputInterface $input, OutputInterface $output)
{
$this->container['filesystem']->remove($this->container['plugins.directory']);
$this->container['filesystem']->mirror(__DIR__ . '/../../../../conf.d/plugins', $this->container['plugins.directory']);
$this->container['filesystem']->remove($this->container['plugin.path']);
$this->container['filesystem']->mirror(__DIR__ . '/../../../../conf.d/plugins', $this->container['plugin.path']);
return 0;
}

View File

@@ -74,7 +74,7 @@ class TaskRun extends Command
$job->addSubscriber(new MemoryLimitSubscriber($maxMemory, $logger));
}
if ($task->isSingleRun()) {
$job->addSubscriber(new FinishedJobRemoverSubscriber($this->container['EM']));
$job->addSubscriber(new FinishedJobRemoverSubscriber($this->container['orm.em']));
}
$job->run(new JobData($this->container, $task));

View File

@@ -537,7 +537,6 @@ class Collection implements ControllerProviderInterface
$msg = $app->trans('Successful removal');
}
} catch (\Exception $e) {
}
if ('json' === $app['request']->getRequestFormat()) {

View File

@@ -47,7 +47,7 @@ class ConnectedUsers implements ControllerProviderInterface
$date = new \DateTime('-2 hours');
$params = ['date' => $date->format('Y-m-d h:i:s')];
$query = $app['EM']->createQuery($dql);
$query = $app['orm.em']->createQuery($dql);
$query->setParameters($params);
$sessions = $query->getResult();

View File

@@ -158,7 +158,7 @@ class Databoxes implements ControllerProviderInterface
$dataTemplate = new \SplFileInfo($app['root.path'] . '/lib/conf.d/data_templates/' . $dataTemplate . '.xml');
try {
$connbas = $app['dbal.provider']->get([
$connbas = $app['dbal.provider']([
'host' => $hostname,
'port' => $port,
'user' => $user,
@@ -175,6 +175,7 @@ class Databoxes implements ControllerProviderInterface
$base->registerAdmin($app['authentication']->getUser());
$app['acl']->get($app['authentication']->getUser())->delete_data_from_cache();
$connbas->close();
return $app->redirectPath('admin_database', ['databox_id' => $base->get_sbas_id(), 'success' => 1, 'reload-tree' => 1]);
} catch (\Exception $e) {
return $app->redirectPath('admin_databases', ['success' => 0, 'error' => 'base-failed']);
@@ -191,7 +192,7 @@ class Databoxes implements ControllerProviderInterface
try {
$data_template = new \SplFileInfo($app['root.path'] . '/lib/conf.d/data_templates/' . $dataTemplate . '.xml');
$connbas = $app['dbal.provider']->get([
$connbas = $app['db.provider']([
'host' => $hostname,
'port' => $port,
'user' => $userDb,

View File

@@ -67,10 +67,10 @@ class Publications implements ControllerProviderInterface
$publisher->setFeed($feed);
$app['EM']->persist($feed);
$app['EM']->persist($publisher);
$app['orm.em']->persist($feed);
$app['orm.em']->persist($publisher);
$app['EM']->flush();
$app['orm.em']->flush();
return $app->redirectPath('admin_feeds_list');
})->bind('admin_feeds_create');
@@ -101,8 +101,8 @@ class Publications implements ControllerProviderInterface
$feed->setSubtitle($request->request->get('subtitle', ''));
$feed->setCollection($collection);
$feed->setIsPublic('1' === $request->request->get('public'));
$app['EM']->persist($feed);
$app['EM']->flush();
$app['orm.em']->persist($feed);
$app['orm.em']->flush();
return $app->redirectPath('admin_feeds_list');
})->before(function (Request $request) use ($app) {
@@ -171,8 +171,8 @@ class Publications implements ControllerProviderInterface
unset($media);
$feed->setIconUrl(true);
$app['EM']->persist($feed);
$app['EM']->flush();
$app['orm.em']->persist($feed);
$app['orm.em']->flush();
$app['filesystem']->copy($tmpname, $app['root.path'] . '/config/feed_' . $feed->getId() . '.jpg');
$app['filesystem']->copy($tmpname, sprintf('%s/www/custom/feed_%d.jpg', $app['root.path'], $feed->getId()));
@@ -202,10 +202,10 @@ class Publications implements ControllerProviderInterface
$feed->addPublisher($publisher);
$app['EM']->persist($feed);
$app['EM']->persist($publisher);
$app['orm.em']->persist($feed);
$app['orm.em']->persist($publisher);
$app['EM']->flush();
$app['orm.em']->flush();
} catch (\Exception $e) {
$error = "An error occured";
}
@@ -230,8 +230,8 @@ class Publications implements ControllerProviderInterface
if ($feed->isPublisher($user) && !$feed->isOwner($user)) {
$feed->removePublisher($publisher);
$app['EM']->remove($publisher);
$app['EM']->flush();
$app['orm.em']->remove($publisher);
$app['orm.em']->flush();
}
} catch (\Exception $e) {
$error = "An error occured";
@@ -254,8 +254,8 @@ class Publications implements ControllerProviderInterface
unlink('custom/feed_' . $feed->getId() . '.jpg');
}
$app['EM']->remove($feed);
$app['EM']->flush();
$app['orm.em']->remove($feed);
$app['orm.em']->flush();
return $app->redirectPath('admin_feeds_list');
})

View File

@@ -30,10 +30,12 @@ class TaskManager implements ControllerProviderInterface
$app['firewall']->addMandatoryAuthentication($controllers);
$converter = function ($task) use ($app) {
return $app['converter.task']->convert($task);
};
$controllers->before(function (Request $request) use ($app) {
$app['firewall']->requireRight('taskmanager');
})->convert('task', function ($id) use ($app) {
return $app['converter.task']->convert($id);
});
$controllers
@@ -70,38 +72,47 @@ class TaskManager implements ControllerProviderInterface
$controllers
->get('/task/{task}/log', 'controller.admin.task:getTaskLog')
->convert('task', $converter)
->bind('admin_tasks_task_log');
$controllers
->post('/task/{task}/delete', 'controller.admin.task:postTaskDelete')
->convert('task', $converter)
->bind('admin_tasks_task_delete');
$controllers
->post('/task/{task}/start', 'controller.admin.task:postStartTask')
->convert('task', $converter)
->bind('admin_tasks_task_start');
$controllers
->post('/task/{task}/stop', 'controller.admin.task:postStopTask')
->convert('task', $converter)
->bind('admin_tasks_task_stop');
$controllers
->post('/task/{task}/resetcrashcounter', 'controller.admin.task:postResetCrashes')
->convert('task', $converter)
->bind('admin_tasks_task_reset');
$controllers
->post('/task/{task}/save', 'controller.admin.task:postSaveTask')
->convert('task', $converter)
->bind('admin_tasks_task_save');
$controllers
->post('/task/{task}/facility', 'controller.admin.task:postTaskFacility')
->convert('task', $converter)
->bind('admin_tasks_task_facility');
$controllers
->post('/task/{task}/xml-from-form', 'controller.admin.task:postXMLFromForm')
->convert('task', $converter)
->bind('admin_tasks_xml_from_form');
$controllers
->get('/task/{task}', 'controller.admin.task:getTask')
->convert('task', $converter)
->bind('admin_tasks_task_show');
$controllers

View File

@@ -648,7 +648,7 @@ class Users implements ControllerProviderInterface
}
$basList = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']));
$models = $app['EM.native-query']->getModelForUser($app['authentication']->getUser(), $basList);
$models = $app['orm.em.native-query']->getModelForUser($app['authentication']->getUser(), $basList);
return $app['twig']->render('/admin/user/import/view.html.twig', [
'nb_user_to_add' => $nbUsrToAdd,

View File

@@ -330,7 +330,7 @@ class V1 implements ControllerProviderInterface
*/
private function get_cache_info(Application $app)
{
$caches = ['main' => $app['cache'], 'op_code' => $app['opcode-cache'], 'doctrine_metadatas' => $app['EM']->getConfiguration()->getMetadataCacheImpl(), 'doctrine_query' => $app['EM']->getConfiguration()->getQueryCacheImpl(), 'doctrine_result' => $app['EM']->getConfiguration()->getResultCacheImpl(),];
$caches = ['main' => $app['cache'], 'op_code' => $app['opcode-cache'], 'doctrine_metadatas' => $app['orm.em']->getConfiguration()->getMetadataCacheImpl(), 'doctrine_query' => $app['orm.em']->getConfiguration()->getQueryCacheImpl(), 'doctrine_result' => $app['orm.em']->getConfiguration()->getResultCacheImpl(),];
$ret = [];
@@ -526,8 +526,8 @@ class V1 implements ControllerProviderInterface
$session = new LazaretSession();
$session->setUser($app['authentication']->getUser());
$app['EM']->persist($session);
$app['EM']->flush();
$app['orm.em']->persist($session);
$app['orm.em']->flush();
$reasons = $output = null;
@@ -767,7 +767,7 @@ class V1 implements ControllerProviderInterface
$that = $this;
$baskets = array_map(function (Basket $basket) use ($that, $app) {
return $that->list_basket($app, $basket);
}, (array) $app['phraseanet.appbox']->get_databox($databox_id)->get_record($record_id)->get_container_baskets($app['EM'], $app['authentication']->getUser()));
}, (array) $app['phraseanet.appbox']->get_databox($databox_id)->get_record($record_id)->get_container_baskets($app['orm.em'], $app['authentication']->getUser()));
$record = $app['phraseanet.appbox']->get_databox($databox_id)->get_record($record_id);
@@ -1038,8 +1038,8 @@ class V1 implements ControllerProviderInterface
$Basket->setUser($app['authentication']->getUser());
$Basket->setName($name);
$app['EM']->persist($Basket);
$app['EM']->flush();
$app['orm.em']->persist($Basket);
$app['orm.em']->flush();
return Result::create($request, ["basket" => $this->list_basket($app, $Basket)])->createResponse();
}
@@ -1054,8 +1054,8 @@ class V1 implements ControllerProviderInterface
*/
public function delete_basket(Application $app, Request $request, Basket $basket)
{
$app['EM']->remove($basket);
$app['EM']->flush();
$app['orm.em']->remove($basket);
$app['orm.em']->flush();
return $this->search_baskets($app, $request);
}
@@ -1145,8 +1145,8 @@ class V1 implements ControllerProviderInterface
{
$basket->setName($request->get('name'));
$app['EM']->persist($basket);
$app['EM']->flush();
$app['orm.em']->persist($basket);
$app['orm.em']->flush();
return Result::create($request, ["basket" => $this->list_basket($app, $basket)])->createResponse();
}
@@ -1163,8 +1163,8 @@ class V1 implements ControllerProviderInterface
{
$basket->setDescription($request->get('description'));
$app['EM']->persist($basket);
$app['EM']->flush();
$app['orm.em']->persist($basket);
$app['orm.em']->flush();
return Result::create($request, ["basket" => $this->list_basket($app, $basket)])->createResponse();
}

View File

@@ -63,8 +63,8 @@ class Baskets implements ControllerProviderInterface
try {
$repository = $app['repo.basket-elements'];
$basketElement = $repository->findUserElement($request->request->get('p0'), $app['authentication']->getUser());
$app['EM']->remove($basketElement);
$app['EM']->flush();
$app['orm.em']->remove($basketElement);
$app['orm.em']->flush();
} catch (\Exception $e) {
}
@@ -87,8 +87,8 @@ class Baskets implements ControllerProviderInterface
$basket = $app['converter.basket']->convert($request->request->get('courChuId'));
$app['acl.basket']->isOwner($basket, $app['authentication']->getUser());
$app['EM']->remove($basket);
$app['EM']->flush();
$app['orm.em']->remove($basket);
$app['orm.em']->flush();
unset($basket);
} catch (\Exception $e) {
@@ -113,8 +113,8 @@ class Baskets implements ControllerProviderInterface
$basket->setName($request->request->get('p0'));
$basket->setUser($app['authentication']->getUser());
$app['EM']->persist($basket);
$app['EM']->flush();
$app['orm.em']->persist($basket);
$app['orm.em']->flush();
} catch (\Exception $e) {
@@ -145,9 +145,9 @@ class Baskets implements ControllerProviderInterface
$basketElement->setBasket($basket);
$basket->addElement($basketElement);
$app['EM']->persist($basket);
$app['orm.em']->persist($basket);
$app['EM']->flush();
$app['orm.em']->flush();
} catch (\Exception $e) {
}

View File

@@ -211,15 +211,15 @@ class Lightbox implements ControllerProviderInterface
);
if ($basket->getIsRead() === false) {
$basket = $app['EM']->merge($basket);
$basket = $app['orm.em']->merge($basket);
$basket->setIsRead(true);
$app['EM']->flush();
$app['orm.em']->flush();
}
if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) {
$basket = $app['EM']->merge($basket);
$basket = $app['orm.em']->merge($basket);
$basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
$app['EM']->flush();
$app['orm.em']->flush();
}
$template = 'lightbox/validate.html.twig';
@@ -258,15 +258,15 @@ class Lightbox implements ControllerProviderInterface
);
if ($basket->getIsRead() === false) {
$basket = $app['EM']->merge($basket);
$basket = $app['orm.em']->merge($basket);
$basket->setIsRead(true);
$app['EM']->flush();
$app['orm.em']->flush();
}
if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) {
$basket = $app['EM']->merge($basket);
$basket = $app['orm.em']->merge($basket);
$basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
$app['EM']->flush();
$app['orm.em']->flush();
}
$template = 'lightbox/validate.html.twig';
@@ -348,9 +348,9 @@ class Lightbox implements ControllerProviderInterface
$validationDatas->setNote($note);
$app['EM']->merge($validationDatas);
$app['orm.em']->merge($validationDatas);
$app['EM']->flush();
$app['orm.em']->flush();
if ($app['browser']->isMobile()) {
$datas = $app['twig']->render('lightbox/sc_note.html.twig', ['basket_element' => $basket_element]);
@@ -408,9 +408,9 @@ class Lightbox implements ControllerProviderInterface
->getValidation()
->getParticipant($app['authentication']->getUser());
$app['EM']->merge($basket_element);
$app['orm.em']->merge($basket_element);
$app['EM']->flush();
$app['orm.em']->flush();
$releasable = false;
if ($participant->isReleasable() === true) {
@@ -468,8 +468,8 @@ class Lightbox implements ControllerProviderInterface
$participant->setIsConfirmed(true);
$app['EM']->merge($participant);
$app['EM']->flush();
$app['orm.em']->merge($participant);
$app['orm.em']->flush();
$datas = ['error' => false, 'datas' => $app->trans('Envoie avec succes')];
} catch (ControllerException $e) {

View File

@@ -95,13 +95,13 @@ class BasketController implements ControllerProviderInterface
{
if ($basket->getIsRead() === false) {
$basket->setIsRead(true);
$app['EM']->flush();
$app['orm.em']->flush();
}
if ($basket->getValidation()) {
if ($basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) {
$basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
$app['EM']->flush();
$app['orm.em']->flush();
}
}
@@ -121,7 +121,7 @@ class BasketController implements ControllerProviderInterface
$Basket->setUser($app['authentication']->getUser());
$Basket->setDescription($request->request->get('desc'));
$app['EM']->persist($Basket);
$app['orm.em']->persist($Basket);
$n = 0;
@@ -136,14 +136,14 @@ class BasketController implements ControllerProviderInterface
$basket_element->setRecord($record);
$basket_element->setBasket($Basket);
$app['EM']->persist($basket_element);
$app['orm.em']->persist($basket_element);
$Basket->addElement($basket_element);
$n++;
}
$app['EM']->flush();
$app['orm.em']->flush();
if ($request->getRequestFormat() === 'json') {
$data = [
@@ -162,8 +162,8 @@ class BasketController implements ControllerProviderInterface
public function deleteBasket(Application $app, Request $request, BasketEntity $basket)
{
$app['EM']->remove($basket);
$app['EM']->flush();
$app['orm.em']->remove($basket);
$app['orm.em']->flush();
$data = [
'success' => true
@@ -179,7 +179,7 @@ class BasketController implements ControllerProviderInterface
public function removeBasketElement(Application $app, Request $request, BasketEntity $basket, $basket_element_id)
{
$basketElement = $app['EM']->getRepository('Phraseanet:BasketElement')->find($basket_element_id);
$basketElement = $app['orm.em']->getRepository('Phraseanet:BasketElement')->find($basket_element_id);
$ord = $basketElement->getOrd();
foreach ($basket->getElements() as $basket_element) {
@@ -188,12 +188,12 @@ class BasketController implements ControllerProviderInterface
}
if ($basket_element->getId() === (int) $basket_element_id) {
$basket->removeElement($basket_element);
$app['EM']->remove($basket_element);
$app['orm.em']->remove($basket_element);
}
}
$app['EM']->persist($basket);
$app['EM']->flush();
$app['orm.em']->persist($basket);
$app['orm.em']->flush();
$data = ['success' => true, 'message' => $app->trans('Record removed from basket')];
@@ -212,8 +212,8 @@ class BasketController implements ControllerProviderInterface
$basket->setName($request->request->get('name', ''));
$basket->setDescription($request->request->get('description'));
$app['EM']->merge($basket);
$app['EM']->flush();
$app['orm.em']->merge($basket);
$app['orm.em']->flush();
$success = true;
$msg = $app->trans('Basket has been updated');
@@ -259,11 +259,11 @@ class BasketController implements ControllerProviderInterface
if (isset($order[$basketElement->getId()])) {
$basketElement->setOrd($order[$basketElement->getId()]);
$app['EM']->merge($basketElement);
$app['orm.em']->merge($basketElement);
}
}
$app['EM']->flush();
$app['orm.em']->flush();
$ret = ['success' => true, 'message' => $app->trans('Basket updated')];
} catch (\Exception $e) {
@@ -278,8 +278,8 @@ class BasketController implements ControllerProviderInterface
$basket->setArchived($archive_status);
$app['EM']->merge($basket);
$app['EM']->flush();
$app['orm.em']->merge($basket);
$app['orm.em']->flush();
if ($archive_status) {
$message = $app->trans('Basket has been archived');
@@ -314,7 +314,7 @@ class BasketController implements ControllerProviderInterface
$basket_element->setRecord($record);
$basket_element->setBasket($basket);
$app['EM']->persist($basket_element);
$app['orm.em']->persist($basket_element);
$basket->addElement($basket_element);
@@ -327,14 +327,14 @@ class BasketController implements ControllerProviderInterface
$validationData->setParticipant($participant);
$validationData->setBasketElement($basket_element);
$app['EM']->persist($validationData);
$app['orm.em']->persist($validationData);
}
}
$n++;
}
$app['EM']->flush();
$app['orm.em']->flush();
$data = [
'success' => true
@@ -365,7 +365,7 @@ class BasketController implements ControllerProviderInterface
$n++;
}
$app['EM']->flush();
$app['orm.em']->flush();
$data = ['success' => true, 'message' => $app->trans('%quantity% records moved', ['%quantity%' => $n])];

View File

@@ -190,8 +190,8 @@ class DoDownload implements ControllerProviderInterface
} else {
$list['complete'] = true;
$token->setData(serialize($list));
$app['em']->persist($token);
$app['em']->flush();
$app['orm.em']->persist($token);
$app['orm.em']->flush();
}
return $app->json([

View File

@@ -78,12 +78,12 @@ class Feed implements ControllerProviderInterface
->setRecordId($record->get_record_id())
->setSbasId($record->get_sbas_id());
$entry->addItem($item);
$app['EM']->persist($item);
$app['orm.em']->persist($item);
}
$app['EM']->persist($entry);
$app['EM']->persist($feed);
$app['EM']->flush();
$app['orm.em']->persist($entry);
$app['orm.em']->persist($feed);
$app['orm.em']->flush();
$app['dispatcher']->dispatch(PhraseaEvents::FEED_ENTRY_CREATE, new FeedEntryEvent($entry, $request->request->get('notify')));
@@ -159,11 +159,11 @@ class Feed implements ControllerProviderInterface
}
$item = $app['repo.feed-items']->find($item_sort_datas[0]);
$item->setOrd($item_sort_datas[1]);
$app['EM']->persist($item);
$app['orm.em']->persist($item);
}
$app['EM']->persist($entry);
$app['EM']->flush();
$app['orm.em']->persist($entry);
$app['orm.em']->flush();
return $app->json([
'error' => false,
@@ -190,8 +190,8 @@ class Feed implements ControllerProviderInterface
$app->abort(403, $app->trans('Action Forbidden : You are not the publisher'));
}
$app['EM']->remove($entry);
$app['EM']->flush();
$app['orm.em']->remove($entry);
$app['orm.em']->flush();
return $app->json(['error' => false, 'message' => 'succes']);
})
@@ -209,7 +209,7 @@ class Feed implements ControllerProviderInterface
$datas = $app['twig']->render('prod/feeds/feeds.html.twig', [
'feeds' => $feeds,
'feed' => new Aggregate($app['EM'], $feeds),
'feed' => new Aggregate($app['orm.em'], $feeds),
'page' => $page
]);
@@ -238,7 +238,7 @@ class Feed implements ControllerProviderInterface
$feeds = $app['repo.feeds']->getAllForUser($app['acl']->get($app['authentication']->getUser()));
$link = $app['feed.aggregate-link-generator']->generate(new Aggregate($app['EM'], $feeds),
$link = $app['feed.aggregate-link-generator']->generate(new Aggregate($app['orm.em'], $feeds),
$app['authentication']->getUser(),
AggregateLinkGenerator::FORMAT_RSS,
null, $renew

View File

@@ -244,8 +244,8 @@ class Lazaret implements ControllerProviderInterface
}
//Delete lazaret file
$app['EM']->remove($lazaretFile);
$app['EM']->flush();
$app['orm.em']->remove($lazaretFile);
$app['orm.em']->flush();
$ret['success'] = true;
} catch (\Exception $e) {
@@ -297,8 +297,8 @@ class Lazaret implements ControllerProviderInterface
$lazaretFileName = $app['tmp.lazaret.path'].'/'.$lazaretFile->getFilename();
$lazaretThumbFileName = $app['tmp.lazaret.path'].'/'.$lazaretFile->getThumbFilename();
$app['EM']->remove($lazaretFile);
$app['EM']->flush();
$app['orm.em']->remove($lazaretFile);
$app['orm.em']->flush();
try {
$app['filesystem']->remove([$lazaretFileName, $lazaretThumbFileName]);
@@ -323,16 +323,16 @@ class Lazaret implements ControllerProviderInterface
$lazaretFiles = $app['repo.lazaret-files']->findAll();
$app['EM']->beginTransaction();
$app['orm.em']->beginTransaction();
try {
foreach ($lazaretFiles as $lazaretFile) {
$this->denyLazaretFile($app, $lazaretFile);
}
$app['EM']->commit();
$app['orm.em']->commit();
$ret['success'] = true;
} catch (\Exception $e) {
$app['EM']->rollback();
$app['orm.em']->rollback();
$ret['message'] = $app->trans('An error occured');
}
@@ -402,8 +402,8 @@ class Lazaret implements ControllerProviderInterface
);
//Delete lazaret file
$app['EM']->remove($lazaretFile);
$app['EM']->flush();
$app['orm.em']->remove($lazaretFile);
$app['orm.em']->flush();
$ret['success'] = true;
} catch (\Exception $e) {

View File

@@ -124,7 +124,7 @@ class Order implements ControllerProviderInterface
$orderElement->setOrder($order);
$orderElement->setBaseId($record->get_base_id());
$orderElement->setRecordId($record->get_record_id());
$app['EM']->persist($orderElement);
$app['orm.em']->persist($orderElement);
}
}
@@ -145,8 +145,8 @@ class Order implements ControllerProviderInterface
try {
$app['dispatcher']->dispatch(PhraseaEvents::ORDER_CREATE, new OrderEvent($order));
$app['EM']->persist($order);
$app['EM']->flush();
$app['orm.em']->persist($order);
$app['orm.em']->flush();
$msg = $app->trans('The records have been properly ordered');
$success = true;
} catch (\Exception $e) {
@@ -242,8 +242,8 @@ class Order implements ControllerProviderInterface
$basket->setUser($order->getUser());
$basket->setPusher($app['authentication']->getUser());
$app['EM']->persist($basket);
$app['EM']->flush();
$app['orm.em']->persist($basket);
$app['orm.em']->flush();
}
$n = 0;
@@ -275,10 +275,10 @@ class Order implements ControllerProviderInterface
}
$success = true;
$app['EM']->persist($basket);
$app['EM']->persist($orderElement);
$app['EM']->persist($order);
$app['EM']->flush();
$app['orm.em']->persist($basket);
$app['orm.em']->persist($orderElement);
$app['orm.em']->persist($order);
$app['orm.em']->flush();
} catch (\Exception $e) {
}
@@ -320,7 +320,7 @@ class Order implements ControllerProviderInterface
$orderElement->setOrderMaster($app['authentication']->getUser());
$orderElement->setDeny(true);
$app['EM']->persist($orderElement);
$app['orm.em']->persist($orderElement);
$n++;
}
}
@@ -332,8 +332,8 @@ class Order implements ControllerProviderInterface
}
$success = true;
$app['EM']->persist($order);
$app['EM']->flush();
$app['orm.em']->persist($order);
$app['orm.em']->flush();
} catch (\Exception $e) {
}

View File

@@ -192,14 +192,14 @@ class Push implements ControllerProviderInterface
$Basket->setPusher($app['authentication']->getUser());
$Basket->setIsRead(false);
$app['EM']->persist($Basket);
$app['orm.em']->persist($Basket);
foreach ($pusher->get_elements() as $element) {
$BasketElement = new BasketElement();
$BasketElement->setRecord($element);
$BasketElement->setBasket($Basket);
$app['EM']->persist($BasketElement);
$app['orm.em']->persist($BasketElement);
$Basket->addElement($BasketElement);
@@ -218,7 +218,7 @@ class Push implements ControllerProviderInterface
}
}
$app['EM']->flush();
$app['orm.em']->flush();
$arguments = [
'basket' => $Basket->getId(),
@@ -238,7 +238,7 @@ class Push implements ControllerProviderInterface
$app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox())
->log($BasketElement->getRecord($app), \Session_Logger::EVENT_VALIDATE, $user_receiver->getId(), '');
$app['EM']->flush();
$app['orm.em']->flush();
$message = $app->trans('%quantity_records% records have been sent to %quantity_users% users', [
'%quantity_records%' => count($pusher->get_elements()),
@@ -264,7 +264,7 @@ class Push implements ControllerProviderInterface
'message' => $app->trans('Unable to send the documents')
];
$app['EM']->beginTransaction();
$app['orm.em']->beginTransaction();
try {
$pusher = new RecordHelper\Push($app, $app['request']);
@@ -291,21 +291,21 @@ class Push implements ControllerProviderInterface
$Basket->setUser($app['authentication']->getUser());
$Basket->setIsRead(false);
$app['EM']->persist($Basket);
$app['orm.em']->persist($Basket);
foreach ($pusher->get_elements() as $element) {
$BasketElement = new BasketElement();
$BasketElement->setRecord($element);
$BasketElement->setBasket($Basket);
$app['EM']->persist($BasketElement);
$app['orm.em']->persist($BasketElement);
$Basket->addElement($BasketElement);
}
$app['EM']->flush();
$app['orm.em']->flush();
}
$app['EM']->refresh($Basket);
$app['orm.em']->refresh($Basket);
if (!$Basket->getValidation()) {
$Validation = new ValidationSession();
@@ -320,7 +320,7 @@ class Push implements ControllerProviderInterface
}
$Basket->setValidation($Validation);
$app['EM']->persist($Validation);
$app['orm.em']->persist($Validation);
} else {
$Validation = $Basket->getValidation();
}
@@ -368,7 +368,7 @@ class Push implements ControllerProviderInterface
$validationParticipant->setCanAgree($participant['agree']);
$validationParticipant->setCanSeeOthers($participant['see_others']);
$app['EM']->persist($validationParticipant);
$app['orm.em']->persist($validationParticipant);
foreach ($Basket->getElements() as $BasketElement) {
$ValidationData = new ValidationData();
@@ -390,8 +390,8 @@ class Push implements ControllerProviderInterface
);
}
$app['EM']->merge($BasketElement);
$app['EM']->persist($ValidationData);
$app['orm.em']->merge($BasketElement);
$app['orm.em']->persist($ValidationData);
$app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox())
->log($BasketElement->getRecord($app), \Session_Logger::EVENT_PUSH, $participantUser->getId(), '');
@@ -399,9 +399,9 @@ class Push implements ControllerProviderInterface
$validationParticipant->addData($ValidationData);
}
$validationParticipant = $app['EM']->merge($validationParticipant);
$validationParticipant = $app['orm.em']->merge($validationParticipant);
$app['EM']->flush();
$app['orm.em']->flush();
$arguments = [
'basket' => $Basket->getId(),
@@ -419,9 +419,9 @@ class Push implements ControllerProviderInterface
$app['dispatcher']->dispatch(PhraseaEvents::VALIDATION_CREATE, new ValidationEvent($validationParticipant, $Basket, $url, $request->request->get('message'), $receipt, (int) $request->request->get('duration')));
}
$app['EM']->merge($Basket);
$app['EM']->merge($Validation);
$app['EM']->flush();
$app['orm.em']->merge($Basket);
$app['orm.em']->merge($Validation);
$app['orm.em']->flush();
$message = $app->trans('%quantity_records% records have been sent for validation to %quantity_users% users', [
'%quantity_records%' => count($pusher->get_elements()),
@@ -433,10 +433,10 @@ class Push implements ControllerProviderInterface
'message' => $message
];
$app['EM']->commit();
$app['orm.em']->commit();
} catch (ControllerException $e) {
$ret['message'] = $e->getMessage();
$app['EM']->rollback();
$app['orm.em']->rollback();
}
return $app->json($ret);

View File

@@ -122,7 +122,7 @@ class Records implements ControllerProviderInterface
]),
"others" => $app['twig']->render('prod/preview/appears_in.html.twig', [
'parents' => $record->get_grouping_parents(),
'baskets' => $record->get_container_baskets($app['EM'], $app['authentication']->getUser())
'baskets' => $record->get_container_baskets($app['orm.em'], $app['authentication']->getUser())
]),
"current" => $train,
"history" => $app['twig']->render('prod/preview/short_history.html.twig', [
@@ -164,14 +164,14 @@ class Records implements ControllerProviderInterface
$basketElements = $basketElementsRepository->findElementsByRecord($record);
foreach ($basketElements as $element) {
$app['EM']->remove($element);
$app['orm.em']->remove($element);
$deleted[] = $element->getRecord($app)->get_serialize_key();
}
$attachedStories = $StoryWZRepository->findByRecord($app, $record);
foreach ($attachedStories as $attachedStory) {
$app['EM']->remove($attachedStory);
$app['orm.em']->remove($attachedStory);
}
$deleted[] = $record->get_serialize_key();
@@ -181,7 +181,7 @@ class Records implements ControllerProviderInterface
}
}
$app['EM']->flush();
$app['orm.em']->flush();
return $app->json($deleted);
}

View File

@@ -80,9 +80,9 @@ class Story implements ControllerProviderInterface
$StoryWZ->setUser($app['authentication']->getUser());
$StoryWZ->setRecord($Story);
$app['EM']->persist($StoryWZ);
$app['orm.em']->persist($StoryWZ);
$app['EM']->flush();
$app['orm.em']->flush();
if ($request->getRequestFormat() == 'json') {
$data = [

View File

@@ -177,7 +177,7 @@ class Upload implements ControllerProviderInterface
$lazaretSession = new LazaretSession();
$lazaretSession->setUser($app['authentication']->getUser());
$app['EM']->persist($lazaretSession);
$app['orm.em']->persist($lazaretSession);
$packageFile = new File($app, $media, $collection, $file->getClientOriginalName());

View File

@@ -170,9 +170,9 @@ class UsrLists implements ControllerProviderInterface
$List->setName($list_name);
$List->addOwner($Owner);
$app['EM']->persist($Owner);
$app['EM']->persist($List);
$app['EM']->flush();
$app['orm.em']->persist($Owner);
$app['orm.em']->persist($List);
$app['orm.em']->flush();
$datas = [
'success' => true
@@ -261,7 +261,7 @@ class UsrLists implements ControllerProviderInterface
$list->setName($list_name);
$app['EM']->flush();
$app['orm.em']->flush();
$datas = [
'success' => true
@@ -290,8 +290,8 @@ class UsrLists implements ControllerProviderInterface
throw new ControllerException($app->trans('You are not authorized to do this'));
}
$app['EM']->remove($list);
$app['EM']->flush();
$app['orm.em']->remove($list);
$app['orm.em']->flush();
$datas = [
'success' => true
@@ -329,8 +329,8 @@ class UsrLists implements ControllerProviderInterface
$user_entry = $entry_repository->findEntryByListAndUsrId($list, $usr_id);
$app['EM']->remove($user_entry);
$app['EM']->flush();
$app['orm.em']->remove($user_entry);
$app['orm.em']->flush();
$datas = [
'success' => true
@@ -381,12 +381,12 @@ class UsrLists implements ControllerProviderInterface
$list->addEntrie($entry);
$app['EM']->persist($entry);
$app['orm.em']->persist($entry);
$inserted_usr_ids[] = $user_entry->getId();
}
$app['EM']->flush();
$app['orm.em']->flush();
if (count($inserted_usr_ids) > 1) {
$datas = [
@@ -476,14 +476,14 @@ class UsrLists implements ControllerProviderInterface
$list->addOwner($owner);
$app['EM']->persist($owner);
$app['orm.em']->persist($owner);
}
$role = $app['request']->request->get('role');
$owner->setRole($role);
$app['EM']->flush();
$app['orm.em']->flush();
$datas = [
'success' => true
@@ -521,8 +521,8 @@ class UsrLists implements ControllerProviderInterface
$owner = $owners_repository->findByListAndUsrId($list, $usr_id);
$app['EM']->remove($owner);
$app['EM']->flush();
$app['orm.em']->remove($owner);
$app['orm.em']->flush();
$datas = [
'success' => true

View File

@@ -150,11 +150,11 @@ class WorkZone implements ControllerProviderInterface
$StoryWZ->setUser($app['authentication']->getUser());
$StoryWZ->setRecord($Story);
$app['EM']->persist($StoryWZ);
$app['orm.em']->persist($StoryWZ);
$done++;
}
$app['EM']->flush();
$app['orm.em']->flush();
if ($alreadyFixed === 0) {
if ($done <= 1) {
@@ -192,8 +192,8 @@ class WorkZone implements ControllerProviderInterface
throw new NotFoundHttpException('Story not found');
}
$app['EM']->remove($StoryWZ);
$app['EM']->flush();
$app['orm.em']->remove($StoryWZ);
$app['orm.em']->flush();
if ($request->getRequestFormat() == 'json') {
return $app->json([

View File

@@ -267,7 +267,7 @@ class Account implements ControllerProviderInterface
WHERE s.user = :usr_id
ORDER BY s.created DESC';
$query = $app['EM']->createQuery($dql);
$query = $app['orm.em']->createQuery($dql);
$query->setMaxResults(100);
$query->setParameters(['usr_id' => $app['session']->get('usr_id')]);
$sessions = $query->getResult();
@@ -393,10 +393,10 @@ class Account implements ControllerProviderInterface
$ftpCredential->setReceptionFolder($request->request->get("form_destFTP"));
$ftpCredential->setRepositoryPrefixName($request->request->get("form_prefixFTPfolder"));
$app['EM']->persist($ftpCredential);
$app['EM']->persist($app['authentication']->getUser());
$app['orm.em']->persist($ftpCredential);
$app['orm.em']->persist($app['authentication']->getUser());
$app['EM']->flush();
$app['orm.em']->flush();
$app->addFlash('success', $app->trans('login::notification: Changements enregistres'));
}

View File

@@ -367,12 +367,12 @@ class Login implements ControllerProviderInterface
}
}
$app['EM']->persist($user);
$app['EM']->flush();
$app['orm.em']->persist($user);
$app['orm.em']->flush();
if (null !== $provider) {
$this->attachProviderToUser($app['EM'], $provider, $user);
$app['EM']->flush();
$this->attachProviderToUser($app['orm.em'], $provider, $user);
$app['orm.em']->flush();
}
$registrationsOK = [];
@@ -809,10 +809,10 @@ class Login implements ControllerProviderInterface
$app['dispatcher']->dispatch(PhraseaEvents::VALIDATION_REMINDER, new ValidationEvent($participant, $basket, $url));
$participant->setReminded(new \DateTime('now'));
$app['EM']->persist($participant);
$app['orm.em']->persist($participant);
}
$app['EM']->flush();
$app['orm.em']->flush();
$session = $app['authentication']->openAccount($user);
@@ -832,8 +832,8 @@ class Login implements ControllerProviderInterface
->setScreenHeight($height)
->setScreenWidth($width);
$app['EM']->persist($session);
$app['EM']->flush();
$app['orm.em']->persist($session);
$app['orm.em']->flush();
return $session;
}
@@ -883,8 +883,8 @@ class Login implements ControllerProviderInterface
}
if (null !== $user) {
$this->attachProviderToUser($app['EM'], $provider, $user);
$app['EM']->flush();
$this->attachProviderToUser($app['orm.em'], $provider, $user);
$app['orm.em']->flush();
$this->postAuthProcess($app, $user);
@@ -900,8 +900,8 @@ class Login implements ControllerProviderInterface
if ($app['authentication.providers.account-creator']->isEnabled()) {
$user = $app['authentication.providers.account-creator']->create($app, $token->getId(), $token->getIdentity()->getEmail(), $token->getTemplates());
$this->attachProviderToUser($app['EM'], $provider, $user);
$app['EM']->flush();
$this->attachProviderToUser($app['orm.em'], $provider, $user);
$app['orm.em']->flush();
$this->postAuthProcess($app, $user);
@@ -996,8 +996,8 @@ class Login implements ControllerProviderInterface
$response->headers->setCookie(new Cookie('persistent', $token, time() + $app['phraseanet.configuration']['session']['lifetime']));
$app['EM']->persist($session);
$app['EM']->flush();
$app['orm.em']->persist($session);
$app['orm.em']->flush();
}
$event = new PostAuthenticate($request, $response, $user, $context);

View File

@@ -68,7 +68,7 @@ class RSSFeeds implements ControllerProviderInterface
$feeds = $app['repo.feeds']->getAllForUser($app['acl']->get($user));
$aggregate = new Aggregate($app['EM'], $feeds, $token);
$aggregate = new Aggregate($app['orm.em'], $feeds, $token);
$request = $app['request'];

View File

@@ -90,7 +90,7 @@ class Session implements ControllerProviderInterface
'notifications' => $app['events-manager']->get_notifications()
]);
$baskets = $app['EM']->getRepository('Phraseanet:Basket')->findUnreadActiveByUser($app['authentication']->getUser());
$baskets = $app['orm.em']->getRepository('Phraseanet:Basket')->findUnreadActiveByUser($app['authentication']->getUser());
foreach ($baskets as $basket) {
$ret['changed'][] = $basket->getId();
@@ -161,13 +161,13 @@ class Session implements ControllerProviderInterface
$module = new SessionModule();
$module->setModuleId($moduleId);
$module->setSession($session);
$app['EM']->persist($module);
$app['orm.em']->persist($module);
} else {
$app['EM']->persist($session->getModuleById($moduleId)->setUpdated(new \DateTime()));
$app['orm.em']->persist($session->getModuleById($moduleId)->setUpdated(new \DateTime()));
}
$app['EM']->persist($session);
$app['EM']->flush();
$app['orm.em']->persist($session);
$app['orm.em']->flush();
$ret['status'] = 'ok';
@@ -219,8 +219,8 @@ class Session implements ControllerProviderInterface
$app->abort(403, 'Unauthorized');
}
$app['EM']->remove($session);
$app['EM']->flush();
$app['orm.em']->remove($session);
$app['orm.em']->flush();
if ($app['request']->isXmlHttpRequest()) {
return $app->json([

View File

@@ -148,13 +148,15 @@ class Setup implements ControllerProviderInterface
$databox_name = $request->request->get('db_name');
try {
$abConn = $app['dbal.provider']->get([
$abInfo = [
'host' => $database_host,
'port' => $database_port,
'user' => $database_user,
'password' => $database_password,
'dbname' => $appbox_name,
]);
];
$abConn = $app['dbal.provider']($abInfo);
$abConn->connect();
} catch (\Exception $e) {
return $app->redirectPath('install_step2', [
@@ -164,13 +166,15 @@ class Setup implements ControllerProviderInterface
try {
if ($databox_name) {
$dbConn = $app['dbal.provider']->get([
$dbInfo = [
'host' => $database_host,
'port' => $database_port,
'user' => $database_user,
'password' => $database_password,
'dbname' => $databox_name,
]);
];
$dbConn = $app['dbal.provider']($dbInfo);
$dbConn->connect();
}
} catch (\Exception $e) {
@@ -179,6 +183,17 @@ class Setup implements ControllerProviderInterface
]);
}
$app['dbs.options'] = array_merge(
$app['db.options.from_info']($dbInfo),
$app['db.options.from_info']($abInfo),
$app['dbs.options']
);
$app['orm.ems.options'] = array_merge(
$app['orm.em.options.from_info']($dbInfo),
$app['orm.em.options.from_info']($abInfo),
$app['orm.ems.options']
);
$email = $request->request->get('email');
$password = $request->request->get('password');
$template = $request->request->get('db_template');

View File

@@ -20,7 +20,7 @@ class DoctrineMigrationServiceProvider implements ServiceProviderInterface
public function register(Application $app)
{
$app['doctrine-migration.configuration'] = $app->share(function ($app) {
$configuration = new YamlConfiguration($app['EM']->getConnection());
$configuration = new YamlConfiguration($app['orm.em']->getConnection());
$configuration->load(__DIR__.'/../../../../conf.d/migrations.yml');
$configuration->setMigrationsDirectory(__DIR__.'/../../../../Alchemy/Phrasea/Setup/DoctrineMigration');

View File

@@ -31,11 +31,11 @@ class PluginServiceProvider implements ServiceProviderInterface
});
$app['plugins.autoloader-generator'] = $app->share(function (Application $app) {
return new AutoloaderGenerator($app['plugins.directory']);
return new AutoloaderGenerator($app['plugin.path']);
});
$app['plugins.assets-manager'] = $app->share(function (Application $app) {
return new AssetsManager($app['filesystem'], $app['plugins.directory'], $app['root.path']);
return new AssetsManager($app['filesystem'], $app['plugin.path'], $app['root.path']);
});
$app['plugins.composer-installer'] = $app->share(function (Application $app) {
@@ -46,10 +46,10 @@ class PluginServiceProvider implements ServiceProviderInterface
$phpBinary = $finder->find();
}
return new ComposerInstaller($app['composer-setup'], $app['plugins.directory'], $phpBinary);
return new ComposerInstaller($app['composer-setup'], $app['plugin.path'], $phpBinary);
});
$app['plugins.explorer'] = $app->share(function (Application $app) {
return new PluginsExplorer($app['plugins.directory']);
return new PluginsExplorer($app['plugin.path']);
});
$app['plugins.importer'] = $app->share(function (Application $app) {

View File

@@ -17,37 +17,59 @@ use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\DriverManager;
use Psr\Log\LoggerInterface;
class ConnectionProvider
class ConnectionPoolManager
{
private $config;
/**
* @var Connection[]
* @var \PDO[]
*/
private $connections = [];
private $eventManager;
private $logger;
public function __construct(Configuration $config, EventManager $eventManager, LoggerInterface $logger)
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
$this->config = $config;
$this->eventManager = $eventManager;
}
public function __destruct()
{
foreach ($this->connections as $conn) {
$conn->close();
}
$this->closeAll();
$this->connections = [];
}
/**
* @param $params
*
* @return Connection
*/
public function closeAll()
{
foreach ($this->connections as $key => $conn) {
$conn->close();
}
}
public function opened()
{
return $this->filter(function($connection) {
return $connection->isConnected();
});
}
public function closed()
{
return $this->filter(function($connection) {
return !$connection->isConnected();
});
}
public function filter(Callable $callback)
{
return array_filter($this->connections, $callback);
}
public function add(Connection $connection)
{
$key = md5(serialize($connection->getParams()));
if (!isset($this->connections[$key])) {
$this->connections[$key] = $connection;
}
}
public function get(array $params)
{
$params = array_replace([
@@ -61,6 +83,6 @@ class ConnectionProvider
return $this->connections[$key];
}
return $this->connections[$key] = new ReconnectableConnection(DriverManager::getConnection($params, $this->config, $this->eventManager), $this->logger);
return $this->connections[$key] = DriverManager::getConnection($params);
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2014 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Event\Subscriber;
use Alchemy\Phrasea\Application;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class DoctrineQueriesLoggerSubscriber implements EventSubscriberInterface
{
private $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => [
['logQueries', -255],
],
];
}
public function logQueries(GetResponseEvent $event)
{
if (Application::ENV_DEV !== $this->app->getEnvironment()) {
return;
}
foreach ($this->app['orm.query.logger']->queries as $query ) {
$this->app['orm.sql-logger']->debug($query['sql'], array(
'params' => $query['params'],
'types' => $query['types'],
'time' => $query['executionMS']
));
}
}
}

View File

@@ -34,7 +34,7 @@ class RegistrationSubscriber extends AbstractNotificationSubscriber
];
try {
$rs = $this->app['EM.native-query']->getAdminsOfBases(array_keys($baseIds));
$rs = $this->app['orm.em.native-query']->getAdminsOfBases(array_keys($baseIds));
$adminUsers = array_map(function ($row) { return $row[0]; }, $rs);
} catch (\Exception $e) {
return;
@@ -82,7 +82,7 @@ class RegistrationSubscriber extends AbstractNotificationSubscriber
];
try {
$rs = $this->app['EM.native-query']->getAdminsOfBases(array_keys($baseIds));
$rs = $this->app['orm.em.native-query']->getAdminsOfBases(array_keys($baseIds));
$adminUsers = array_map(function ($row) { return $row[0]; }, $rs);
} catch (\Exception $e) {
return;

View File

@@ -142,12 +142,12 @@ class SessionManagerSubscriber implements EventSubscriberInterface
$module->setSession($session);
$session->addModule($module);
$this->app['EM']->persist($module);
$this->app['orm.em']->persist($module);
} else {
$this->app['EM']->persist($session->getModuleById($moduleId)->setUpdated(new \DateTime()));
$this->app['orm.em']->persist($session->getModuleById($moduleId)->setUpdated(new \DateTime()));
}
$this->app['EM']->persist($session);
$this->app['EM']->flush();
$this->app['orm.em']->persist($session);
$this->app['orm.em']->flush();
}
private function isFlashUploadRequest(Request $request)

View File

@@ -32,7 +32,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface
public function register(Application $app)
{
$app['authentication'] = $app->share(function (Application $app) {
return new Authenticator($app, $app['browser'], $app['session'], $app['EM']);
return new Authenticator($app, $app['browser'], $app['session'], $app['orm.em']);
});
$app['authentication.persistent-manager'] = $app->share(function (Application $app) {
@@ -98,7 +98,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface
$app['auth.native.failure-manager'] = $app->share(function (Application $app) {
$authConf = $app['conf']->get(['authentication', 'captcha']);
return new FailureManager($app['repo.auth-failures'], $app['EM'], $app['recaptcha'], isset($authConf['trials-before-display']) ? $authConf['trials-before-display'] : 9);
return new FailureManager($app['repo.auth-failures'], $app['orm.em'], $app['recaptcha'], isset($authConf['trials-before-display']) ? $authConf['trials-before-display'] : 9);
});
$app['auth.password-checker'] = $app->share(function (Application $app) {

View File

@@ -25,10 +25,10 @@ class FeedServiceProvider implements ServiceProviderInterface
public function register(Application $app)
{
$app['feed.user-link-generator'] = $app->share(function ($app) {
return new FeedLinkGenerator($app['url_generator'], $app['EM'], $app['random.low']);
return new FeedLinkGenerator($app['url_generator'], $app['orm.em'], $app['random.low']);
});
$app['feed.aggregate-link-generator'] = $app->share(function ($app) {
return new AggregateLinkGenerator($app['url_generator'], $app['EM'], $app['random.medium']);
return new AggregateLinkGenerator($app['url_generator'], $app['orm.em'], $app['random.medium']);
});
$app['feed.link-generator-collection'] = $app->share(function ($app) {
$collection = new LinkGeneratorCollection();

View File

@@ -34,7 +34,7 @@ class ManipulatorServiceProvider implements ServiceProviderInterface
public function register(SilexApplication $app)
{
$app['manipulator.task'] = $app->share(function (SilexApplication $app) {
return new TaskManipulator($app['EM'], $app['task-manager.notifier'], $app['translator'], $app['repo.tasks']);
return new TaskManipulator($app['orm.em'], $app['task-manager.notifier'], $app['translator'], $app['repo.tasks']);
});
$app['manipulator.user'] = $app->share(function ($app) {
@@ -42,11 +42,11 @@ class ManipulatorServiceProvider implements ServiceProviderInterface
});
$app['manipulator.token'] = $app->share(function ($app) {
return new TokenManipulator($app['EM'], $app['random.medium'], $app['repo.tokens']);
return new TokenManipulator($app['orm.em'], $app['random.medium'], $app['repo.tokens']);
});
$app['manipulator.preset'] = $app->share(function ($app) {
return new PresetManipulator($app['EM'], $app['repo.presets']);
return new PresetManipulator($app['orm.em'], $app['repo.presets']);
});
$app['manipulator.acl'] = $app->share(function ($app) {
@@ -54,43 +54,43 @@ class ManipulatorServiceProvider implements ServiceProviderInterface
});
$app['model.user-manager'] = $app->share(function ($app) {
return new UserManager($app['EM'], $app['phraseanet.appbox']->get_connection());
return new UserManager($app['orm.em'], $app['phraseanet.appbox']->get_connection());
});
$app['manipulator.registration'] = $app->share(function ($app) {
return new RegistrationManipulator($app, $app['EM'], $app['acl'], $app['phraseanet.appbox'], $app['repo.registrations']);
return new RegistrationManipulator($app, $app['orm.em'], $app['acl'], $app['phraseanet.appbox'], $app['repo.registrations']);
});
$app['manipulator.api-application'] = $app->share(function ($app) {
return new ApiApplicationManipulator($app['EM'], $app['repo.api-applications'], $app['random.medium']);
return new ApiApplicationManipulator($app['orm.em'], $app['repo.api-applications'], $app['random.medium']);
});
$app['manipulator.api-account'] = $app->share(function ($app) {
return new ApiAccountManipulator($app['EM'], $app['repo.api-accounts']);
return new ApiAccountManipulator($app['orm.em'], $app['repo.api-accounts']);
});
$app['manipulator.api-oauth-code'] = $app->share(function ($app) {
return new ApiOauthCodeManipulator($app['EM'], $app['repo.api-oauth-codes'], $app['random.medium']);
return new ApiOauthCodeManipulator($app['orm.em'], $app['repo.api-oauth-codes'], $app['random.medium']);
});
$app['manipulator.api-oauth-token'] = $app->share(function ($app) {
return new ApiOauthTokenManipulator($app['EM'], $app['repo.api-oauth-tokens'], $app['random.medium']);
return new ApiOauthTokenManipulator($app['orm.em'], $app['repo.api-oauth-tokens'], $app['random.medium']);
});
$app['manipulator.api-oauth-refresh-token'] = $app->share(function ($app) {
return new ApiOauthRefreshTokenManipulator($app['EM'], $app['repo.api-oauth-refresh-tokens'], $app['random.medium']);
return new ApiOauthRefreshTokenManipulator($app['orm.em'], $app['repo.api-oauth-refresh-tokens'], $app['random.medium']);
});
$app['manipulator.api-log'] = $app->share(function ($app) {
return new ApiLogManipulator($app['EM'], $app['repo.api-logs']);
return new ApiLogManipulator($app['orm.em'], $app['repo.api-logs']);
});
$app['manipulator.webhook-event'] = $app->share(function ($app) {
return new WebhookEventManipulator($app['EM'], $app['repo.webhook-event']);
return new WebhookEventManipulator($app['orm.em'], $app['repo.webhook-event']);
});
$app['manipulator.webhook-delivery'] = $app->share(function ($app) {
return new WebhookEventDeliveryManipulator($app['EM'], $app['repo.webhook-delivery']);
return new WebhookEventDeliveryManipulator($app['orm.em'], $app['repo.webhook-delivery']);
});
}

View File

@@ -12,22 +12,22 @@
namespace Alchemy\Phrasea\Core\Provider;
use Alchemy\Phrasea\Application as PhraseaApplication;
use Alchemy\Phrasea\Cache\ArrayCache;
use Alchemy\Phrasea\Core\Connection\ConnectionPoolManager;
use Alchemy\Phrasea\Core\Connection\ConnectionProvider;
use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Model\MonologSQLLogger;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Configuration;
use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Model\NativeQueryProvider;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\FileCacheReader;
use Doctrine\Common\EventManager;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\Mapping\Driver\DriverChain;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Configuration as ORMConfiguration;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\DBAL\Logging\DebugStack;
use Doctrine\DBAL\Types\Type;
use Gedmo\DoctrineExtensions;
use Doctrine\ORM\Configuration as ORMConfig;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Gedmo\Timestampable\TimestampableListener;
use Monolog\Handler\RotatingFileHandler;
use Silex\Application;
@@ -37,84 +37,570 @@ class ORMServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['EM.sql-logger.file'] = $app->share(function (Application $app) {
return $app['log.path'].'/doctrine-log.log';
});
$app['EM.sql-logger.max-files'] = 5;
$app['EM.sql-logger'] = $app->share(function (Application $app) {
$logger = new $app['monolog.logger.class']('doctrine-logger');
$logger->pushHandler(new RotatingFileHandler($app['EM.sql-logger.file'], $app['EM.sql-logger.max-files']));
return new MonologSQLLogger($logger, 'yaml');
/**
* Provide configuration for DoctrineServiceProvider.
*/
$app['dbs.service.conf'] = $app->share(function() use ($app) {
return array(
'dbs.options' => $app['dbs.options']
);
});
$app['EM.driver'] = $app->share(function (Application $app) {
AnnotationRegistry::registerFile(
$app['root.path'].'/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'
);
$annotationReader = new AnnotationReader();
$fileCacheReader = new FileCacheReader(
$annotationReader,
$app['cache.path'].'/doctrine',
$app['debug']
);
$driverChain = new MappingDriverChain();
DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
$driverChain,
$fileCacheReader
);
$annotationDriver = new AnnotationDriver(
$fileCacheReader,
[$app['root.path'].'/lib/Alchemy/Phrasea/Model/Entities']
);
$driverChain->addDriver($annotationDriver, 'Alchemy\Phrasea\Model\Entities');
return $driverChain;
});
$app['EM.config'] = $app->share(function (Application $app) {
$config = new ORMConfiguration();
if ($app->getEnvironment() === PhraseaApplication::ENV_DEV) {
$config->setSQLLogger($app['EM.sql-logger']);
}
/**
* Provide configuration for DoctrineORMServiceProvider.
*/
$app['orm.service.conf'] = $app->share(function() use ($app) {
return array(
// Override "orm.cache.configurer" service provided for benefiting
// of "phraseanet.cache-service"
"orm.cache.configurer" => $app->protect(function($name, ORMConfig $config, $options) use ($app) {
$config->setMetadataCacheImpl($app['phraseanet.cache-service']->factory(
'ORMmetadata', $app['EM.opcode-cache-type'], $app['EM.opcode-cache-options']
'ORM_metadata', $app['orm.cache.driver'], $app['orm.cache.options']
));
$config->setQueryCacheImpl($app['phraseanet.cache-service']->factory(
'ORMquery', $app['EM.opcode-cache-type'], $app['EM.opcode-cache-options']
'ORM_query', $app['orm.cache.driver'], $app['orm.cache.options']
));
$config->setResultCacheImpl($app['phraseanet.cache-service']->factory(
'ORMresult', $app['EM.cache-type'], $app['EM.cache-options']
'ORM_result', $app['orm.cache.driver'], $app['orm.cache.options']
));
$config->setHydrationCacheImpl($app['phraseanet.cache-service']->factory(
'ORM_hydration', $app['orm.cache.driver'], $app['orm.cache.options']
));
}),
"orm.proxies_dir" => $app['root.path'].'/resources/proxies',
"orm.auto_generate_proxies" => $app['debug'],
"orm.proxies_namespace" => 'Alchemy\Phrasea\Model\Proxies',
"orm.em.options" => $app['orm.ems.options']
);
});
/**
* Provides DSN string using database information
*/
$app['db.dsn'] = $app->protect(function(array $params) use ($app) {
$params = $app['db.info']($params);
switch ($params['driver']) {
case 'pdo_mysql':
return sprintf('%s://%s:%s@%s:%s/%s',
$params['driver'],
$params['user'],
$params['password'],
$params['host'],
$params['port'],
$params['dbname']
);
case 'pdo_sqlite':
return sprintf('%s:%s',
$params['driver'],
$params['path']
);
}
});
/**
* Hash a DSN string
*/
$app['hash.dsn'] = $app->protect(function($dsn) {
return md5($dsn);
});
/**
* Return database test configuration
*/
$app['db.test.info'] = $app->share(function() use ($app) {
return $app['conf']->get(['main', 'database-test'], array());
});
/**
* Return application box database configuration
*/
$app['db.appbox.info'] = $app->share(function() use ($app) {
return $app['conf']->get(['main', 'database'], array());
});
/**
* Return database fixture configuration
*/
$app['db.fixture.info'] = $app->share(function() use ($app) {
return [
'driver' => 'pdo_sqlite',
'path' => sprintf('%s/%s', $app['tmp.path'], 'db-ref.sqlite'),
'charset' => 'UTF8',
];
});
/**
* Return databox database configuration
*/
$app['db.databox.info'] = $app->share(function() use ($app) {
if (false === $app['phraseanet.configuration']->isSetup()) {
return array();
}
$info = $app['db.appbox.info'];
$connection = $app['dbal.provider']($info);
$connection->connect();
//@todo cache this request ?
$sql = <<<SQL
SELECT
host,
port,
`user`,
IFNULL(pwd, '') AS password,
dbname,
'utf8' AS charset,
'pdo_mysql' AS driver
FROM sbas
SQL;
$stmt = $connection->prepare($sql);
$stmt->execute();
$databox = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$connection->close();
unset($stmt, $connection);
return $databox;
});
/**
* Return unique key for fixture database
*/
$app['db.fixture.hash.key'] = $app->share(function() use ($app) {
$info = $app['db.fixture.info'];
return $app['hash.dsn']($app['db.dsn']($info));
});
/**
* Return unique key for test database
*/
$app['db.test.hash.key'] = $app->share(function() use ($app) {
$info = $app['db.test.info'];
return $app['hash.dsn']($app['db.dsn']($info));
});
/**
* Return unique for appbox database
*/
$app['db.appbox.hash.key'] = $app->share(function() use ($app) {
$info = $app['db.appbox.info'];
return $app['hash.dsn']($app['db.dsn']($info));
});
/**
* Return configuration option for test database in DoctrineServiceProvider
*/
$app['db.test.options'] = $app->share(function() use ($app) {
return array($app['db.test.hash.key'] => $app['db.test.info']);
});
/**
* Return configuration option for test database in DoctrineServiceProvider
*/
$app['db.fixture.options'] = $app->share(function() use ($app) {
return array($app['db.fixture.hash.key'] => $app['db.fixture.info']);
});
/**
* Return configuration option for appbox database in DoctrineServiceProvider
*/
$app['db.appbox.options'] = $app->share(function() use ($app) {
return array($app['db.appbox.hash.key'] => $app['db.appbox.info']);
});
/**
* Return configuration option for databox databases in DoctrineServiceProvider
*/
$app['dbs.databox.options'] = $app->share(function() use ($app) {
$options = array();
foreach($app['db.databox.info'] as $info) {
$info = $app['db.info']($info);
$key = $app['hash.dsn']($app['db.dsn']($info));
$options[$key] = $info;
}
return $options;
});
/**
* Return DoctrineServiceProvider database options, it merges all previous
* set database configuration
*/
$app['dbs.options'] = $app->share(function() use ($app) {
if (false === $app['phraseanet.configuration']->isSetup()) {
return [];
}
return array_merge(
$app['db.appbox.options'],
$app['dbs.databox.options'],
$app['db.fixture.options'],
$app['db.test.options']
);
});
/**
* Return DoctrineORMServiceProvider information for a database from its parameters
*/
$app['orm.em.options.from_info'] = $app->protect(function(array $info) use ($app) {
$info = $app['db.info']($info);
$key = $app['hash.dsn']($app['db.dsn']($info));
return array($key => $app['orm.options']($key));
});
/**
* Return DoctrineServiceProvider information for a database from its parameters
*/
$app['db.options.from_info'] = $app->protect(function(array $info) use ($app) {
$info = $app['db.info']($info);
$key = $app['hash.dsn']($app['db.dsn']($info));
return array($key => $info);
});
/**
* Add orm on the fly, used only when a new databox is mounted.
* This allow to use new EM instance right after the database is mounted.
*/
$app['orm.add'] = $app->protect(function($info) use ($app) {
$info = $app['db.info']($info);
$key = $app['hash.dsn']($app['db.dsn']($info));
$evm = new EventManager();
$app['dbal.evm.register.listeners']($evm);
$app['dbs.event_manager'][$key] = $evm;
$app['dbs.config'][$key] = new Configuration();
$app['dbs'][$key] = $app['dbs']->share(function () use ($app, $info, $key) {
return DriverManager::getConnection($info,$app['dbs.config'][$key] ,$app['dbs.event_manager'][$key]);
});
$options = $app['orm.options']($key);
$config = $app['orm.config.new']($key, $options);
$app['orm.annotation.register']($key);
$app['orm.ems'][$key] = $app['orm.ems']->share(function ($ems) use ($app, $key, $options, $config) {
$connection = $app['dbs'][$key];
$app['connection.pool.manager']->add($connection);
$types = $options['types'];
$app['dbal.type.register']($connection, $types);
return EntityManager::create(
$connection,
$config,
$app['dbs.event_manager'][$options['connection']]
);
});
return $key;
});
$app['dbal.evm.register.listeners'] = $app->protect(function($evm) use($app) {
$evm->addEventSubscriber(new TimestampableListener());
});
$app['dbal.config.register.loggers'] = $app->protect(function($config) use($app) {
if ($app->getEnvironment() === PhraseaApplication::ENV_DEV) {
$config->setSQLLogger($app['orm.query.logger']);
}
});
$app['orm.annotation.register'] = $app->protect(function($key) use($app) {
$driver = new AnnotationDriver($app['orm.annotation.reader'], array(
$app['root.path'].'/vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity/MappedSuperclass',
$app['root.path'].'/vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity/MappedSuperclass',
$app['root.path'].'/vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity/MappedSuperclass',
));
$config->setAutoGenerateProxyClasses($app['debug']);
$app['orm.add_mapping_driver']($driver, 'Gedmo', $key);
});
$config->setMetadataDriverImpl($app['EM.driver']);
$app['dbal.type.register'] = $app->protect(function(Connection $connection, $types) {
$platform = $connection->getDatabasePlatform();
$config->setProxyDir($app['root.path'].'/resources/proxies');
$config->setProxyNamespace('Alchemy\Phrasea\Model\Proxies');
$config->setAutoGenerateProxyClasses($app['debug']);
$config->addEntityNamespace('Phraseanet', 'Alchemy\Phrasea\Model\Entities');
foreach (array_keys((array) $types) as $type) {
$platform->registerDoctrineTypeMapping($type, $type);
}
});
$app['orm.config.new'] = $app->protect(function($key, $options) use($app) {
$config = new ORMConfig();
$app['orm.cache.configurer']($key, $config, $options);
$config->setProxyDir($app['orm.proxies_dir']);
$config->setProxyNamespace($app['orm.proxies_namespace']);
$config->setAutoGenerateProxyClasses($app['orm.auto_generate_proxies']);
$config->setCustomStringFunctions($app['orm.custom.functions.string']);
$config->setCustomNumericFunctions($app['orm.custom.functions.numeric']);
$config->setCustomDatetimeFunctions($app['orm.custom.functions.datetime']);
$config->setCustomHydrationModes($app['orm.custom.hydration_modes']);
$config->setClassMetadataFactoryName($app['orm.class_metadata_factory_name']);
$config->setDefaultRepositoryClassName($app['orm.default_repository_class']);
$config->setEntityListenerResolver($app['orm.entity_listener_resolver']);
$config->setRepositoryFactory($app['orm.repository_factory']);
$config->setNamingStrategy($app['orm.strategy.naming']);
$config->setQuoteStrategy($app['orm.strategy.quote']);
$chain = $app['orm.mapping_driver_chain.locator']($key);
foreach ((array)$options['mappings'] as $entity) {
if (!is_array($entity)) {
throw new \InvalidArgumentException(
"The 'orm.em.options' option 'mappings' should be an array of arrays."
);
}
if (!empty($entity['resources_namespace'])) {
$entity['path'] = $app['psr0_resource_locator']->findFirstDirectory($entity['resources_namespace']);
}
if (isset($entity['alias'])) {
$config->addEntityNamespace($entity['alias'], $entity['namespace']);
}
switch ($entity['type']) {
case 'annotation':
$useSimpleAnnotationReader =
isset($entity['use_simple_annotation_reader'])
? $entity['use_simple_annotation_reader']
: true;
$driver = $config->newDefaultAnnotationDriver((array) $entity['path'], $useSimpleAnnotationReader);
$chain->addDriver($driver, $entity['namespace']);
break;
case 'yml':
$driver = new YamlDriver($entity['path']);
$chain->addDriver($driver, $entity['namespace']);
break;
case 'simple_yml':
$driver = new SimplifiedYamlDriver(array($entity['path'] => $entity['namespace']));
$chain->addDriver($driver, $entity['namespace']);
break;
case 'xml':
$driver = new XmlDriver($entity['path']);
$chain->addDriver($driver, $entity['namespace']);
break;
case 'simple_xml':
$driver = new SimplifiedXmlDriver(array($entity['path'] => $entity['namespace']));
$chain->addDriver($driver, $entity['namespace']);
break;
case 'php':
$driver = new StaticPHPDriver($entity['path']);
$chain->addDriver($driver, $entity['namespace']);
break;
default:
throw new \InvalidArgumentException(sprintf('"%s" is not a recognized driver', $entity['type']));
break;
}
}
$config->setMetadataDriverImpl($chain);
foreach ((array) $options['types'] as $typeName => $typeClass) {
if (Type::hasType($typeName)) {
Type::overrideType($typeName, $typeClass);
} else {
Type::addType($typeName, $typeClass);
}
}
return $config;
});
$app['EM.opcode-cache-type'] = $app->share(function (Application $app) {
$app['orm.ems.options'] = $app->share(function() use ($app) {
if (false === $app['phraseanet.configuration']->isSetup()) {
return [];
}
return array_merge(
$app['orm.em.appbox.options'],
$app['orm.ems.databox.options'],
$app['orm.em.fixture.options'],
$app['orm.em.test.options']
);
});
/**
* Check database connection information
*/
$app['db.info'] = $app->protect(function(array $info){
if (!isset($info['driver'])) {
$info['driver'] = 'pdo_mysql';
}
if (!isset($info['charset'])) {
$info['charset'] = 'utf8';
}
switch ($info['driver']) {
case 'pdo_mysql':
foreach (array('user', 'password', 'host', 'dbname', 'port') as $param) {
if (!array_key_exists($param, $info)) {
throw new InvalidArgumentException(sprintf('Missing "%s" argument for database connection using driver %s', $param, $info['driver']));
}
}
break;
case 'pdo_sqlite':
if (!array_key_exists('path', $info)) {
throw new InvalidArgumentException(sprintf('Missing "path" argument for database connection using driver %s', $info['driver']));
}
break;
}
return $info;
});
/**
* Return configuration option for appbox database in DoctrineORMServiceProvider
*/
$app['orm.em.appbox.options'] = $app->share(function() use ($app) {
$key = $app['db.appbox.hash.key'];
return array($key => $app['orm.options']($key));
});
/**
* Return configuration option for fixture database in DoctrineORMServiceProvider
*/
$app['orm.em.fixture.options'] = $app->share(function() use ($app) {
$key = $app['db.fixture.hash.key'];
return array($key => $app['orm.options']($key));
});
/**
* Return configuration option for test database in DoctrineORMServiceProvider
*/
$app['orm.em.test.options'] = $app->share(function() use ($app) {
$key = $app['db.test.hash.key'];
return array($key => $app['orm.options']($key));
});
/**
* Return configuration option for databox databases in DoctrineORMServiceProvider
*/
$app['orm.ems.databox.options'] = $app->share(function() use ($app) {
$options = array();
foreach ($app['db.databox.info'] as $base) {
$info = $app['db.info']($base);
$key = $app['hash.dsn']($app['db.dsn']($info));
$options[$key] = $app['orm.options']($key);
}
return $options;
});
/**
* Return orm configuration for a connection given its unique id
*/
$app['orm.options'] = $app->protect(function($connection) use ($app) {
return array(
"connection" => $connection,
"mappings" => array(
array(
"type" => "annotation",
"alias" => "Phraseanet",
"use_simple_annotation_reader" => false,
"namespace" => 'Alchemy\Phrasea\Model\Entities',
"path" => $app['root.path'].'/lib/Alchemy/Phrasea/Model/Entities',
)
),
"types" => array(
'blob' => 'Alchemy\Phrasea\Model\Types\Blob',
'enum' => 'Alchemy\Phrasea\Model\Types\Enum',
'longblob' => 'Alchemy\Phrasea\Model\Types\LongBlob',
'varbinary' => 'Alchemy\Phrasea\Model\Types\VarBinary',
'binary' => 'Alchemy\Phrasea\Model\Types\Binary',
'binary_string' => 'Alchemy\Phrasea\Model\Types\BinaryString',
)
);
});
/**
* Path to doctrine log file
*/
$app['orm.monolog.handler.file'] = $app->share(function (Application $app) {
return $app['log.path'].'/doctrine.log';
});
/**
* Maximum files of logs
*/
$app['orm.monolog.handler.file.max-files'] = 5;
/**
* Monolog handler for doctrine
*/
$app['orm.monolog.handler'] = $app->share(function(Application $app) {
return new RotatingFileHandler($app['orm.monolog.handler.file'], $app['orm.monolog.handler.file.max-files']);
});
/**
* Monolog instance for doctrine
*/
$app['orm.monolog.logger'] = $app->share(function (Application $app) {
$logger = new $app['monolog.logger.class']('doctrine-logger');
$logger->pushHandler($app['orm.monolog.handler']);
return $logger;
});
/**
* Doctrine query logger
*/
$app['orm.query.logger'] = $app->share(function () {
return new DebugStack();
});
/**
* Return op code cache driver
*/
$app['orm.cache.op_code.driver'] = $app->share(function (Application $app) {
if ($app['configuration.store']->isSetup()) {
return $app['conf']->get(['main', 'opcodecache', 'type']);
}
return 'ArrayCache';
return 'array';
});
$app['EM.opcode-cache-options'] = $app->share(function (Application $app) {
/**
* Return op code cache options
*/
$app['orm.cache.op_code.options'] = $app->share(function (Application $app) {
if ($app['configuration.store']->isSetup()) {
return $app['conf']->get(['main', 'opcodecache', 'options']);
}
@@ -122,69 +608,76 @@ class ORMServiceProvider implements ServiceProviderInterface
return [];
});
$app['EM.cache-type'] = $app->share(function (Application $app) {
/**
* Return cache driver
*/
$app['orm.cache.driver'] = $app->share(function (Application $app) {
if ($app['configuration.store']->isSetup()) {
return $app['conf']->get(['main', 'cache', 'type']);
}
return 'ArrayCache';
return 'array';
});
$app['EM.cache-options'] = $app->share(function (Application $app) {
/**
* Return cache options
*/
$app['orm.cache.options'] = $app->share(function (Application $app) {
if ($app['configuration.store']->isSetup()) {
return $app['conf']->get(['main', 'cache', 'options']);
}
return [];
});
$app['EM.events-manager'] = $app->share(function (Application $app) {
$evm = new EventManager();
$evm->addEventSubscriber(new TimestampableListener());
return $evm;
/**
* Retrieve a registered DBALConnection using configuration parameters
*/
$app['db.provider'] = $app->protect(function (array $info) use ($app) {
$info = $app['db.info']($info);
$key = $app['hash.dsn']($app['db.dsn']($info));
return $app['dbs'][$key];
});
$app['EM.dbal-conf'] = $app->share(function (Application $app) {
if ('test' === $app->getEnvironment()) {
return $app['conf']->get(['main', 'database-test']);
}
/**
* Returns a new DBALConnection instance using configuration parameters
*/
$app['dbal.provider'] = $app->protect(function (array $info) use ($app) {
$info = $app['db.info']($info);
return $app['conf']->get(['main', 'database']);
$connection = DriverManager::getConnection($info);
$app['connection.pool.manager']->add($connection);
return $connection;
});
$app['dbal.provider'] = $app->share(function (Application $app) {
return new ConnectionProvider($app['EM.config'], $app['EM.events-manager'], isset($app['task-manager.logger']) ? $app['task-manager.logger'] : $app['monolog']);
$app['connection.pool.manager'] = $app->share(function() use ($app) {
return new ConnectionPoolManager();
});
$app['EM'] = $app->share(function (Application $app) {
try {
$em = EntityManager::create($app['EM.dbal-conf'], $app['EM.config'], $app['EM.events-manager']);
} catch (\Exception $e) {
throw new RuntimeException("Unable to create database connection", $e->getCode(), $e);
}
$platform = $em->getConnection()->getDatabasePlatform();
$types = [
'blob' => 'Alchemy\Phrasea\Model\Types\Blob',
'enum' => 'Alchemy\Phrasea\Model\Types\Blob',
'longblob' => 'Alchemy\Phrasea\Model\Types\LongBlob',
'varbinary' => 'Alchemy\Phrasea\Model\Types\VarBinary',
'binary' => 'Alchemy\Phrasea\Model\Types\Binary',
'binary_string' => 'Alchemy\Phrasea\Model\Types\BinaryString',
];
foreach ($types as $type => $class) {
if (!Type::hasType($type)) {
Type::addType($type, $class);
}
$platform->registerDoctrineTypeMapping($type, $type);
}
return $em;
/**
* Return an instance of native cache query for default ORM
* @todo return an instance of NativeQueryProvider for given orm;
*/
$app['orm.orm.em.native-query'] = $app->share(function ($app) {
return new NativeQueryProvider($app['orm.em']);
});
$app['EM.native-query'] = $app->share(function ($app) {
return new NativeQueryProvider($app['EM']);
/**
* Return an instance of annotation cache reader
*/
$app['orm.annotation.reader'] = $app->share(function() use ($app) {
$cache = new ArrayCache();
if ($app->getEnvironment() !== PhraseaApplication::ENV_DEV) {
$cache = $app['phraseanet.cache-service']->factory(
'ORM_annotation', $app['orm.cache.driver'], $app['orm.cache.options']
);
}
return new CachedReader(new AnnotationReader(), $cache);
});
}

View File

@@ -68,13 +68,25 @@ class PhraseanetServiceProvider implements ServiceProviderInterface
return $reader;
});
$app['phraseanet.metadata-setter'] = $app->share(function (SilexApplication $app) {
$app['phraseanet.metadata-setter'] = $app->share(function () {
return new PhraseanetMetadataSetter();
});
$app['phraseanet.user-query'] = function (SilexApplication $app) {
return new \User_Query($app);
};
$app['phraseanet.logger'] = $app->protect(function ($databox) use ($app) {
try {
return \Session_Logger::load($app, $databox);
} catch (\Exception_Session_LoggerNotFound $e) {
return \Session_Logger::create($app, $databox, $app['browser']);
}
});
$app['date-formatter'] = $app->share(function (SilexApplication $app) {
return new \phraseadate($app);
});
}
public function boot(SilexApplication $app)

View File

@@ -37,7 +37,7 @@ class PluginServiceProvider implements ServiceProviderInterface
});
$app['plugins.manager'] = $app->share(function (Application $app) {
return new PluginManager($app['plugins.directory'], $app['plugins.plugins-validator'], $app['conf']);
return new PluginManager($app['plugin.path'], $app['plugins.plugins-validator'], $app['conf']);
});
}

View File

@@ -20,106 +20,106 @@ class RepositoriesServiceProvider implements ServiceProviderInterface
public function register(Application $app)
{
$app['repo.users'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:User');
return $app['orm.em']->getRepository('Phraseanet:User');
});
$app['repo.auth-failures'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:AuthFailure');
return $app['orm.em']->getRepository('Phraseanet:AuthFailure');
});
$app['repo.sessions'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Session');
return $app['orm.em']->getRepository('Phraseanet:Session');
});
$app['repo.tasks'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Task');
return $app['orm.em']->getRepository('Phraseanet:Task');
});
$app['repo.registrations'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Registration');
return $app['orm.em']->getRepository('Phraseanet:Registration');
});
$app['repo.baskets'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Basket');
return $app['orm.em']->getRepository('Phraseanet:Basket');
});
$app['repo.basket-elements'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:BasketElement');
return $app['orm.em']->getRepository('Phraseanet:BasketElement');
});
$app['repo.validation-participants'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ValidationParticipant');
return $app['orm.em']->getRepository('Phraseanet:ValidationParticipant');
});
$app['repo.story-wz'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:StoryWZ');
return $app['orm.em']->getRepository('Phraseanet:StoryWZ');
});
$app['repo.orders'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Order');
return $app['orm.em']->getRepository('Phraseanet:Order');
});
$app['repo.order-elements'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:OrderElement');
return $app['orm.em']->getRepository('Phraseanet:OrderElement');
});
$app['repo.feeds'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Feed');
return $app['orm.em']->getRepository('Phraseanet:Feed');
});
$app['repo.feed-entries'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:FeedEntry');
return $app['orm.em']->getRepository('Phraseanet:FeedEntry');
});
$app['repo.feed-items'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:FeedItem');
return $app['orm.em']->getRepository('Phraseanet:FeedItem');
});
$app['repo.feed-publishers'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:FeedPublisher');
return $app['orm.em']->getRepository('Phraseanet:FeedPublisher');
});
$app['repo.feed-tokens'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:FeedToken');
return $app['orm.em']->getRepository('Phraseanet:FeedToken');
});
$app['repo.aggregate-tokens'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:AggregateToken');
return $app['orm.em']->getRepository('Phraseanet:AggregateToken');
});
$app['repo.usr-lists'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:UsrList');
return $app['orm.em']->getRepository('Phraseanet:UsrList');
});
$app['repo.usr-list-owners'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:UsrListOwner');
return $app['orm.em']->getRepository('Phraseanet:UsrListOwner');
});
$app['repo.usr-list-entries'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:UsrListEntry');
return $app['orm.em']->getRepository('Phraseanet:UsrListEntry');
});
$app['repo.lazaret-files'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:LazaretFile');
return $app['orm.em']->getRepository('Phraseanet:LazaretFile');
});
$app['repo.usr-auth-providers'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:UsrAuthProvider');
return $app['orm.em']->getRepository('Phraseanet:UsrAuthProvider');
});
$app['repo.ftp-exports'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:FtpExport');
return $app['orm.em']->getRepository('Phraseanet:FtpExport');
});
$app['repo.user-queries'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:UserQuery');
return $app['orm.em']->getRepository('Phraseanet:UserQuery');
});
$app['repo.tokens'] = $app->share(function ($app) {
return $app['EM']->getRepository('Phraseanet:Token');
return $app['orm.em']->getRepository('Phraseanet:Token');
});
$app['repo.presets'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:Preset');
return $app['orm.em']->getRepository('Phraseanet:Preset');
});
$app['repo.api-accounts'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ApiAccount');
return $app['orm.em']->getRepository('Phraseanet:ApiAccount');
});
$app['repo.api-logs'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ApiLog');
return $app['orm.em']->getRepository('Phraseanet:ApiLog');
});
$app['repo.api-applications'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ApiApplication');
return $app['orm.em']->getRepository('Phraseanet:ApiApplication');
});
$app['repo.api-oauth-codes'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ApiOauthCode');
return $app['orm.em']->getRepository('Phraseanet:ApiOauthCode');
});
$app['repo.api-oauth-tokens'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ApiOauthToken');
return $app['orm.em']->getRepository('Phraseanet:ApiOauthToken');
});
$app['repo.api-oauth-refresh-tokens'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:ApiOauthRefreshToken');
return $app['orm.em']->getRepository('Phraseanet:ApiOauthRefreshToken');
});
$app['repo.webhook-event'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:WebhookEvent');
return $app['orm.em']->getRepository('Phraseanet:WebhookEvent');
});
$app['repo.webhook-delivery'] = $app->share(function (PhraseaApplication $app) {
return $app['EM']->getRepository('Phraseanet:WebhookEventDelivery');
return $app['orm.em']->getRepository('Phraseanet:WebhookEventDelivery');
});
}

View File

@@ -81,7 +81,7 @@ class Aggregate implements FeedInterface
$feeds = $app['repo.feeds']->getAllForUser($app['acl']->get($user), $restrictions);
$token = $app['repo.aggregate-tokens']->findOneBy(['user' => $user]);
return new static($app['EM'], $feeds, $token);
return new static($app['orm.em'], $feeds, $token);
}
/**
@@ -239,6 +239,6 @@ class Aggregate implements FeedInterface
*/
public static function getPublic(Application $app)
{
return new static($app['EM'], $app['repo.feeds']->findBy(['public' => true], ['updatedOn' => 'DESC']));
return new static($app['orm.em'], $app['repo.feeds']->findBy(['public' => true], ['updatedOn' => 'DESC']));
}
}

View File

@@ -24,21 +24,23 @@ class DatabaseHelper extends Helper
$connection_ok = $db_ok = $is_databox = $is_appbox = $empty = false;
try {
$conn = $this->app['dbal.provider']->get([
$connection = $this->app['dbal.provider']([
'host' => $hostname,
'port' => $port,
'user' => $user,
'password' => $password
]);
$conn->connect();
$connection->connect();
$connection_ok = true;
$connection->close();
} catch (\Exception $e) {
}
unset($connection);
if (null !== $db_name && $connection_ok) {
try {
$conn = $this->app['dbal.provider']->get([
$connection = $this->app['dbal.provider']([
'host' => $hostname,
'port' => $port,
'user' => $user,
@@ -46,12 +48,10 @@ class DatabaseHelper extends Helper
'dbname' => $db_name,
]);
$conn->connect();
$db_ok = true;
$sql = "SHOW TABLE STATUS";
$stmt = $conn->prepare($sql);
$stmt = $connection->prepare($sql);
$stmt->execute();
$empty = $stmt->rowCount() === 0;
@@ -67,11 +67,16 @@ class DatabaseHelper extends Helper
$is_databox = true;
}
}
$connection->close();
} catch (\Exception $e) {
}
unset($connection);
}
$this->app['connection.pool.manager']->closeAll();
return [
'connection' => $connection_ok,
'innodb' => true,

View File

@@ -18,6 +18,7 @@ use Alchemy\Phrasea\Notification\Mail\MailSuccessEmailUpdate;
use Alchemy\Phrasea\Notification\Receiver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Edit extends \Alchemy\Phrasea\Helper\Helper
{
@@ -644,6 +645,9 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
{
$template = $this->app['repo.users']->find($this->request->get('template'));
if (null === $template) {
throw new NotFoundHttpException(sprintf('Given template "%s" could not be found', $this->request->get('template')));
}
if (null === $template->getTemplateOwner() || $template->getTemplateOwner()->getId() !== $this->app['authentication']->getUser()->getId()) {
throw new AccessDeniedHttpException('You are not the owner of the template');
}

View File

@@ -48,8 +48,8 @@ class WorkZone extends Helper
$basket->setName($this->app->trans('Default basket'));
$basket->setUser($this->app['authentication']->getUser());
$this->app['EM']->persist($basket);
$this->app['EM']->flush();
$this->app['orm.em']->persist($basket);
$this->app['orm.em']->flush();
$baskets = [$basket];
}

View File

@@ -58,7 +58,7 @@ class ValidationParticipant
/**
* @ORM\ManyToOne(targetEntity="ValidationSession", inversedBy="participants", cascade={"persist"})
* @ORM\JoinColumn(name="ValidationSession_id", referencedColumnName="id")
* @ORM\JoinColumn(name="validation_session_id", referencedColumnName="id")
*/
private $session;

View File

@@ -1,84 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2014 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Model;
use Doctrine\DBAL\Logging\SQLLogger;
use Psr\Log\LoggerInterface;
/**
* Log doctrine sql request with monolog
*
* Please move this to a service provider as follow
* http://srcmvn.com/blog/2011/11/10/doctrine-dbal-query-logging-with-monolog-in-silex/
*/
class MonologSQLLogger implements SQLLogger
{
const JSON = 'json';
const YAML = 'yaml';
const VDUMP = 'vdump';
/**
* @var LoggerInterface
*/
private $logger;
private $start;
private $output = [];
private $outputType;
/**
* Tell which monolog user to use and which format to output
*
* @param LoggerInterface $logger A monolog logger instance
* @param string $type the output format
*/
public function __construct(LoggerInterface $logger, $type = self::YAML)
{
$this->logger = $logger;
$this->outputType = $type;
}
/**
* {@inheritdoc}
*/
public function startQuery($sql, array $params = null, array $types = null)
{
$this->start = microtime(true);
$this->output["sql"] = $sql;
if ($params) {
$this->output["params"] = $params;
}
}
/**
* {@inheritdoc}
*/
public function stopQuery()
{
$mstime = microtime(true) - $this->start;
$this->output["times"] = $mstime . " seconds";
if ($this->outputType == self::JSON) {
$this->log(json_encode($this->output));
} elseif ($this->outputType == self::YAML) {
$this->log(\Symfony\Component\Yaml\Yaml::dump($this->output));
} else {
$this->log(var_export($this->output, true));
}
}
protected function log($message)
{
$this->logger->debug($message);
}
}

View File

@@ -79,10 +79,10 @@ class FeedItemRepository extends EntityRepository
try {
$record = $item->getRecord($app);
} catch (NotFoundHttpException $e) {
$app['EM']->remove($item);
$app['orm.em']->remove($item);
continue;
} catch (\Exception_Record_AdapterNotFound $e) {
$app['EM']->remove($item);
$app['orm.em']->remove($item);
continue;
}
@@ -97,7 +97,7 @@ class FeedItemRepository extends EntityRepository
}
}
$app['EM']->flush();
$app['orm.em']->flush();
$execution++;
} while (count($items) < $nbItems && count($result) !== 0);

View File

@@ -28,7 +28,7 @@ class WorkzoneMigration extends AbstractMigration
$this->addSql("CREATE TABLE ValidationSessions (id INT AUTO_INCREMENT NOT NULL, initiator_id INT NOT NULL, basket_id INT DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, expires DATETIME DEFAULT NULL, INDEX IDX_5B9DFB067DB3B714 (initiator_id), UNIQUE INDEX UNIQ_5B9DFB061BE1FB52 (basket_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
$this->addSql("CREATE TABLE ValidationDatas (id INT AUTO_INCREMENT NOT NULL, participant_id INT DEFAULT NULL, basket_element_id INT DEFAULT NULL, agreement TINYINT(1) DEFAULT NULL, note LONGTEXT DEFAULT NULL, updated DATETIME NOT NULL, INDEX IDX_70E84DDC9D1C3019 (participant_id), INDEX IDX_70E84DDCE989605 (basket_element_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
$this->addSql("CREATE TABLE BasketElements (id INT AUTO_INCREMENT NOT NULL, basket_id INT DEFAULT NULL, record_id INT NOT NULL, sbas_id INT NOT NULL, ord INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_C0B7ECB71BE1FB52 (basket_id), UNIQUE INDEX unique_recordcle (basket_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
$this->addSql("CREATE TABLE ValidationParticipants (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, is_aware TINYINT(1) NOT NULL, is_confirmed TINYINT(1) NOT NULL, can_agree TINYINT(1) NOT NULL, can_see_others TINYINT(1) NOT NULL, reminded DATETIME DEFAULT NULL, ValidationSession_id INT DEFAULT NULL, INDEX IDX_17850D7BF25B0F5B (ValidationSession_id), INDEX IDX_17850D7BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
$this->addSql("CREATE TABLE ValidationParticipants (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, is_aware TINYINT(1) NOT NULL, is_confirmed TINYINT(1) NOT NULL, can_agree TINYINT(1) NOT NULL, can_see_others TINYINT(1) NOT NULL, reminded DATETIME DEFAULT NULL, validation_session_id INT DEFAULT NULL, INDEX IDX_17850D7BF25B0F5B (validation_session_id), INDEX IDX_17850D7BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
$this->addSql("ALTER TABLE Baskets ADD CONSTRAINT FK_13461873A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)");
$this->addSql("ALTER TABLE Baskets ADD CONSTRAINT FK_13461873C2D98306 FOREIGN KEY (pusher_id) REFERENCES Users (id)");
$this->addSql("ALTER TABLE StoryWZ ADD CONSTRAINT FK_E0D2CBAEA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)");
@@ -37,7 +37,7 @@ class WorkzoneMigration extends AbstractMigration
$this->addSql("ALTER TABLE ValidationDatas ADD CONSTRAINT FK_70E84DDC9D1C3019 FOREIGN KEY (participant_id) REFERENCES ValidationParticipants (id)");
$this->addSql("ALTER TABLE ValidationDatas ADD CONSTRAINT FK_70E84DDCE989605 FOREIGN KEY (basket_element_id) REFERENCES BasketElements (id)");
$this->addSql("ALTER TABLE BasketElements ADD CONSTRAINT FK_C0B7ECB71BE1FB52 FOREIGN KEY (basket_id) REFERENCES Baskets (id)");
$this->addSql("ALTER TABLE ValidationParticipants ADD CONSTRAINT FK_17850D7BF25B0F5B FOREIGN KEY (ValidationSession_id) REFERENCES ValidationSessions (id)");
$this->addSql("ALTER TABLE ValidationParticipants ADD CONSTRAINT FK_17850D7BF25B0F5B FOREIGN KEY (validation_session_id) REFERENCES ValidationSessions (id)");
$this->addSql("ALTER TABLE ValidationParticipants ADD CONSTRAINT FK_17850D7BA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)");
}

View File

@@ -35,11 +35,11 @@ class Installer
$this->createConfigFile($abConn, $serverName, $binaryData, $dataPath);
try {
$this->createAB();
$this->createAB($abConn);
$user = $this->createUser($email, $password);
$this->createDefaultUsers();
if (null !== $dbConn) {
$this->createDB($dbConn, $template);
$this->createDB($dbConn, $template, $user);
}
} catch (\Exception $e) {
$this->rollbackInstall($abConn, $dbConn);
@@ -56,11 +56,12 @@ class Installer
$this->phraseaIndexer = $path;
}
private function createDB(Connection $dbConn = null, $template)
private function createDB(Connection $dbConn = null, $template, User $admin)
{
$template = new \SplFileInfo(__DIR__ . '/../../../conf.d/data_templates/' . $template . '-simple.xml');
$databox = \databox::create($this->app, $dbConn, $template);
$this->app['acl']->get($this->app['authentication']->getUser())
$this->app['acl']->get($admin)
->give_access_to_sbas([$databox->get_sbas_id()])
->update_rights_to_sbas(
$databox->get_sbas_id(), [
@@ -69,10 +70,10 @@ class Installer
]
);
$collection = \collection::create($this->app, $databox, $this->app['phraseanet.appbox'], 'test', $this->app['authentication']->getUser());
$collection = \collection::create($this->app, $databox, $this->app['phraseanet.appbox'], 'test', $admin);
$this->app['acl']->get($this->app['authentication']->getUser())->give_access_to_base([$collection->get_base_id()]);
$this->app['acl']->get($this->app['authentication']->getUser())->update_rights_to_base($collection->get_base_id(), [
$this->app['acl']->get($admin)->give_access_to_base([$collection->get_base_id()]);
$this->app['acl']->get($admin)->update_rights_to_base($collection->get_base_id(), [
'canpush' => 1, 'cancmd' => 1
, 'canputinalbum' => 1, 'candwnldhd' => 1, 'candwnldpreview' => 1, 'canadmin' => 1
, 'actif' => 1, 'canreport' => 1, 'canaddrecord' => 1, 'canmodifrecord' => 1
@@ -95,7 +96,6 @@ class Installer
private function createUser($email, $password)
{
$user = $this->app['manipulator.user']->createUser($email, $password, $email, true);
$this->app['authentication']->openAccount($user);
return $user;
}
@@ -145,16 +145,19 @@ class Installer
return;
}
private function createAB()
private function createAB(Connection $abConn)
{
$metadatas = $this->app['EM']->getMetadataFactory()->getAllMetadata();
// set default orm to the application box
$this->app['orm.ems.default'] = $this->app['hash.dsn']($this->app['db.dsn']($abConn->getParams()));
if (!empty($metadatas)) {
$metadata = $this->app['orm.em']->getMetadataFactory()->getAllMetadata();
if (!empty($metadata)) {
// Create SchemaTool
$tool = new SchemaTool($this->app['EM']);
$tool = new SchemaTool($this->app['orm.em']);
// Create schema
$tool->dropSchema($metadatas);
$tool->createSchema($metadatas);
$tool->dropSchema($metadata);
$tool->createSchema($metadata);
}
$this->app['phraseanet.appbox']->insert_datas($this->app);

View File

@@ -12,6 +12,7 @@
namespace Alchemy\Phrasea\Setup\Version;
use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Core\Version;
/**
* In version 3.9 the user table have been removed.
@@ -30,6 +31,10 @@ class MailChecker
*/
public static function getWrongEmailUsers(Application $app, $table = 'usr')
{
if (version_compare(Version::getNumber(), '3.9', '>')) {
return [];
}
$sql = 'SELECT usr_mail, usr_id, last_conn, usr_login FROM '. $table .' WHERE usr_mail IS NOT NULL';
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute();

View File

@@ -39,20 +39,20 @@ class PreSchemaUpgradeCollection
if ($upgrade->isApplyable($app)) {
try {
$upgrade->apply(
$app['EM'],
$app['orm.em'],
$app['phraseanet.appbox'],
$app['doctrine-migration.configuration']
);
$applied[] = $upgrade;
} catch (\Exception $e) {
$upgrade->rollback(
$app['EM'],
$app['orm.em'],
$app['phraseanet.appbox'],
$app['doctrine-migration.configuration']
);
foreach (array_reverse($applied) as $done) {
$done->rollback(
$app['EM'],
$app['orm.em'],
$app['phraseanet.appbox'],
$app['doctrine-migration.configuration']
);

View File

@@ -32,7 +32,7 @@ class Upgrade39Feeds implements PreSchemaUpgradeInterface
*/
public function isApplyable(Application $app)
{
return $this->tableExists($app['EM'], 'feeds');
return $this->tableExists($app['orm.em'], 'feeds');
}
/**

View File

@@ -32,7 +32,7 @@ class Upgrade39Tokens implements PreSchemaUpgradeInterface
*/
public function isApplyable(Application $app)
{
return $this->tableExists($app['EM'], 'tokens');
return $this->tableExists($app['orm.em'], 'tokens');
}
/**

View File

@@ -65,7 +65,7 @@ class Upgrade39Users implements PreSchemaUpgradeInterface
*/
public function isApplyable(Application $app)
{
return false === $this->tableExists($app['EM'], 'Users');
return false === $this->tableExists($app['orm.em'], 'Users');
}
/**
@@ -248,7 +248,7 @@ class Upgrade39Users implements PreSchemaUpgradeInterface
],
"ValidationSessions" => [
"referenced_by" => [
"ValidationParticipants" => "ValidationSession_id"
"ValidationParticipants" => "validation_session_id"
],
'field' => ['initiator_id'],
],

View File

@@ -1364,8 +1364,8 @@ class ArchiveJob extends AbstractJob
{
$lazaretSession = new LazaretSession();
$app['EM']->persist($lazaretSession);
$app['EM']->flush();
$app['orm.em']->persist($lazaretSession);
$app['orm.em']->flush();
return $lazaretSession;
}

View File

@@ -75,9 +75,9 @@ class FtpJob extends AbstractJob
{
foreach ($app['repo.ftp-exports']
->findCrashedExports(new \DateTime('-1 month')) as $export) {
$app['EM']->remove($export);
$app['orm.em']->remove($export);
}
$app['EM']->flush();
$app['orm.em']->flush();
}
private function retrieveExports(Application $app)
@@ -238,8 +238,8 @@ class FtpJob extends AbstractJob
$exportElement
->setDone(true)
->setError(false);
$app['EM']->persist($exportElement);
$app['EM']->flush();
$app['orm.em']->persist($exportElement);
$app['orm.em']->flush();
$this->logexport($app, $record, $obj, $ftpLog);
} catch (\Exception $e) {
$state .= $line = $this->translator->trans('task::ftp:File "%file%" (record %record_id%) de la base "%basename%" (Export du Document) : Transfert cancelled (le document n\'existe plus)', ['%file%' => basename($localfile), '%record_id%' => $record_id, '%basename%' => \phrasea::sbas_labels(\phrasea::sbasFromBas($app, $base_id), $app)]) . "\n<br/>";
@@ -250,8 +250,8 @@ class FtpJob extends AbstractJob
$exportElement
->setDone($exportElement->isError())
->setError(true);
$app['EM']->persist($exportElement);
$app['EM']->flush();
$app['orm.em']->persist($exportElement);
$app['orm.em']->flush();
}
}
@@ -289,8 +289,8 @@ class FtpJob extends AbstractJob
$this->log('debug', $line);
$export->incrementCrash();
$app['EM']->persist($export);
$app['EM']->flush();
$app['orm.em']->persist($export);
$app['orm.em']->flush();
}
$this->finalize($app, $export);
@@ -316,16 +316,16 @@ class FtpJob extends AbstractJob
$this->send_mails($app, $export);
if ((int) $error === 0) {
$app['EM']->remove($export);
$app['EM']->flush();
$app['orm.em']->remove($export);
$app['orm.em']->flush();
} else {
$export->setCrash($export->getNbretry());
foreach ($export->getElements() as $element) {
if (!$element->isError()) {
$app['EM']->remove($export);
$app['orm.em']->remove($export);
}
}
$app['EM']->flush();
$app['orm.em']->flush();
}
return $this;

View File

@@ -12,7 +12,7 @@ class FeedEntryProcessor extends AbstractProcessor implements ProcessorInterface
return null;
}
$entry = $this->app['EM']->getRepository('Phraseanet::Entry')->find($data->{"entry_id"});
$entry = $this->app['orm.em']->getRepository('Phraseanet::Entry')->find($data->{"entry_id"});
if (null === $entry) {
return null;

View File

@@ -888,7 +888,6 @@ class ACL implements cache_cacheableInterface
return $this;
} catch (\Exception $e) {
}
$sql = 'SELECT u.* FROM basusr u, bas b, sbas s
@@ -1475,12 +1474,10 @@ class ACL implements cache_cacheableInterface
public function delete_injected_rights_sbas(databox $databox)
{
$sql = 'DELETE FROM collusr WHERE usr_id = :usr_id AND site = :site';
$params = [
':usr_id' => $this->user->getId()
, ':site' => $this->app['conf']->get(['main', 'key'])
];
$stmt = $databox->get_connection()->prepare($sql);
$stmt->execute($params);
$stmt->execute([
':usr_id' => $this->user->getId(), ':site' => $this->app['conf']->get(['main', 'key'])
]);
$stmt->closeCursor();
return $this;

View File

@@ -199,10 +199,10 @@ class Session_Logger
$module->setSession($session);
$session->addModule($module);
$app['EM']->persist($module);
$app['EM']->persist($session);
$app['orm.em']->persist($module);
$app['orm.em']->persist($session);
$app['EM']->flush();
$app['orm.em']->flush();
}
$appName = [

View File

@@ -55,7 +55,8 @@ class appbox extends base
{
$this->app = $app;
$connexion = $app['conf']->get(['main', 'database']);
$this->connection = $app['dbal.provider']->get($connexion);
$this->connection = $app['db.provider']($connexion);
$this->host = $connexion['host'];
$this->port = $connexion['port'];
@@ -317,6 +318,16 @@ class appbox extends base
$app['filesystem']->mirror($this->app['root.path'] . '/' . $source, $this->app['root.path'] . '/' . $target, null, array('override' => true));
}
// do not apply patches
// just update old database schema
// it is need before applying patches
$advices = $this->upgradeDB(false, $app);
foreach ($this->get_databoxes() as $s) {
$advices = array_merge($advices, $s->upgradeDB(false, $app));
}
// then apply patches
$advices = $this->upgradeDB(true, $app);
foreach ($this->get_databoxes() as $s) {
@@ -327,9 +338,9 @@ class appbox extends base
$app['phraseanet.cache-service']->flushAll();
if ($app['EM']->getConnection()->getDatabasePlatform()->supportsAlterTable()) {
$tool = new SchemaTool($app['EM']);
$metas = $app['EM']->getMetadataFactory()->getAllMetadata();
if ($app['orm.em']->getConnection()->getDatabasePlatform()->supportsAlterTable()) {
$tool = new SchemaTool($app['orm.em']);
$metas = $app['orm.em']->getMetadataFactory()->getAllMetadata();
$tool->updateSchema($metas, true);
}

View File

@@ -822,7 +822,7 @@ abstract class base implements cache_cacheableInterface
$migration = $version->getMigration();
// Inject entity manager
$migration->setEntityManager($app['EM']);
$migration->setEntityManager($app['orm.em']);
// Execute migration if not marked as migrated and not already applied by an older patch
if (!$migration->isAlreadyApplied()) {

View File

@@ -410,6 +410,8 @@ class collection implements cache_cacheableInterface
$this->app['manipulator.registration']->deleteRegistrationsOnCollection($this);
$this->get_databox()->delete_data_from_cache(databox::CACHE_COLLECTIONS);
$appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
phrasea::reset_baseDatas($appbox);
return;
}
@@ -600,9 +602,7 @@ class collection implements cache_cacheableInterface
$new_bas = $conn->lastInsertId();
$databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
$appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
cache_databox::update($app, $sbas_id, 'structure');
phrasea::reset_baseDatas($appbox);

View File

@@ -121,7 +121,7 @@ class databox extends base
throw new NotFoundHttpException(sprintf('databox %d not found', $sbas_id));
}
$this->connection = $app['dbal.provider']->get([
$this->connection = $app['db.provider']([
'host' => $connection_params[$sbas_id]['host'],
'port' => $connection_params[$sbas_id]['port'],
'user' => $connection_params[$sbas_id]['user'],
@@ -489,14 +489,14 @@ class databox extends base
}
foreach ($this->app['repo.story-wz']->findByDatabox($this->app, $this) as $story) {
$this->app['EM']->remove($story);
$this->app['orm.em']->remove($story);
}
foreach ($this->app['repo.basket-elements']->findElementsByDatabox($this) as $element) {
$this->app['EM']->remove($element);
$this->app['orm.em']->remove($element);
}
$this->app['EM']->flush();
$this->app['orm.em']->flush();
$params = [':site_id' => $this->app['conf']->get(['main', 'key'])];
@@ -593,10 +593,19 @@ class databox extends base
$stmt->closeCursor();
$sbas_id = (int) $app['phraseanet.appbox']->get_connection()->lastInsertId();
$app['orm.add']([
'host' => $host,
'port' => $port,
'dbname' => $dbname,
'user' => $user,
'password' => $password
]);
$app['phraseanet.appbox']->delete_data_from_cache(appbox::CACHE_LIST_BASES);
$databox = $app['phraseanet.appbox']->get_databox($sbas_id);
$databox->insert_datas();
$databox->setNewStructure(
$data_template, $app['conf']->get(['main', 'storage', 'subdefs'])
);
@@ -616,7 +625,7 @@ class databox extends base
*/
public static function mount(Application $app, $host, $port, $user, $password, $dbname)
{
$conn = $app['dbal.provider']->get([
$conn = $app['db.provider']([
'host' => $host,
'port' => $port,
'user' => $user,

View File

@@ -58,21 +58,21 @@ class patch_320alpha2a extends patchAbstract
public function apply(base $appbox, Application $app)
{
$dql = 'SELECT u FROM Phraseanet:User u WHERE u.nonce IS NULL';
$q = $app['EM']->createQuery($dql);
$q = $app['orm.em']->createQuery($dql);
$q->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$users = $q->getResult();
$n = 0;
foreach ($users as $user) {
$user->setNonce($app['random.medium']->generateString(64));
$app['EM']->persist($user);
$app['orm.em']->persist($user);
$n++;
if ($n %100 === 0) {
$app['EM']->flush();
$app['orm.em']->flush();
}
}
$app['EM']->flush();
$app['orm.em']->flush();
$sql = 'SELECT task_id, `class` FROM task2';
$stmt = $appbox->get_connection()->prepare($sql);

View File

@@ -16,6 +16,7 @@ use Alchemy\Phrasea\Model\Entities\FeedItem;
use Alchemy\Phrasea\Model\Entities\FeedPublisher;
use Gedmo\Timestampable\TimestampableListener;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Alchemy\Phrasea\Model\Entities\User;
class patch_320alpha4b extends patchAbstract
{
@@ -84,9 +85,9 @@ class patch_320alpha4b extends patchAbstract
$date_ref = new DateTime();
$n = 0;
$app['EM']->getEventManager()->removeEventSubscriber(new TimestampableListener());
$app['orm.em']->getEventManager()->removeEventSubscriber(new TimestampableListener());
foreach ($rs as $row) {
if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
@@ -99,8 +100,8 @@ class patch_320alpha4b extends patchAbstract
$publishers = $feed->getPublishers();
$entry = new FeedEntry();
$entry->setAuthorEmail($user->getEmail());
$entry->setAuthorName($user->getDisplayName());
$entry->setAuthorEmail((string) $user->getEmail());
$entry->setAuthorName((string) $user->getDisplayName());
$entry->setFeed($feed);
$entry->setPublisher($publishers->first());
$entry->setTitle($row['name']);
@@ -134,31 +135,31 @@ class patch_320alpha4b extends patchAbstract
$entry->addItem($item);
$item->setRecordId($record->get_record_id());
$item->setSbasId($record->get_sbas_id());
$app['EM']->persist($item);
$app['orm.em']->persist($item);
} catch (NotFoundHttpException $e) {
}
}
$app['EM']->persist($entry);
$app['orm.em']->persist($entry);
$sql = 'UPDATE ssel SET deleted = "1", migrated="1"
WHERE ssel_id = :ssel_id';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute([':ssel_id' => $row['ssel_id']]);
$stmt->closeCursor();
$app['EM']->persist($feed);
$app['orm.em']->persist($feed);
$n++;
if ($n % 1000 == 0) {
$app['EM']->flush();
$app['EM']->clear();
$app['orm.em']->flush();
$app['orm.em']->clear();
}
}
$this->set_feed_dates($date_ref);
$app['EM']->flush();
$app['EM']->clear();
$app['orm.em']->flush();
$app['orm.em']->clear();
$app['EM']->getEventManager()->removeEventSubscriber(new TimestampableListener());
$app['orm.em']->getEventManager()->removeEventSubscriber(new TimestampableListener());
return true;
}
@@ -200,15 +201,15 @@ class patch_320alpha4b extends patchAbstract
$feed->setSubtitle('');
$feed->addPublisher($publisher);
$publisher->setFeed($feed);
$publisher->setOwner(true);
$publisher->setIsOwner(true);
$publisher->setUser($user);
if ($homelink) {
$feed->setPublic(true);
$feed->setIsPublic(true);
$app['EM']->persist($feed);
$app['EM']->persist($user);
$app['EM']->flush();
$app['orm.em']->persist($feed);
$app['orm.em']->persist($user);
$app['orm.em']->flush();
} elseif ($pub_restrict == 1) {
$collections = $app['acl']->get($user)->get_granted_base();

View File

@@ -67,9 +67,14 @@ class patch_360alpha1a extends patchAbstract
$stories = [];
$sql = 'SELECT sbas_id, rid as record_id, usr_id
$sql = <<<SQL
SELECT
sbas_id,
rid as record_id,
usr_id
FROM ssel
WHERE temporaryType = "1"';
WHERE temporaryType = "1"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
@@ -88,9 +93,13 @@ class patch_360alpha1a extends patchAbstract
$current[$serial] = $serial;
}
$sql = 'DELETE FROM ssel
WHERE temporaryType="1" AND record_id = :record_id
AND usr_id = :usr_id AND sbas_id = :sbas_id';
$sql = <<<SQL
DELETE FROM ssel
WHERE temporaryType="1"
AND record_id = :record_id
AND usr_id = :usr_id
AND sbas_id = :sbas_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
@@ -105,30 +114,52 @@ class patch_360alpha1a extends patchAbstract
$stmt->closeCursor();
$sql = 'INSERT INTO StoryWZ
(
SELECT null as id, sbas_id, rid as record_id, usr_id, date as created
$sql = <<<SQL
INSERT INTO StoryWZ (
SELECT
null as id,
usr_id as user_id,
sbas_id,
rid as record_id,
date as created
FROM ssel
INNER JOIN Users ON usr_id = Users.id
WHERE temporaryType = "1"
)';
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'INSERT INTO Baskets
(
SELECT ssel_id as id, name, descript as description, usr_id, 1 as is_read
, pushFrom as pusher_id, 0 as archived, date as created, updater as updated
$sql = <<<SQL
INSERT INTO Baskets (
SELECT
ssel_id as id,
usr_id as user_id,
pushFrom as pusher_id,
name,
descript as description,
1 as is_read,
0 as archived,
date as created,
updater as updated
FROM ssel
INNER JOIN Users a ON ssel.usr_id = a.id
INNER JOIN Users b ON ssel.pushFrom = b.id
WHERE temporaryType = "0"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = <<<SQL
SELECT ssel_id
FROM ssel
WHERE temporaryType = "0"
)';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'SELECT ssel_id FROM ssel WHERE temporaryType = "0"';
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
@@ -137,10 +168,18 @@ class patch_360alpha1a extends patchAbstract
$sselcont_ids = [];
foreach ($rs as $row) {
$sql = 'SELECT c.sselcont_id, c.record_id, b.sbas_id
FROM sselcont c, bas b, ssel s
WHERE s.temporaryType = "0" AND b.base_id = c.base_id
AND c.ssel_id = :ssel_id AND s.ssel_id = c.ssel_id';
$sql = <<<SQL
SELECT
c.sselcont_id,
c.record_id,
b.sbas_id
FROM sselcont c
INNER JOIN bas b ON (b.base_id = c.base_id)
INNER JOIN ssel s ON (s.ssel_id = c.ssel_id)
INNER JOIN Baskets ba ON (ba.id = s.ssel_id)
WHERE s.temporaryType = "0"
AND c.ssel_id = :ssel_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute([':ssel_id' => $row['ssel_id']]);
@@ -160,7 +199,10 @@ class patch_360alpha1a extends patchAbstract
}
}
$sql = 'DELETE FROM sselcont WHERE sselcont_id = :sselcont_id';
$sql = <<<SQL
DELETE FROM sselcont
WHERE sselcont_id = :sselcont_id
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($sselcont_ids as $sselcont_id) {
@@ -169,68 +211,111 @@ class patch_360alpha1a extends patchAbstract
$stmt->closeCursor();
$sql = 'INSERT INTO BasketElements
(
SELECT sselcont_id as id, c.ssel_id as basket_id, record_id, b.sbas_id, c.ord,
s.date as created, s.updater as updated
FROM sselcont c, ssel s, bas b
WHERE temporaryType = "0" AND b.base_id = c.base_id AND s.ssel_id = c.ssel_id
)';
$sql = <<<SQL
INSERT INTO BasketElements (
SELECT
sselcont_id as id,
c.ssel_id as basket_id,
record_id,
b.sbas_id,
c.ord,
s.date as created,
s.updater as updated
FROM sselcont c
INNER JOIN ssel s ON (s.ssel_id = c.ssel_id)
INNER JOIN Baskets a ON (a.id = s.ssel_id)
INNER JOIN bas b ON (b.base_id = c.base_id)
WHERE s.temporaryType = "0"
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE Baskets SET pusher_id = NULL WHERE pusher_id = 0';
$sql = <<<SQL
UPDATE Baskets
SET pusher_id = NULL
WHERE pusher_id = 0
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'INSERT INTO ValidationSessions
(
SELECT null as id, v.ssel_id as basket_id ,created_on as created
,updated_on as updated ,expires_on as expires
,v.usr_id as initiator_id
FROM ssel s, validate v
WHERE v.ssel_id = s.ssel_id AND v.usr_id = s.usr_id
)';
$sql = <<<SQL
INSERT INTO ValidationSessions (
SELECT null as id,
v.usr_id as initiator_id,
v.ssel_id as basket_id,
v.created_on as created,
v.updated_on as updated,
v.expires_on as expires
FROM validate v
INNER JOIN Baskets b ON (b.id = v.ssel_id)
INNER JOIN Users u ON (u.id = v.usr_id)
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'INSERT INTO ValidationParticipants
(
SELECT v.id as id, v.usr_id
, 1 AS is_aware, confirmed as is_confirmed, 1 as can_agree
, can_see_others, last_reminder AS reminded
, vs.`id` AS ValidationSession_id
FROM validate v, ssel s, ValidationSessions vs
WHERE s.ssel_id = v.ssel_id AND vs.basket_id = v.ssel_id
)';
$sql = <<<SQL
INSERT INTO ValidationParticipants (
SELECT
v.id AS id,
v.usr_id AS user_id,
1 AS is_aware,
confirmed AS is_confirmed,
1 AS can_agree,
can_see_others,
last_reminder AS reminded,
vs.`id` AS validation_session_id
FROM validate v
INNER JOIN Baskets b ON (b.id = v.ssel_id)
INNER JOIN ValidationSessions vs ON (vs.basket_id = b.id)
INNER JOIN Users u ON (u.id = v.usr_id)
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'SELECT user_id, basket_id, p.id as participant_id
FROM ValidationParticipants p, ValidationSessions s
WHERE p.ValidationSession_Id = s.id';
$sql = <<<SQL
SELECT
p.user_id,
s.basket_id,
p.id as participant_id
FROM ValidationParticipants p
INNER JOIN ValidationSessions s ON (s.id = p.validation_session_id)
INNER JOIN Users u ON (u.id = p.user_id)
INNER JOIN Baskets b ON (b.id = s.basket_id)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$sql = 'INSERT INTO ValidationDatas
(
SELECT d.id , :participant_id as participant_id, d.sselcont_id, d.agreement
,d.note, d.updated_on as updated
FROM validate v, validate_datas d, sselcont c
WHERE c.sselcont_id = d.sselcont_id AND v.id = d.validate_id
$sql = <<<SQL
INSERT INTO ValidationDatas (
SELECT
d.id ,
:participant_id AS participant_id,
d.sselcont_id AS basket_element_id,
d.agreement,
d.note, d.updated_on AS updated
FROM validate v
INNER JOIN validate_datas d ON (v.id = d.validate_id)
INNER JOIN Baskets b ON (v.ssel_id = b.id)
INNER JOIN BasketElements be ON (be.id = d.sselcont_id)
AND v.usr_id = :usr_id AND v.ssel_id = :basket_id
)';
)
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
foreach ($rs as $row) {
$params = [
@@ -243,15 +328,21 @@ class patch_360alpha1a extends patchAbstract
$stmt->closeCursor();
$sql = 'UPDATE ValidationDatas
SET agreement = NULL where agreement = "0"';
$sql = <<<SQL
UPDATE ValidationDatas
SET agreement = NULL
WHERE agreement = "0"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
$sql = 'UPDATE ValidationDatas
SET agreement = "0" where agreement = "-1"';
$sql = <<<SQL
UPDATE ValidationDatas
SET agreement = "0"
WHERE agreement = "-1"
SQL;
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();

View File

@@ -56,7 +56,7 @@ class patch_360alpha2a extends patchAbstract
*/
public function apply(base $appbox, Application $app)
{
$app['EM']->getConnection()->executeUpdate('UPDATE Users u SET u.email = NULL WHERE u.email IS NOT NULL AND u.deleted = 1');
$app['orm.em']->getConnection()->executeUpdate('UPDATE Users u SET u.email = NULL WHERE u.email IS NOT NULL AND u.deleted = 1');
return true;
}

View File

@@ -69,7 +69,8 @@ class patch_361alpha1a extends patchAbstract
$sbas_id = (int) $row['sbas_id'];
try {
$connbas = $app['phraseanet.appbox']->get_databox($sbas_id)->get_connection()->connect();
$connbas = $app['phraseanet.appbox']->get_databox($sbas_id)->get_connection();
$connbas->connect();
} catch (\Exception $e) {
$conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
$conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
@@ -93,7 +94,7 @@ class patch_361alpha1a extends patchAbstract
$n = 0;
$perPage = 100;
$query = $app['EM']->createQuery($dql)
$query = $app['orm.em']->createQuery($dql)
->setFirstResult($n)
->setMaxResults($perPage);
@@ -102,7 +103,7 @@ class patch_361alpha1a extends patchAbstract
$count = count($paginator);
while ($n < $count) {
$query = $app['EM']->createQuery($dql)
$query = $app['orm.em']->createQuery($dql)
->setFirstResult($n)
->setMaxResults($perPage);
@@ -121,10 +122,10 @@ class patch_361alpha1a extends patchAbstract
}
$n += $perPage;
$app['EM']->flush();
$app['orm.em']->flush();
}
$app['EM']->flush();
$app['orm.em']->flush();
return true;
}

View File

@@ -81,16 +81,16 @@ class patch_370alpha7a extends patchAbstract
//order matters for foreign keys constraints
//truncate all altered tables
$this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretAttribute');
$this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretCheck');
$this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretFile');
$this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretSession');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretAttribute');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretCheck');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretFile');
$this->truncateTable($app['orm.em'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretSession');
$i = 0;
foreach ($rs as $row) {
$filePath = $app['tmp.lazaret.path'].'/'.$row['filepath'];
if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
@@ -140,17 +140,17 @@ class patch_370alpha7a extends patchAbstract
$lazaretFile->setCreated(new \DateTime($row['created_on']));
$lazaretFile->setSession($lazaretSession);
$app['EM']->persist($lazaretFile);
$app['orm.em']->persist($lazaretFile);
if (0 === ++$i % 100) {
$app['EM']->flush();
$app['EM']->clear();
$app['orm.em']->flush();
$app['orm.em']->clear();
}
}
}
$app['EM']->flush();
$app['EM']->clear();
$app['orm.em']->flush();
$app['orm.em']->clear();
$stmt->closeCursor();

View File

@@ -212,9 +212,9 @@ class patch_370alpha8a extends patchAbstract
->setSettings($settings)
->setPeriod($period)
->setStatus(Task::STATUS_STARTED);
$app['EM']->persist($task);
$app['orm.em']->persist($task);
}
$app['EM']->flush();
$app['orm.em']->flush();
return true;
}

View File

@@ -73,7 +73,7 @@ class patch_380alpha11a extends patchAbstract
}
foreach ($rs as $row) {
if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
@@ -117,14 +117,14 @@ class patch_380alpha11a extends patchAbstract
$session->addModule($module);
$app['EM']->persist($module);
$app['orm.em']->persist($module);
}
}
$app['EM']->persist($session);
$app['orm.em']->persist($session);
}
$app['EM']->flush();
$app['orm.em']->flush();
return true;
}

View File

@@ -78,16 +78,16 @@ class patch_380alpha4a extends patchAbstract
$failure->setLocked(!!$row['locked']);
$failure->setUsername($row['login']);
$app['EM']->persist($failure);
$app['orm.em']->persist($failure);
if (0 === $n++ % 1000) {
$app['EM']->flush();
$app['EM']->clear();
$app['orm.em']->flush();
$app['orm.em']->clear();
}
}
$app['EM']->flush();
$app['EM']->clear();
$app['orm.em']->flush();
$app['orm.em']->clear();
return true;
}

View File

@@ -70,19 +70,19 @@ class patch_383alpha1a extends patchAbstract
foreach ($rows as $row) {
if (null !== $session = $app['repo.sessions']->find($row['id'])) {
$app['EM']->remove($session);
$app['orm.em']->remove($session);
}
}
// Remove API sessions
$query = $app['EM']->createQuery('SELECT s FROM Phraseanet:Session s WHERE s.user_agent LIKE :guzzle');
$query = $app['orm.em']->createQuery('SELECT s FROM Phraseanet:Session s WHERE s.user_agent LIKE :guzzle');
$query->setParameter(':guzzle', 'Guzzle%');
foreach ($query->getResult() as $session) {
$app['EM']->remove($session);
$app['orm.em']->remove($session);
}
$app['EM']->flush();
$app['orm.em']->flush();
return true;
}
@@ -92,7 +92,7 @@ class patch_383alpha1a extends patchAbstract
$rsm = (new ResultSetMapping())->addScalarResult('Name', 'Name');
$ret = false;
foreach ($app['EM']->createNativeQuery('SHOW TABLE STATUS', $rsm)->getResult() as $row) {
foreach ($app['orm.em']->createNativeQuery('SHOW TABLE STATUS', $rsm)->getResult() as $row) {
if ('Session' === $row['Name']) {
$ret = true;
break;

View File

@@ -66,17 +66,17 @@ class patch_383alpha2a extends patchAbstract
foreach ($rows as $row) {
try {
$vsession = $app['EM']->createQuery('SELECT PARTIAL s.{id} FROM Phraseanet:ValidationSession s WHERE s.id = :id')
$vsession = $app['orm.em']->createQuery('SELECT PARTIAL s.{id} FROM Phraseanet:ValidationSession s WHERE s.id = :id')
->setParameters(['id' => $row['validation_session_id']])
->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)
->getSingleResult();
$app['EM']->remove($vsession);
$app['orm.em']->remove($vsession);
} catch (NoResultException $e) {
}
}
$app['EM']->flush();
$app['orm.em']->flush();
return true;
}

View File

@@ -42,7 +42,7 @@ class patch_386alpha4a implements patchInterface
*/
public function getDoctrineMigrations()
{
return array();
return array('user-list');
}
/**
@@ -58,12 +58,12 @@ class patch_386alpha4a implements patchInterface
*/
public function apply(base $appbox, Application $app)
{
$repo = $app['EM']->getRepository('Phraseanet:UsrList');
foreach ($app['EM']->getRepository('Phraseanet:User')->findDeleted() as $user) {
$repo = $app['orm.em']->getRepository('Phraseanet:UsrList');
foreach ($app['orm.em']->getRepository('Phraseanet:User')->findDeleted() as $user) {
foreach ($repo->findUserLists($user) as $list) {
$app['EM']->remove($list);
$app['orm.em']->remove($list);
}
$app['EM']->flush();
$app['orm.em']->flush();
}
return true;

View File

@@ -69,7 +69,7 @@ class patch_390alpha12a extends patchAbstract
$finder = new Finder();
$finder
->depth(0)
->in($app['plugins.directory'])
->in($app['plugin.path'])
->directories();
$plugins = [];

View File

@@ -60,7 +60,7 @@ class patch_390alpha13a implements patchInterface
*/
public function apply(base $appbox, Application $app)
{
$em = $app['EM'];
$em = $app['orm.em'];
$sql = "SELECT date_modif, usr_id, base_id, en_cours, refuser
FROM demand";

View File

@@ -58,7 +58,7 @@ class patch_390alpha14a extends patchAbstract
{
$app['conf']->remove(['main', 'api-timers']);
if ($this->tableHasField($app['EM'], 'api_logs', 'api_log_ressource')) {
if ($this->tableHasField($app['orm.em'], 'api_logs', 'api_log_ressource')) {
$sql = "ALTER TABLE api_logs CHANGE api_log_ressource api_log_resource varchar(64)";
$app['phraseanet.appbox']->get_connection()->executeUpdate($sql);
}

View File

@@ -56,11 +56,11 @@ class patch_390alpha15a extends patchAbstract
*/
public function apply(base $appbox, Application $app)
{
if (!$this->tableExists($app['EM'], 'tokens_backup')) {
if (!$this->tableExists($app['orm.em'], 'tokens_backup')) {
return true;
}
$app['EM']->getConnection()->executeUpdate('
$app['orm.em']->getConnection()->executeUpdate('
INSERT INTO Tokens
(
`value`, user_id, `type`, `data`,

View File

@@ -61,11 +61,11 @@ class patch_390alpha16a extends patchAbstract
$sql = ' SELECT edit_preset_id, creation_date, title, xml, usr_id, sbas_id
FROM edit_presets';
$em = $app['EM'];
$em = $app['orm.em'];
$n = 0;
$em->getEventManager()->removeEventSubscriber(new TimestampableListener());
foreach ($app['phraseanet.appbox']->get_connection()->fetchAll($sql) as $row) {
if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
$preset = new Preset();

View File

@@ -57,14 +57,14 @@ class patch_390alpha17a extends patchAbstract
*/
public function apply(base $appbox, Application $app)
{
$this->fillApplicationTable($app['EM']);
$this->fillAccountTable($app['EM']);
$this->fillLogTable($app['EM']);
$this->fillCodeTable($app['EM']);
$this->fillRefreshTokenTable($app['EM']);
$this->fillOauthTokenTable($app['EM']);
$this->setOauthTokenExpiresToNull($app['EM']);
$this->updateLogsTable($app['EM']);
$this->fillApplicationTable($app['orm.em']);
$this->fillAccountTable($app['orm.em']);
$this->fillLogTable($app['orm.em']);
$this->fillCodeTable($app['orm.em']);
$this->fillRefreshTokenTable($app['orm.em']);
$this->fillOauthTokenTable($app['orm.em']);
$this->setOauthTokenExpiresToNull($app['orm.em']);
$this->updateLogsTable($app['orm.em']);
}
private function fillApplicationTable(EntityManager $em)

View File

@@ -56,33 +56,33 @@ class patch_390alpha18a extends patchAbstract
*/
public function apply(base $appbox, Application $app)
{
$app['EM']->getConnection()->executeUpdate('
$app['orm.em']->getConnection()->executeUpdate('
DELETE lf FROM LazaretFiles lf
INNER JOIN LazaretSessions ls ON (ls.id = lf.lazaret_session_id)
LEFT JOIN Users u ON (ls.user_id = u.id)
WHERE u.id IS NULL'
);
$app['EM']->getConnection()->executeUpdate('
$app['orm.em']->getConnection()->executeUpdate('
DELETE ls FROM LazaretSessions AS ls
LEFT JOIN Users u ON (ls.user_id = u.id)
WHERE u.id IS NULL'
);
$app['EM']->getConnection()->executeUpdate('
$app['orm.em']->getConnection()->executeUpdate('
DELETE fi FROM FeedItems AS fi
INNER JOIN FeedEntries fe ON (fe.id = fi.entry_id)
LEFT JOIN Users u ON (fe.publisher_id = u.id)
WHERE u.id IS NULL'
);
$app['EM']->getConnection()->executeUpdate('
$app['orm.em']->getConnection()->executeUpdate('
DELETE fe FROM FeedEntries AS fe
LEFT JOIN Users u ON (fe.publisher_id = u.id)
WHERE u.id IS NULL'
);
$app['EM']->getConnection()->executeUpdate(
$app['orm.em']->getConnection()->executeUpdate(
'DELETE se FROM Sessions AS se
LEFT JOIN Users u ON (se.user_id = u.id)
WHERE u.id IS NULL'

View File

@@ -79,7 +79,7 @@ class patch_390alpha1a extends patchAbstract
$stmt->closeCursor();
$n = 0;
$em = $app['EM'];
$em = $app['orm.em'];
$em->getEventManager()->removeEventSubscriber(new TimestampableListener());
foreach ($rs as $row) {
@@ -93,12 +93,12 @@ class patch_390alpha1a extends patchAbstract
$todo = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) {
if (null === $user = $this->loadUser($app['orm.em'], $row['usr_id'])) {
continue;
}
try {
$basket = $app['EM']->createQuery('SELECT PARTIAL b.{id} FROM Phraseanet:Basket b WHERE b.id = :id')
$basket = $app['orm.em']->createQuery('SELECT PARTIAL b.{id} FROM Phraseanet:Basket b WHERE b.id = :id')
->setParameters(['id' => $row['ssel_id']])
->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)
->getSingleResult();
@@ -127,7 +127,7 @@ class patch_390alpha1a extends patchAbstract
foreach ($elements as $element) {
$orderElement = new OrderElement();
$user = $this->loadUser($app['EM'], $row['usr_id']);
$user = $this->loadUser($app['orm.em'], $row['usr_id']);
$orderElement->setBaseId($element['base_id'])
->setDeny($element['deny'] === null ? null : (Boolean) $element['deny'])
->setOrder($order)

Some files were not shown because too many files have changed in this diff Show More