diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e2832450f..31a8366a7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - BC Break : Removed `bin/console check:config` command. - BC Break : Removed `bin/console check:system` command, replaced by `bin/setup check:system`. - BC Break : Removed `bin/console system:upgrade` command, replaced by `bin/setup system:upgrade`. + - BC break : Configuration simplification, optimized for performances. - SwiftMailer integration (replaces PHPMailer). - Emails now include an HTML view. diff --git a/UPGRADE-3.8.md b/UPGRADE-3.8.md index 10fe68a950..576f3e679e 100644 --- a/UPGRADE-3.8.md +++ b/UPGRADE-3.8.md @@ -9,7 +9,16 @@ some new features, robustness and stability. These enhancements are described in the CHANGELOG file. The purpose of this document is to provide a list a BC breaks / Changes. -## Nginx +## Configuration : + +Configuration has been drastically simplified. There is now one file to +configure Phraseanet : `config/configuration.yml`. + +This file is now compiled to plain PHP for best performances. If you ever edit +this file manually, please run the `bin/console compile:configuration` command +to re-compile the configuration. + +## Nginx : If you are using Nginx as Phraseanet web-server, you must update you virtual-host configuration as follow : diff --git a/bin/console b/bin/console index 48ac46beb3..6f43d7fe98 100755 --- a/bin/console +++ b/bin/console @@ -76,8 +76,6 @@ try { $app->command(new \module_console_schedulerState('scheduler:state')); $app->command(new \module_console_schedulerStop('scheduler:stop')); $app->command(new \module_console_schedulerStart('scheduler:start')); - $app->command(new \module_console_fileEnsureProductionSetting('check:ensure-production-settings')); - $app->command(new \module_console_fileEnsureDevSetting('check:ensure-dev-settings')); $app->command(new Mailtest('mail:test')); diff --git a/build-env.sh b/build-env.sh index 1d8b1b70b0..d3d63623b3 100755 --- a/build-env.sh +++ b/build-env.sh @@ -1,4 +1,4 @@ -rm -f config/services.yml config/connexions.yml config/config.yml config/config.inc config/connexion.inc config/_GV.php config/_GV.php.old +rm -f config/configuration.yml config/services.yml config/connexions.yml config/config.yml config/config.inc config/connexion.inc config/_GV.php config/_GV.php.old cp -f hudson/connexion.inc config/ cp -f hudson/_GV.php config/ php vendors.php diff --git a/config/binaries.sample.yml b/config/binaries.sample.yml deleted file mode 100644 index 8d7075e07e..0000000000 --- a/config/binaries.sample.yml +++ /dev/null @@ -1,13 +0,0 @@ -binaries: - php_binary: '' - convert_binary: '' - composite_binary: '' - swf_extract_binary: '' - pdf2swf_binary: '' - swf_render_binary: '' - unoconv_binary: '' - ffmpeg_binary: '' - ffprobe_binary: '' - mp4box_binary: '' - pdftotext_binary: '' - ghostscript_binary: '' diff --git a/config/config.sample.yml b/config/config.sample.yml deleted file mode 100644 index 859d460474..0000000000 --- a/config/config.sample.yml +++ /dev/null @@ -1,219 +0,0 @@ -#Here's the main configuration file which is loaded when phraseanet bootstraps - -#Declare which environment will be used by the application - -environment : prod -key : null - -#Declare all your environment configurations - -################# -# DEVELOPPEMENT # -################# -dev: - #Phraseanet refers to phraseanet app specific configuration - phraseanet: - servername: 'http://sub.domain.tld/' - maintenance: false - debug: true - display_errors: true - - #Assign your phraseanet application connection - #Connections are defined in connexions.yml configuration file - database: main_connexion - api-timers: true - - #Assign your template engine service & ORM service - #Services are defined in service.yml configuration file - template_engine: twig_debug - orm: doctrine_dev - cache: array_cache - opcodecache: array_cache - border-manager: border_manager - search-engine: phrasea - task-manager: task_manager - authentication: - auto-create: - enabled: false - templates: [] - captcha: - enabled: true - trials-before-failure: 9 - providers: - facebook: - enabled: false - options: - app-id: '' - secret: '' - twitter: - enabled: false - options: - consumer-key: '' - consumer-secret: '' - google-plus: - enabled: false - options: - client-id: '' - client-secret: '' - github: - enabled: false - options: - client-id: '' - client-secret: '' - viadeo: - enabled: false - options: - client-id: '' - client-secret: '' - linkedin: - enabled: false - options: - client-id: '' - client-secret: '' - registration-fields: - - - name: company - required: true - - - name: firstname - required: true - - - name: geonameid - required: true - -############## -# PRODUCTION # -############## -prod: - phraseanet: - servername: 'http://sub.domain.tld/' - maintenance: false - debug: false - display_errors: false - database: main_connexion - api-timers: false - - template_engine: twig - orm: doctrine_prod - cache: array_cache - opcodecache: array_cache - border-manager: border_manager - search-engine: phrasea - task-manager: task_manager - authentication: - auto-create: - enabled: false - templates: [] - captcha: - enabled: true - trials-before-failure: 9 - providers: - facebook: - enabled: false - options: - app-id: '' - secret: '' - twitter: - enabled: false - options: - consumer-key: '' - consumer-secret: '' - google-plus: - enabled: false - options: - client-id: '' - client-secret: '' - github: - enabled: false - options: - client-id: '' - client-secret: '' - viadeo: - enabled: false - options: - client-id: '' - client-secret: '' - linkedin: - enabled: false - options: - client-id: '' - client-secret: '' - registration-fields: - - - name: company - required: true - - - name: firstname - required: true - - - name: geonameid - required: true - -############## -# TEST # -############## -test: - phraseanet: - servername: 'http://sub.domain.tld/' - maintenance: false - debug: true - display_errors: true - database: main_connexion - api-timers: false - - template_engine: twig_debug - orm: doctrine_test - cache: array_cache - opcodecache: array_cache - border-manager: border_manager - search-engine: phrasea - task-manager: task_manager - authentication: - auto-create: - enabled: false - templates: [] - captcha: - enabled: true - trials-before-failure: 9 - providers: - facebook: - enabled: false - options: - app-id: '' - secret: '' - twitter: - enabled: false - options: - consumer-key: '' - consumer-secret: '' - google-plus: - enabled: false - options: - client-id: '' - client-secret: '' - github: - enabled: false - options: - client-id: '' - client-secret: '' - viadeo: - enabled: false - options: - client-id: '' - client-secret: '' - linkedin: - enabled: false - options: - client-id: '' - client-secret: '' - registration-fields: - - - name: company - required: true - - - name: firstname - required: true - - - name: geonameid - required: true - diff --git a/config/configuration.sample.yml b/config/configuration.sample.yml new file mode 100644 index 0000000000..ceb3177653 --- /dev/null +++ b/config/configuration.sample.yml @@ -0,0 +1,113 @@ +main: + servername: 'http://local.phrasea/' + maintenance: false + database: + host: 127.0.0.1 + port: '3306' + user: root + password: '' + dbname: ab_test + driver: pdo_mysql + charset: UTF8 + database-test: + driver: pdo_sqlite + path: '/tmp/db.sqlite' + charset: UTF8 + api-timers: true + cache: + type: MemcacheCache + options: + host: localhost + port: 11211 + opcodecache: + type: ArrayCache + options: [] + search-engine: + type: Alchemy\Phrasea\SearchEngine\Phrasea\PhraseaEngine + options: [] + task-manager: + options: null +binaries: [] +border-manager: + enabled: true + checkers: + - + type: Checker\Sha256 + enabled: true + - + type: Checker\UUID + enabled: true + - + type: Checker\Colorspace + enabled: false + options: + colorspaces: [cmyk, grayscale, rgb] + - + type: Checker\Dimension + enabled: false + options: + width: 80 + height: 160 + - + type: Checker\Extension + enabled: false + options: + extensions: [jpg, jpeg, bmp, tif, gif, png, pdf, doc, odt, mpg, mpeg, mov, avi, xls, flv, mp3, mp2] + - + type: Checker\Filename + enabled: false + options: + sensitive: true + - + type: Checker\MediaType + enabled: false + options: + mediatypes: [Audio, Document, Flash, Image, Video] +authentication: + auto-create: + enabled: false + templates: { } + captcha: + enabled: true + trials-before-failure: 9 + providers: + facebook: + enabled: false + options: + app-id: '' + secret: '' + twitter: + enabled: false + options: + consumer-key: '' + consumer-secret: '' + google-plus: + enabled: false + options: + client-id: '' + client-secret: '' + github: + enabled: false + options: + client-id: '' + client-secret: '' + viadeo: + enabled: false + options: + client-id: '' + client-secret: '' + linkedin: + enabled: false + options: + client-id: '' + client-secret: '' +registration-fields: + - + name: company + required: true + - + name: firstname + required: true + - + name: geonameid + required: true diff --git a/config/connexions.sample.yml b/config/connexions.sample.yml deleted file mode 100644 index 138b4c3ef9..0000000000 --- a/config/connexions.sample.yml +++ /dev/null @@ -1,19 +0,0 @@ -#Here you can define many connexions configurations -#Please refer to Doctrine documentation abstraction layer for database connection configuration -#DBAL connection : http://www.doctrine-project.org/docs/dbal/2.1/en/reference/configuration.html - -#Defines a connexion to MYSQL database named main_connexion -main_connexion: - host: - port: - user: - password: - dbname: - driver: pdo_mysql - charset: UTF8 - -#Defines a connexion to a SQLite database named test_connexion -test_connexion: - driver: pdo_sqlite - path: '/tmp/db.sqlite' - charset: UTF8 diff --git a/config/services.sample.yml b/config/services.sample.yml deleted file mode 100644 index 9a15a5541d..0000000000 --- a/config/services.sample.yml +++ /dev/null @@ -1,215 +0,0 @@ -#base service file -Orm: - #Doctrine developement service options - #Service name - doctrine_dev: - type: Orm\Doctrine - options: - #Set automatically propers values for debug - #Query & result caches are setted to Array cache - #Auto-generating Proxy Classes is setted to false - debug: true - #Assign a connexion from connexions.yml to the DataBase Abstraction Layer - dbal: main_connexion - #Available cache driver [memcached, apc, array] - #Query cache : is used to cache the transformation of a DQL query to its SQL counterpart - #Result cache : is used to cache the results of your queries - #Metadata cache : is used to cache entity class metadatas - #If No cache is provided all cache are setted to default_cache which is an array cache type - cache: - query: - service: Cache\array_cache - result: - service: Cache\array_cache - metadata: - service: Cache\array_cache - # Assign a service to log doctrine queries - log: - service: Log\query_logger - - # Doctrine test service options - doctrine_test: - type: Orm\Doctrine - options: - debug: true - #Doctrine use a different connection configuration base to run tests - dbal: test_connexion - cache: - query: - service: Cache\array_cache - result: - service: Cache\array_cache - metadata: - service: Cache\array_cache - log: - service: Log\query_logger - - # Doctrine production service options - doctrine_prod: - type: Orm\Doctrine - options: - debug: false - dbal: main_connexion - cache: - query: - service: Cache\array_cache - result: - service: Cache\array_cache - metadata: - service: Cache\array_cache - -TemplateEngine: - #Define a template engine service - #Only Twig is avalaible as a template engine service - #see http://twig.sensiolabs.org/ - - #Define the service name first - twig: - #Template engine type - type: TemplateEngine\Twig - options: - #When set to true, the generated templates have a __toString() method that you can use to display the generated nodes - debug: false - #The charset used by the templates - charset: utf-8 - #Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) - #And replace them with a null value. When set to true, Twig throws an exception instead (default to false) - strict_variables: false - autoescape: true - #Optimize the node tree before compilation - optimizer: true - - twig_debug: - type: TemplateEngine\Twig - options: - debug: true - charset: utf-8 - strict_variables: true - autoescape: true - optimizer: true - - -Log: - # Define a Log service - # This one is defined to handle the logs of doctrine queries - # Only Monolog is available as a logger service - # Please Notice that for doctrine ONLY a echo logger service is available, see below - # Monolog logger use the PHP Monolog library to handle logs using differents handlers - query_logger: - type: Log\Doctrine\Monolog - options: - #You can precise the output format - #This option is only available when log are used to log doctrine queries - #Available output [vdump, json, yaml] - # vdump : output logs in a var_dump formatted style - # json : output logs in json - # yml : output logs yml - output: json - #Name used for the Monolog channel - channel: query-logger - #Define how the logs will be handled - #Avalaibale Handler are [rotate, stream] - #Rotate handler is used to stores logs to files that are rotated every day - #And a limited number of files are kept by defining the max_day value - #Stream handler is used to stores logs in a single local file - handler: rotate - max_day: 2 - #Name of the file where logs are written - filename: doctrine-query.log - - # Define a phpecho log service for Doctrine - # phpecho logger logs doctrine queries to the standard output using echo/var_dump - # Notice that phpecho logger do not have options - sql_logger: - type: Log\Doctrine\Phpecho - -Cache: - #Define cache services - #There are Four different cache type available [array, xcache, apc, memcache] - #Only a memcache service can take option to define port & host for the memcache server - array_cache: - type: Cache\ArrayCache - - memcache_cache: - type: Cache\MemcacheCache - options: - host: localhost - port: 11211 - - apc_cache: - type: Cache\ApcCache - - xcache_cache: - type: Cache\XcacheCache - - wincache_cache: - type: Cache\WinCacheCache - -Border: - #Define Border service - #The border service handles checks validation constraints against incoming files - border_manager: - type: Border\BorderManager - options: - #Enable validation on incoming files - enabled: true - checkers: - #Check for duplicated file based on their sha256 check sum - - - type: Checker\Sha256 - enabled: true - #Check for duplicated file based on their UUID - - - type: Checker\UUID - enabled: true - #Check colorspace (if applicable) - - - type: Checker\Colorspace - enabled: false - options: - colorspaces: [cmyk, grayscale, rgb] - #Check file dimension (if applicable) - - - type: Checker\Dimension - enabled: false - options: - width: 80 - height: 160 - #Check file extension - #set to false to enable all file extensions - - - type: Checker\Extension - enabled: false - options: - extensions: [jpg, jpeg, bmp, tif, gif, png, pdf, doc, odt, mpg, mpeg, mov, avi, xls, flv, mp3, mp2] - #Check filename - - - type: Checker\Filename - enabled: false - options: - sensitive: true - #Check media type - #Set to false to enable all mediatype - - - type: Checker\MediaType - enabled: false - options: - mediatypes: [Audio, Document, Flash, Image, Video] -SearchEngine: - phrasea: - type: SearchEngine\PhraseaEngine - sphinxsearch: - type: SearchEngine\SphinxSearch - options: - host: localhost - port: 9306 - rt_host: localhost - rt_port: 9308 -TaskManager: - task_manager: - type: TaskManager\TaskManager - options: - # set the threshold for sending task logs to syslog or by mail - # values : task_abstract::[LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERROR | LOG_CRITICAL | LOG_ALERT] - #syslog_level: task_abstract::LOG_ERROR - #maillog_level: task_abstract::LOG_ERROR diff --git a/lib/Alchemy/Phrasea/Application.php b/lib/Alchemy/Phrasea/Application.php index 914ea8516b..f05df5d72a 100644 --- a/lib/Alchemy/Phrasea/Application.php +++ b/lib/Alchemy/Phrasea/Application.php @@ -163,6 +163,7 @@ class Application extends SilexApplication { parent::__construct(); + $this['root.path'] = realpath(__DIR__ . '/../../..'); $this->environment = $environment; if ((int) ini_get('memory_limit') < 2048) { diff --git a/lib/Alchemy/Phrasea/Cache/Cache.php b/lib/Alchemy/Phrasea/Cache/Cache.php index 996b87c393..9995c64985 100644 --- a/lib/Alchemy/Phrasea/Cache/Cache.php +++ b/lib/Alchemy/Phrasea/Cache/Cache.php @@ -20,6 +20,18 @@ use Doctrine\Common\Cache\Cache as DoctrineCache; */ interface Cache extends DoctrineCache { + /** + * Sets the namespace + * + * @param type $namespace + */ + public function setNamespace($namespace); + + /** + * Flushes all data contained in the adapter + */ + public function flushAll(); + /** * Name of the cache driver * @return string diff --git a/lib/Alchemy/Phrasea/Cache/Factory.php b/lib/Alchemy/Phrasea/Cache/Factory.php new file mode 100644 index 0000000000..bbebbd04ea --- /dev/null +++ b/lib/Alchemy/Phrasea/Cache/Factory.php @@ -0,0 +1,142 @@ +createApc($options); + break; + case 'array': + case 'arraycache': + $cache = new ArrayCache(); + break; + case 'memcache': + case 'memcachecache': + $cache = $this->createMemcache($options); + break; + case 'redis': + case 'rediscache': + $cache = $this->createRedis($options); + break; + case 'wincache': + case 'wincachecache': + $cache = $this->createWincache($options); + break; + case 'xcache': + case 'xcachecache': + $cache = $this->createXcache($options); + break; + default: + throw new RuntimeException(sprintf('Unnown cache type %s', $name)); + } + + return $cache; + } + + private function createXcache($options) + { + if (!extension_loaded('xcache')) { + throw new RuntimeException('The XCache cache requires the XCache extension.'); + } + + return new XcacheCache(); + } + + private function createWincache($options) + { + if (!extension_loaded('wincache')) { + throw new RuntimeException('The WinCache cache requires the WinCache extension.'); + } + + return new WinCacheCache(); + } + + private function createRedis($options) + { + if (!extension_loaded('redis')) { + throw new RuntimeException('The Redis cache requires the Redis extension.'); + } + + $redis = new \Redis(); + + $host = isset($options['host']) ? $options['host'] : 'localhost'; + $port = isset($options['port']) ? $options['port'] : 6379; + + if (!$redis->connect($host, $port)) { + throw new RuntimeException(sprintf("Redis instance with host '%s' and port '%s' is not reachable", $host, $port)); + } + if (!defined('Redis::SERIALIZER_IGBINARY') || !$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY)) { + $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); + } + + $cache = new RedisCache(); + $cache->setRedis($redis); + + return $cache; + } + + private function createMemcache($options) + { + if (!extension_loaded('memcache')) { + throw new RuntimeException('The Memcache cache requires the Memcache extension.'); + } + + $host = isset($options['host']) ? $options['host'] : 'localhost'; + $port = isset($options['port']) ? $options['port'] : 11211; + + $memcache = new \Memcache(); + $memcache->addServer($host, $port); + + $key = sprintf("%s:%s", $host, $port); + $stats = @$memcache->getExtendedStats(); + + if (!isset($stats[$key]) || false === $stats[$key]) { + throw new RuntimeException(sprintf("Memcache instance with host '%s' and port '%s' is not reachable", $host, $port)); + } + + $cache = new MemcacheCache(); + $cache->setMemcache($memcache); + + return $cache; + } + + private function createApc($options) + { + if (!extension_loaded('apc')) { + throw new RuntimeException('The APC cache requires the APC extension.'); + } + + return new ApcCache(); + } +} diff --git a/lib/Alchemy/Phrasea/Cache/Manager.php b/lib/Alchemy/Phrasea/Cache/Manager.php index a566838193..0ed4ead53d 100644 --- a/lib/Alchemy/Phrasea/Cache/Manager.php +++ b/lib/Alchemy/Phrasea/Cache/Manager.php @@ -11,102 +11,110 @@ namespace Alchemy\Phrasea\Cache; -use Alchemy\Phrasea\Application; -use Alchemy\Phrasea\Core\Service\Builder; -use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; -use Symfony\Component\Yaml\Yaml; +use Alchemy\Phrasea\Exception\RuntimeException; +use Alchemy\Phrasea\Core\Configuration\Compiler; +use Alchemy\Phrasea\Cache\Cache; +use Alchemy\Phrasea\Cache\Factory; +use Monolog\Logger; -/** - * - * @license http://opensource.org/licenses/gpl-3.0 GPLv3 - * @link www.phraseanet.com - */ class Manager { - /** - * - * @var \SplFileInfo - */ - protected $cacheFile; - protected $app; + private $file; + /** @var Compiler */ + private $compiler; + private $registry = array(); + private $drivers = array(); + /** @var Logger */ + private $logger; + /** @var Factory */ + private $factory; - /** - * - */ - protected $parser; - - /** - * - * @var array - */ - protected $registry = array(); - - public function __construct(Application $app, \SplFileInfo $file) + public function __construct(Compiler $compiler, $file, Logger $logger, Factory $factory) { - $this->cacheFile = $file; - $this->parser = new Yaml(); - $this->app = $app; + $this->file = $file; + $this->compiler = $compiler; + $this->logger = $logger; + $this->factory = $factory; - $this->registry = $this->parser->parse($file) ? : array(); - } - - protected function exists($name) - { - return isset($this->registry[$name]); + if (!is_file($file)) { + $this->registry = array(); + $this->save(); + } else { + $this->registry = require $file; + } } + /** + * Flushes all registered cache + * + * @return Manager + */ public function flushAll() { - foreach ($this->registry as $cacheKey => $service_name) { - $this->get($cacheKey, $service_name)->getDriver()->flushAll(); + foreach ($this->drivers as $driver) { + $driver->flushAll(); } - file_put_contents($this->cacheFile->getPathname(), ''); + $this->registry = array(); + $this->save(); return $this; } - public function get($cacheKey, $service_name) + /** + * @param string $label + * @param string $name + * @param array $options + * + * @return Cache + */ + public function factory($label, $name, $options) { + if ($this->isAlreadyRegistered($name, $label) && $this->isAlreadyLoaded($label)) { + return $this->drivers[$label]; + } + try { - $configuration = $this->app['phraseanet.configuration']->getService($service_name); - $service = Builder::create($this->app, $configuration); - $driver = $service->getDriver(); - $write = true; - } catch (\Exception $e) { - $configuration = new ParameterBag( - array('type' => 'Cache\\ArrayCache') - ); - $service = Builder::create($this->app, $configuration); - $driver = $service->getDriver(); - $write = false; + $cache = $this->factory->create($name, $options); + } catch (RuntimeException $e) { + $this->logger->error($e->getMessage()); + $cache = $this->factory->create('array', array()); } - if ($this->hasChange($cacheKey, $service_name)) { - $service->getDriver()->flushAll(); - if ($write) { - $this->registry[$cacheKey] = $service_name; - $this->save($cacheKey, $service_name); - } + $cache->setNamespace(md5(__DIR__)); + + $this->drivers[$label] = $cache; + + if (!$this->isAlreadyRegistered($name, $label)) { + $this->register($name, $label); + $cache->flushAll(); } - return $service; + return $cache; } - protected function hasChange($name, $driver) + private function register($name, $label) { - return $this->exists($name) ? $this->registry[$name] !== $driver : true; + $this->registry[$label] = $name; + $this->save(); } - protected function save($name, $driver) + private function isAlreadyRegistered($name, $label) + { + return isset($this->registry[$label]) && $name === $this->registry[$label]; + } + + private function isAlreadyLoaded($label) + { + return isset($this->drivers[$label]); + } + + private function save() { $date = new \DateTime(); + $data = $this->compiler->compile($this->registry) + . "\n// Last Update on ".$date->format(DATE_ISO8601)." \n"; - $this->registry[$name] = $driver; - - $datas = sprintf("#LastUpdate: %s\n", $date->format(DATE_ISO8601)) - . $this->parser->dump($this->registry, 6); - - file_put_contents($this->cacheFile->getPathname(), $datas); + file_put_contents($this->file, $data); } } diff --git a/lib/Alchemy/Phrasea/Command/Compile/Configuration.php b/lib/Alchemy/Phrasea/Command/Compile/Configuration.php new file mode 100644 index 0000000000..ab907332b8 --- /dev/null +++ b/lib/Alchemy/Phrasea/Command/Compile/Configuration.php @@ -0,0 +1,31 @@ +container['phraseanet.configuration']->compileAndWrite(); + + return 0; + } +} diff --git a/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php b/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php index b7799b1272..ff847a8cdc 100644 --- a/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php +++ b/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php @@ -29,9 +29,7 @@ class RegenerateSqliteDb extends Command $fs->rename($source, $target); try { - $dbsParams = $this->container['phraseanet.configuration']->getConnexions(); - $dbParams = $dbsParams['test_connexion']; - + $dbParams = $this->container['phraseanet.configuration']->getTestConnectionParameters(); $dbParams['path'] = $source; $config = Setup::createYAMLMetadataConfiguration(array(__DIR__ . '/../../../../conf.d/Doctrine'), true); diff --git a/lib/Alchemy/Phrasea/Controller/AbstractDelivery.php b/lib/Alchemy/Phrasea/Controller/AbstractDelivery.php index 20d5308b58..d8347a797a 100644 --- a/lib/Alchemy/Phrasea/Controller/AbstractDelivery.php +++ b/lib/Alchemy/Phrasea/Controller/AbstractDelivery.php @@ -46,7 +46,7 @@ abstract class AbstractDelivery implements ControllerProviderInterface $referrer = $_SERVER['HTTP_REFERER']; } - $record->log_view($log_id, $referrer, $app['phraseanet.registry']->get('GV_sit')); + $record->log_view($log_id, $referrer, $app['phraseanet.configuration']['main']['key']); } catch (\Exception $e) { } diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Databoxes.php b/lib/Alchemy/Phrasea/Controller/Admin/Databoxes.php index fd57f71a28..4372031916 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Databoxes.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Databoxes.php @@ -210,13 +210,12 @@ class Databoxes implements ControllerProviderInterface if ((null === $request->request->get('new_settings')) && (null !== $dataTemplate = $request->request->get('new_data_template'))) { $configuration = $app['phraseanet.configuration']; - $choosenConnexion = $configuration->getPhraseanet()->get('database'); - $connexion = $configuration->getConnexion($choosenConnexion); + $connexion = $configuration['main']['database']; - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); + $hostname = $connexion['host']; + $port = $connexion['port']; + $user = $connexion['user']; + $password = $connexion['password']; $dataTemplate = new \SplFileInfo($app['phraseanet.registry']->get('GV_RootPath') . 'lib/conf.d/data_templates/' . $dataTemplate . '.xml'); @@ -282,12 +281,12 @@ class Databoxes implements ControllerProviderInterface if ((null === $request->request->get('new_settings'))) { try { $configuration = $app['phraseanet.configuration']; - $connexion = $configuration->getConnexion(); + $connexion = $configuration['main']['database']; - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); + $hostname = $connexion['host']; + $port = $connexion['port']; + $user = $connexion['user']; + $password = $connexion['password']; $app['phraseanet.appbox']->get_connection()->beginTransaction(); $base = \databox::mount($app, $hostname, $port, $user, $password, $dbName, $app['phraseanet.registry']); diff --git a/lib/Alchemy/Phrasea/Core/Configuration.php b/lib/Alchemy/Phrasea/Core/Configuration.php deleted file mode 100644 index 6045cdb5d6..0000000000 --- a/lib/Alchemy/Phrasea/Core/Configuration.php +++ /dev/null @@ -1,346 +0,0 @@ -specifications = $specifications; - - if ($specifications->isSetup()) { - $configurations = $this->specifications->getConfigurations(); - if (!$environment) { - if (isset($configurations[self::KEYWORD_ENV])) { - $environment = $configurations[self::KEYWORD_ENV]; - } else { - throw new RuntimeException('No configuration environment provided'); - } - } - } else { - $environment = null; - } - - $this->setEnvironnement($environment); - - return $this; - } - - public function get($name) - { - return $this->configuration->get($name); - } - - public function has($name) - { - return $this->configuration->has($name); - } - - public function getSpecifications() - { - return $this->specifications; - } - - /** - * Return the current used environnement - * - * @return string - */ - public function getEnvironnement() - { - return $this->environment; - } - - /** - * Return the current used environnement - * - * @return string - */ - public function setEnvironnement($environment) - { - $this->environment = $environment; - - if ($this->specifications->isSetup()) { - $configurations = $this->specifications->getConfigurations(); - - if ( ! isset($configurations[$this->environment])) { - throw new InvalidArgumentException('Requested environnment is not available'); - } - - $this->configuration = new ParameterBag($configurations[$this->environment]); - } else { - $this->configuration = new ParameterBag(array()); - } - - return $this; - } - - /** - * Check if current environnement is on debug mode - * Default to false - * @return boolean - */ - public function isDebug() - { - try { - $debug = (Boolean) $this->getPhraseanet()->get('debug'); - } catch (\Exception $e) { - $debug = false; - } - - return $debug; - } - - /** - * Check if phrasea is currently maintained - * Default to false - * @return boolean - */ - public function isMaintained() - { - try { - $maintained = (Boolean) $this->getPhraseanet()->get('maintenance'); - } catch (\Exception $e) { - $maintained = false; - } - - return $maintained; - } - - /** - * Check if current environnement should display errors - * Default to false - * @return boolean - */ - public function isDisplayingErrors() - { - try { - $displayErrors = (Boolean) $this->getPhraseanet()->get('display_errors'); - } catch (\Exception $e) { - $displayErrors = false; - } - - return $displayErrors; - } - - /** - * Return the phraseanet scope configurations values - * - * @return ParameterBag - */ - public function getPhraseanet() - { - return new ParameterBag($this->configuration->get('phraseanet')); - } - - public function initialize() - { - $this->specifications->initialize(); - $this->setEnvironnement('prod'); - - return $this; - } - - public function delete() - { - return $this->specifications->delete(); - } - - public function setConfigurations($configurations, $environment = null) - { - $this->specifications->setConfigurations($configurations); - - if (null === $environment) { - $environment = $this->environment; - } - - $this->setEnvironnement($environment); - - return $this->getConfigurations(); - } - - public function setServices($services) - { - return $this->specifications->setServices($services); - } - - public function resetServices($name = null) - { - return $this->specifications->resetServices($name); - } - - public function setBinaries($binaries) - { - return $this->specifications->setBinaries($binaries); - } - - public function setConnexions($connexions) - { - return $this->specifications->setConnexions($connexions); - } - - public function getConfigurations() - { - return $this->specifications->getConfigurations(); - } - - public function getServices() - { - return $this->specifications->getServices(); - } - - public function getBinaries() - { - return $this->specifications->getBinaries(); - } - - public function getConnexions() - { - return $this->specifications->getConnexions(); - } - - /** - * Return the connexion parameters as configuration parameter object - * - * @return ParameterBag - */ - public function getConnexion($name = 'main_connexion') - { - $connexions = $this->getConnexions(); - - if ( ! isset($connexions[$name])) { - throw new InvalidArgumentException(sprintf('Unknown connexion name %s', $name)); - } - - return new Parameterbag($connexions[$name]); - } - - /** - * Return configuration service for template_engine - * @return string - */ - public function getTemplating() - { - return 'TemplateEngine\\' . $this->configuration->get('template_engine'); - } - - public function getCache() - { - return 'Cache\\' . $this->configuration->get('cache'); - } - - public function getOpcodeCache() - { - return 'Cache\\' . $this->configuration->get('opcodecache'); - } - - /** - * Return configuration service for orm - * @return string - */ - public function getOrm() - { - return 'Orm\\' . $this->configuration->get('orm'); - } - - public function getSearchEngine() - { - return 'SearchEngine\\' . $this->configuration->get('search-engine'); - } - - /** - * Return border service for border-manager - * @return string - */ - public function getBorder() - { - return 'Border\\' . $this->configuration->get('border-manager'); - } - - public function getTaskManager() - { - return 'TaskManager\\' . $this->configuration->get('task-manager'); - } - - /** - * Return the selected service configuration - * - * @param type $name - * @return ParameterBag - */ - public function getService($name) - { - $scopes = explode('\\', $name); - $services = new ParameterBag($this->getServices()); - $service = null; - - while ($scopes) { - $scope = array_shift($scopes); - - try { - $service = new ParameterBag($services->get($scope)); - $services = $service; - } catch (\Exception $e) { - throw new InvalidArgumentException(sprintf('Unknow service name %s', $name)); - } - } - - return $service; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php b/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php deleted file mode 100644 index d4b95c8194..0000000000 --- a/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php +++ /dev/null @@ -1,207 +0,0 @@ -parser = new Yaml(); - } - - public function setConfigurations($configurations) - { - return file_put_contents( - $this->getConfigurationsPathFile(), $this->parser->dump($configurations, 7) - ); - } - - public function setConnexions($connexions) - { - return file_put_contents( - $this->getConnexionsPathFile(), $this->parser->dump($connexions, 7) - ); - } - - public function resetServices($name = null) - { - $services = $this->getServices(); - - if (!$name) { - $newServices = $services; - } else { - $newServices = $services; - - $legacyServices = $this->parser->parse( - file_get_contents($this->getRealRootPath() . "/lib/conf.d/services.yml") - ); - - if (!isset($legacyServices[$name])) { - throw new InvalidArgumentException(sprintf('%s is not a valid service name')); - } - - $newServices[$name] = $legacyServices[$name]; - } - - return $this->setServices($newServices); - } - - public function setServices($services) - { - return file_put_contents( - $this->getServicesPathFile(), $this->parser->dump($services, 7) - ); - } - - public function setBinaries($binaries) - { - return file_put_contents( - $this->getBinariesPathFile(), $this->parser->dump($binaries, 7) - ); - } - - public function getConfigurations() - { - return $this->parser->parse( - file_get_contents($this->getConfigurationsPathFile()) - ); - } - - public function getConnexions() - { - return $this->parser->parse( - file_get_contents($this->getConnexionsPathFile()) - ); - } - - public function getBinaries() - { - if (file_exists($this->getBinariesPathFile())) { - return $this->parser->parse( - file_get_contents($this->getBinariesPathFile()) - ); - } - - return array('binaries' => array()); - } - - public function getServices() - { - return $this->parser->parse( - file_get_contents($this->getServicesPathFile()) - ); - } - - public function delete() - { - $files = array( - $this->getConnexionsPathFile(), - $this->getConfigurationsPathFile(), - $this->getServicesPathFile() - ); - - foreach ($files as $file) { - if (file_exists($file)) - unlink($file); - } - } - - public function initialize() - { - $this->delete(); - - copy( - $this->getRealRootPath() . "/lib/conf.d/connexions.yml" - , $this->getConnexionsPathFile() - ); - - copy( - $this->getRealRootPath() . "/lib/conf.d/services.yml" - , $this->getServicesPathFile() - ); - - copy( - $this->getRealRootPath() . "/lib/conf.d/config.yml" - , $this->getConfigurationsPathFile() - ); - - $this->setBinaries(array('binaries' => array())); - - if (function_exists('chmod')) { - chmod($this->getConnexionsPathFile(), 0700); - chmod($this->getConfigurationsPathFile(), 0700); - chmod($this->getServicesPathFile(), 0700); - chmod($this->getBinariesPathFile(), 0700); - } - } - - public function isSetup() - { - try { - $this->getConfigurationsFile(); - $this->getConnexionsFile(); - $this->getServicesFile(); - - return true; - } catch (FileNotFoundException $e) { - - } - - return false; - } - - protected function getConfigurationsPathFile() - { - return $this->getRealRootPath() . '/config/config.yml'; - } - - protected function getConnexionsPathFile() - { - return $this->getRealRootPath() . '/config/connexions.yml'; - } - - protected function getServicesPathFile() - { - return $this->getRealRootPath() . '/config/services.yml'; - } - - protected function getBinariesPathFile() - { - return $this->getRealRootPath() . '/config/binaries.yml'; - } - - protected function getRealRootPath() - { - return realpath(__DIR__ . '/../../../../../'); - } - - protected function getConfigurationsFile() - { - return new SymfonyFile($this->getConfigurationsPathFile(), true); - } - - protected function getConnexionsFile() - { - return new SymfonyFile($this->getConnexionsPathFile(), true); - } - - protected function getServicesFile() - { - return new SymfonyFile($this->getServicesPathFile(), true); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Configuration/Compiler.php b/lib/Alchemy/Phrasea/Core/Configuration/Compiler.php new file mode 100644 index 0000000000..bcbbe1f3db --- /dev/null +++ b/lib/Alchemy/Phrasea/Core/Configuration/Compiler.php @@ -0,0 +1,87 @@ +line = $line; + } + + /** + * Compiles data to PHP code + * + * @param array $data + * + * @return string + */ + public function compile(array $data) + { + return 'addLine() . 'return ' . $this->doCompile($data) . ';' . $this->addLine(); + } + + private function doCompile(array $data, $offset = 0) + { + $out = 'array(' . $this->addLine(); + + foreach ($data as $key => $value) { + if (is_object($value)) { + $value = get_object_vars($value); + } + + $assoc = $this->addIndentation($offset + 1) . (is_int($key) ? '' : $this->quote($key) . ' => '); + + if (is_array($value)) { + $out .= $assoc . $this->doCompile($value, $offset + 1) . ',' . $this->addLine(); + } else { + $out .= $assoc . $this->quoteValue($value) . ',' . $this->addLine(); + } + } + + $out .= $this->addIndentation($offset) . ')'; + + return $out; + } + + private function quote($string) + { + return "'".str_replace("'", "\'", $string)."'"; + } + + private function quoteValue($string) + { + if (is_int($string)) { + return $string; + } + if (true === $string) { + return 'true'; + } + if (false === $string) { + return 'false'; + } + + return $this->quote($string); + } + + private function addLine() + { + return $this->line; + } + + private function addIndentation($quantity) + { + return str_repeat(' ', $quantity * 4); + } +} diff --git a/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php b/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php new file mode 100644 index 0000000000..e5c74875e7 --- /dev/null +++ b/lib/Alchemy/Phrasea/Core/Configuration/Configuration.php @@ -0,0 +1,243 @@ +parser = $yaml; + $this->compiler = $compiler; + $this->config = $config; + $this->compiled = $compiled; + $this->autoReload = (Boolean) $autoReload; + } + + /** + * {@inheritdoc} + */ + public function offsetExists($offset) + { + $conf = $this->getConfig(); + + return isset($conf[$offset]); + } + + /** + * {@inheritdoc} + */ + public function offsetSet($offset, $value) + { + $conf = $this->getConfig(); + $conf[$offset] = $value; + + $this->setConfig($conf); + } + + /** + * {@inheritdoc} + */ + public function offsetGet($offset) + { + $conf = $this->getConfig(); + + return $conf[$offset]; + } + + /** + * {@inheritdoc} + */ + public function offsetUnset($offset) + { + $conf = $this->getConfig(); + unset($conf[$offset]); + + $this->setConfig($conf); + } + + /** + * {@inheritdoc} + */ + public function setDefault($name) + { + $defaultConfig = $this->loadDefaultConfiguration(); + + if (!isset($defaultConfig[$name])) { + throw new InvalidArgumentException(sprintf('%s is not a valid config name', $name)); + } + + $newConfig = $this->doSetDefault($this->getConfig(), $defaultConfig, func_get_args()); + + return $this->setConfig($newConfig); + } + + private function doSetDefault($newConfig, $default, array $keys) + { + $name = array_shift($keys); + + if (!isset($default[$name])) { + throw new InvalidArgumentException(sprintf('%s is not a valid config name', $name)); + } + + if (count($keys) === 0) { + $newConfig[$name] = $default[$name]; + } else { + $newConfig[$name] = $this->doSetDefault($newConfig[$name], $default[$name], $keys); + } + + return $newConfig; + } + + /** + * {@inheritdoc} + */ + public function getConfig() + { + if (!is_file($this->compiled) || ($this->isAutoReload() && !$this->isConfigFresh())) { + if (!$this->isSetup()) { + throw new RuntimeException('Configuration is not set up'); + } + $this->writeCacheConfig($this->compiler->compile( + $this->parser->parse($this->loadFile($this->config)) + )); + } + + return require $this->compiled; + } + + /** + * {@inheritdoc} + */ + public function setConfig(array $config) + { + $this->dumpFile($this->config, $this->parser->dump($config, 7)); + $this->writeCacheConfig($this->compiler->compile($config)); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function compileAndWrite() + { + $this->writeCacheConfig($this->compiler->compile( + $this->parser->parse($this->loadFile($this->config)) + )); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function delete() + { + foreach (array( + $this->config, + $this->compiled, + ) as $file) { + $this->eraseFile($file); + } + } + + /** + * {@inheritdoc} + */ + public function initialize() + { + $this->delete(); + $this->dumpFile($this->config, $this->loadFile(__DIR__ . static::CONFIG_REF), 0600); + + return $this->getConfig(); + } + + /** + * {@inheritdoc} + */ + public function isSetup() + { + return file_exists($this->config); + } + + private function isAutoReload() + { + return $this->autoReload; + } + + public function getTestConnectionParameters() + { + return array( + 'driver' => 'pdo_sqlite', + 'path' => '/tmp/db.sqlite', + 'charset' => 'UTF8', + ); + } + + private function loadDefaultConfiguration() + { + return $this->parser->parse($this->loadFile(__DIR__ . static::CONFIG_REF)); + } + + private function writeCacheConfig($content) + { + $this->dumpFile($this->compiled, $content, 0600); + } + + private function isConfigFresh() + { + return @filemtime($this->config) <= @filemtime($this->compiled); + } + + private function loadFile($file) + { + if (!is_file($file) || !is_readable($file)) { + throw new RuntimeException(sprintf('Unable to read %s', $file)); + } + + return file_get_contents($file); + } + + private function dumpFile($file, $content, $mod = 0600) + { + $tmpFile = tempnam(dirname($file), basename($file)); + if (false !== @file_put_contents($tmpFile, $content)) { + // rename does not work on Win32 before 5.2.6 + if (@rename($tmpFile, $file)) { + @chmod($file, $mod & ~umask()); + + return; + } + } + + throw new RuntimeException(sprintf('Unable to write %s', $file)); + } + + private function eraseFile($file) + { + if (is_file($file)) { + unlink($file); + } + } +} diff --git a/lib/Alchemy/Phrasea/Core/Configuration/ConfigurationInterface.php b/lib/Alchemy/Phrasea/Core/Configuration/ConfigurationInterface.php new file mode 100644 index 0000000000..fefce88d50 --- /dev/null +++ b/lib/Alchemy/Phrasea/Core/Configuration/ConfigurationInterface.php @@ -0,0 +1,66 @@ +share(function (Application $app) { - $authConf = $app['phraseanet.configuration']->get('authentication'); + $authConf = $app['phraseanet.configuration']['authentication']; $templates = array_filter(array_map(function ($templateId) use ($app) { try { if (is_int($templateId) || ctype_digit($templateId)) { @@ -75,7 +75,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface $providers = new ProvidersCollection(); - $authConf = $app['phraseanet.configuration']->get('authentication'); + $authConf = $app['phraseanet.configuration']['authentication']; foreach ($authConf['providers'] as $providerId => $data) { if (isset($data['enabled']) && false === $data['enabled']) { continue; @@ -91,7 +91,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface }); $app['auth.password-encoder'] = $app->share(function (Application $app) { - return new PasswordEncoder($app['phraseanet.registry']->get('GV_sit')); + return new PasswordEncoder($app['phraseanet.configuration']['main']['key']); }); $app['auth.old-password-encoder'] = $app->share(function (Application $app) { @@ -99,7 +99,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface }); $app['auth.native.failure-manager'] = $app->share(function (Application $app) { - $authConf = $app['phraseanet.configuration']->get('authentication'); + $authConf = $app['phraseanet.configuration']['authentication']['captcha']; return new FailureManager($app['EM'], $app['recaptcha'], isset($authConf['trials-before-failure']) ? $authConf['trials-before-failure'] : 9); }); @@ -109,10 +109,13 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface }); $app['auth.native'] = $app->share(function (Application $app) { - $authConf = $app['phraseanet.configuration']->get('authentication'); + $authConf = $app['phraseanet.configuration']['authentication']; if ($authConf['captcha']['enabled']) { - return new FailureHandledNativeAuthentication($app['auth.password-checker'], $app['auth.native.failure-manager']); + return new FailureHandledNativeAuthentication( + $app['auth.password-checker'], + $app['auth.native.failure-manager'] + ); } else { return $app['auth.password-checker']; } diff --git a/lib/Alchemy/Phrasea/Core/Provider/BorderManagerServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/BorderManagerServiceProvider.php index cf0ec37aee..e06854ddd7 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/BorderManagerServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/BorderManagerServiceProvider.php @@ -11,7 +11,7 @@ namespace Alchemy\Phrasea\Core\Provider; -use Alchemy\Phrasea\Core\Service\Builder; +use Alchemy\Phrasea\Border\Manager; use Silex\Application; use Silex\ServiceProviderInterface; @@ -21,14 +21,78 @@ class BorderManagerServiceProvider implements ServiceProviderInterface public function register(Application $app) { $app['border-manager'] = $app->share(function(Application $app) { + $borderManager = new Manager($app); - $configuration = $app['phraseanet.configuration'] - ->getService($app['phraseanet.configuration'] - ->getBorder()); + if ($app['xpdf.pdf2text']) { + $borderManager->setPdfToText($app['xpdf.pdf2text']); + } - $service = Builder::create($app, $configuration); + $options = $app['phraseanet.configuration']['border-manager']; - return $service->getDriver(); + $registeredCheckers = array(); + + if ($options['enabled']) { + foreach ($options['checkers'] as $checker) { + if (!isset($checker['type'])) { + continue; + } + if (isset($checker['enabled']) && $checker['enabled'] !== true) { + continue; + } + + $className = sprintf('\\Alchemy\\Phrasea\\Border\\%s', $checker['type']); + + if (!class_exists($className)) { + $app['monolog']->error(sprintf('Border manager checker, invalid checker %s', $checker['type'])); + continue; + } + + $options = array(); + + if (isset($checker['options']) && is_array($checker['options'])) { + $options = $checker['options']; + } + + try { + $checkerObj = new $className($app, $options); + if (isset($checker['databoxes'])) { + + $databoxes = array(); + foreach ($checker['databoxes'] as $sbas_id) { + try { + $databoxes[] = $app['phraseanet.appbox']->get_databox($sbas_id); + } catch (\Exception $e) { + throw new \InvalidArgumentException('Invalid databox option'); + } + } + + $checkerObj->restrictToDataboxes($databoxes); + } + if (isset($checker['collections'])) { + + $collections = array(); + foreach ($checker['collections'] as $base_id) { + try { + $collections[] = \collection::get_from_base_id($app, $base_id); + } catch (\Exception $e) { + throw new \InvalidArgumentException('Invalid collection option'); + } + } + + $checkerObj->restrictToCollections($collections); + } + $registeredCheckers[] = $checkerObj; + } catch (\InvalidArgumentException $e) { + $app['monolog']->error(sprintf('Border manager checker InvalidArgumentException : %s', $e->getMessage())); + } catch (\LogicException $e) { + $app['monolog']->error(sprintf('Border manager checker LogicException : %s', $e->getMessage())); + } + } + + $borderManager->registerCheckers($registeredCheckers); + } + + return $borderManager; }); } diff --git a/lib/Alchemy/Phrasea/Core/Provider/CacheServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/CacheServiceProvider.php index 3cda4f7943..5ab2fa6e4b 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/CacheServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/CacheServiceProvider.php @@ -14,30 +14,43 @@ namespace Alchemy\Phrasea\Core\Provider; use Alchemy\Phrasea\Cache\Manager as CacheManager; use Silex\Application; use Silex\ServiceProviderInterface; +use Alchemy\Phrasea\Core\Configuration\Compiler; +use Alchemy\Phrasea\Cache\Factory; class CacheServiceProvider implements ServiceProviderInterface { public function register(Application $app) { - $app['phraseanet.cache-service'] = $app->share(function(Application $app) { - if ( ! file_exists(__DIR__ . '/../../../../../tmp/cache_registry.yml')) { - touch(__DIR__ . '/../../../../../tmp/cache_registry.yml'); - } + $app['phraseanet.cache-registry'] = __DIR__ . '/../../../../../tmp/cache_registry.php'; - return new CacheManager($app, new \SplFileInfo(__DIR__ . '/../../../../../tmp/cache_registry.yml')); + $app['phraseanet.cache-compiler'] = $app->share(function () { + return new Compiler(); + }); + + $app['phraseanet.cache-factory'] = $app->share(function () { + return new Factory(); + }); + + $app['phraseanet.cache-service'] = $app->share(function(Application $app) { + return new CacheManager( + $app['phraseanet.cache-compiler'], + $app['phraseanet.cache-registry'], + $app['monolog'], + $app['phraseanet.cache-factory'] + ); }); $app['cache'] = $app->share(function(Application $app) { - return $app['phraseanet.cache-service'] - ->get('MainCache', $app['phraseanet.configuration']->getCache()) - ->getDriver(); + $conf = $app['phraseanet.configuration']['main']['cache']; + + return $app['phraseanet.cache-service']->factory('cache', $conf['type'], $conf['options']); }); $app['opcode-cache'] = $app->share(function(Application $app) { - return $app['phraseanet.cache-service'] - ->get('OpcodeCache', $app['phraseanet.configuration']->getOpcodeCache()) - ->getDriver(); + $conf = $app['phraseanet.configuration']['main']['opcodecache']; + + return $app['phraseanet.cache-service']->factory('cache', $conf['type'], $conf['options']); }); } diff --git a/lib/Alchemy/Phrasea/Core/Provider/ConfigurationServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/ConfigurationServiceProvider.php index 3a8b949a4a..00d3923c0c 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/ConfigurationServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/ConfigurationServiceProvider.php @@ -11,18 +11,35 @@ namespace Alchemy\Phrasea\Core\Provider; -use Alchemy\Phrasea\Core\Configuration; use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Core\Configuration\Configuration; +use Alchemy\Phrasea\Core\Configuration\Compiler; use Silex\Application as SilexApplication; use Silex\ServiceProviderInterface; +use Symfony\Component\Yaml\Yaml; class ConfigurationServiceProvider implements ServiceProviderInterface { public function register(SilexApplication $app) { - $app['phraseanet.configuration'] = $app->share(function(Application $app) { - return Configuration::build(null, $app->getEnvironment()); + $app['phraseanet.configuration.yaml-parser'] = $app->share(function (SilexApplication $app) { + return new Yaml(); + }); + $app['phraseanet.configuration.compiler'] = $app->share(function (SilexApplication $app) { + return new Compiler(); + }); + $app['phraseanet.configuration.config-path'] = $app['root.path'] . '/config/configuration.yml'; + $app['phraseanet.configuration.config-compiled-path'] = $app['root.path'] . '/tmp/configuration-compiled.php'; + + $app['phraseanet.configuration'] = $app->share(function(SilexApplication $app) { + return new Configuration( + $app['phraseanet.configuration.yaml-parser'], + $app['phraseanet.configuration.compiler'], + $app['phraseanet.configuration.config-path'], + $app['phraseanet.configuration.config-compiled-path'], + $app['debug'] + ); }); } diff --git a/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php index a7923152cc..0bd21b9407 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php @@ -11,7 +11,17 @@ namespace Alchemy\Phrasea\Core\Provider; -use Alchemy\Phrasea\Core\Service\Builder; +use Alchemy\Phrasea\Exception\RuntimeException; +use Doctrine\Common\EventManager; +use Doctrine\ORM\Mapping\Driver\DriverChain; +use Doctrine\ORM\Mapping\Driver\YamlDriver; +use Doctrine\ORM\EntityManager; +use Doctrine\ORM\Configuration as ORMConfiguration; +use Doctrine\DBAL\Types\Type; +use Doctrine\Logger\MonologSQLLogger; +use Gedmo\Timestampable\TimestampableListener; +use Monolog\Logger; +use Monolog\Handler\RotatingFileHandler; use Silex\Application; use Silex\ServiceProviderInterface; @@ -20,12 +30,85 @@ class ORMServiceProvider implements ServiceProviderInterface public function register(Application $app) { + $app['EM.sql-logger.file'] = $app['root.path'] . '/logs/doctrine-log.log'; + $app['EM.sql-logger.max-files'] = 5; + + $app['EM.sql-logger'] = $app->share(function (Application $app) { + $logger = new Logger('doctrine-logger'); + $logger->pushHandler(new RotatingFileHandler($app['EM.sql-logger.file'], $app['EM.sql-logger.max-files'])); + + return new MonologSQLLogger($logger, 'yaml'); + }); + $app['EM'] = $app->share(function(Application $app) { - return Builder::create( - $app, $app['phraseanet.configuration'] - ->getService($app['phraseanet.configuration'] - ->getOrm()) - )->getDriver(); + + $config = new ORMConfiguration(); + + if ($app['debug']) { + $config->setSQLLogger($app['EM.sql-logger']); + } + + $opCodeCacheType = $app['phraseanet.configuration']['main']['opcodecache']['type']; + $opCodeCacheOptions = $app['phraseanet.configuration']['main']['opcodecache']['options']; + + $cacheType = $app['phraseanet.configuration']['main']['cache']['type']; + $cacheOptions = $app['phraseanet.configuration']['main']['cache']['options']; + + $config->setMetadataCacheImpl($app['phraseanet.cache-service']->factory( + 'ORMmetadata', $opCodeCacheType, $opCodeCacheOptions + )); + $config->setQueryCacheImpl($app['phraseanet.cache-service']->factory( + 'ORMquery', $opCodeCacheType, $opCodeCacheOptions + )); + $config->setResultCacheImpl($app['phraseanet.cache-service']->factory( + 'ORMresult', $cacheType, $cacheOptions + )); + + //define autoregeneration of proxies base on debug mode + $config->setAutoGenerateProxyClasses($app['debug']); + + $chainDriverImpl = new DriverChain(); + $driverYaml = new YamlDriver(array($app['root.path'] . '/lib/conf.d/Doctrine')); + $chainDriverImpl->addDriver($driverYaml, 'Entities'); + $chainDriverImpl->addDriver($driverYaml, 'Gedmo\Timestampable'); + $config->setMetadataDriverImpl($chainDriverImpl); + + $config->setProxyDir($app['root.path'] . '/lib/Doctrine/Proxies'); + $config->setProxyNamespace('Proxies'); + + if ('test' === $app->getEnvironment()) { + $dbalConf = $app['phraseanet.configuration']['main']['database-test']; + } else { + $dbalConf = $app['phraseanet.configuration']['main']['database']; + } + + $evm = new EventManager(); + $evm->addEventSubscriber(new TimestampableListener()); + + try { + $em = EntityManager::create($dbalConf, $config, $evm); + } catch (\Exception $e) { + throw new RuntimeException("Unable to create database connection", $e->getCode(), $e); + } + + $platform = $em->getConnection()->getDatabasePlatform(); + + $types = array( + 'blob' => 'Types\Blob', + 'enum' => 'Types\Blob', + 'longblob' => 'Types\LongBlob', + 'varbinary' => 'Types\VarBinary', + 'binary' => 'Types\Binary', + ); + + foreach ($types as $type => $class) { + if (!Type::hasType($type)) { + Type::addType($type, $class); + } + $platform->registerDoctrineTypeMapping($type, $type); + } + + return $em; }); } diff --git a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php index 26821a789b..da6f04a25c 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php @@ -21,11 +21,7 @@ class RegistrationServiceProvider implements ServiceProviderInterface public function register(Application $app) { $app['registration.fields'] = $app->share(function (Application $app){ - if ($app['phraseanet.configuration']->has('registration-fields')) { - return $app['phraseanet.configuration']->get('registration-fields'); - } - - return array(); + return isset($app['phraseanet.configuration']['registration-fields']) ? $app['phraseanet.configuration']['registration-fields'] : array(); }); $app['registration.enabled'] = $app->share(function (Application $app){ diff --git a/lib/Alchemy/Phrasea/Core/Provider/SearchEngineServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/SearchEngineServiceProvider.php index c56ef9ff25..56e5d48f3c 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/SearchEngineServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/SearchEngineServiceProvider.php @@ -12,7 +12,8 @@ namespace Alchemy\Phrasea\Core\Provider; use Alchemy\Phrasea\SearchEngine\SearchEngineLogger; -use Alchemy\Phrasea\Core\Service\Builder; +use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\SearchEngine\SearchEngineInterface; use Silex\Application; use Silex\ServiceProviderInterface; @@ -22,12 +23,15 @@ class SearchEngineServiceProvider implements ServiceProviderInterface public function register(Application $app) { $app['phraseanet.SE'] = $app->share(function($app) { - $configuration = $app['phraseanet.configuration'] - ->getService($app['phraseanet.configuration']->getSearchEngine()); - $service = Builder::create($app, $configuration); + $engineClass = $app['phraseanet.configuration']['main']['search-engine']['type']; + $engineOptions = $app['phraseanet.configuration']['main']['search-engine']['options']; - return $service->getDriver(); + if (!class_exists($engineClass) || $engineClass instanceof SearchEngineInterface) { + throw new InvalidArgumentException(sprintf('%s is not valid SearchEngineInterface', $engineClass)); + } + + return $engineClass::create($app, $engineOptions); }); $app['phraseanet.SE.logger'] = $app->share(function(Application $app) { diff --git a/lib/Alchemy/Phrasea/Core/Provider/TaskManagerServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/TaskManagerServiceProvider.php index 4f9da534e6..8d36b6f9c2 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/TaskManagerServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/TaskManagerServiceProvider.php @@ -11,9 +11,11 @@ namespace Alchemy\Phrasea\Core\Provider; -use Alchemy\Phrasea\Core\Service\Builder; use Silex\Application; use Silex\ServiceProviderInterface; +use Monolog\Handler\SyslogHandler; +use Monolog\Handler\NativeMailerHandler; +use Alchemy\Phrasea\Exception\RuntimeException; class TaskManagerServiceProvider implements ServiceProviderInterface { @@ -22,17 +24,30 @@ class TaskManagerServiceProvider implements ServiceProviderInterface { $app['task-manager'] = $app->share(function(Application $app) { - $configuration = $app['phraseanet.configuration'] - ->getService($app['phraseanet.configuration']->getTaskManager()); + $logger = clone $app['monolog']; - $service = Builder::create($app, $configuration); + $options = $app['phraseanet.configuration']['main']['task-manager']['options']; - return $service->getDriver(); + if (isset($options['syslog_level']) && null !== $syslogLevel = constant($options['syslog_level'])) { + $handler = new SyslogHandler("Phraseanet-Task", "user", $syslogLevel); + $logger->pushHandler($handler); + } + + if (isset($options['maillog_level']) && null !== $maillogLevel = constant($options['maillog_level'])) { + if ('' === $adminMail = trim($app['phraseanet.registry']->get('GV_adminMail'))) { + throw new RuntimeException("Admininstrator mail must be set to get log by mail."); + } + $senderMail = $app['phraseanet.registry']->get('GV_defaultmailsenderaddr'); + + $handler = new NativeMailerHandler($adminMail, "Phraseanet-Task", $senderMail, $maillogLevel); + $logger->pushHandler($handler); + } + + return new \task_manager($app, $logger); }); } public function boot(Application $app) { - } } diff --git a/lib/Alchemy/Phrasea/Core/Service/Border/BorderManager.php b/lib/Alchemy/Phrasea/Core/Service/Border/BorderManager.php deleted file mode 100644 index 20cf7a48ae..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Border/BorderManager.php +++ /dev/null @@ -1,172 +0,0 @@ -app); - - if ($this->app['xpdf.pdf2text']) { - $borderManager->setPdfToText($this->app['xpdf.pdf2text']); - } - - $options = $this->getOptions(); - - $registeredCheckers = array(); - - if (! ! $options['enabled']) { - foreach ($options['checkers'] as $checker) { - - if ( ! isset($checker['type'])) { - $this->addUnregisteredCheck(null, 'No type defined'); - continue; - } - - $type = $checker['type']; - - if (isset($checker['enabled']) && $checker['enabled'] !== true) { - $this->addUnregisteredCheck($type, 'Checker is disabled'); - continue; - } - - $className = sprintf('\\Alchemy\\Phrasea\\Border\\%s', $checker['type']); - - if ( ! class_exists($className)) { - $this->addUnregisteredCheck($type, sprintf('Unknow checker type "%s"', $type)); - continue; - } - - $options = array(); - - if (isset($checker['options']) && is_array($checker['options'])) { - $options = $checker['options']; - } - - try { - $checkerObj = new $className($this->app, $options); - if (isset($checker['databoxes'])) { - - $databoxes = array(); - foreach ($checker['databoxes'] as $sbas_id) { - try { - $databoxes[] = $this->app['phraseanet.appbox']->get_databox($sbas_id); - } catch (\Exception $e) { - throw new \InvalidArgumentException('Invalid databox option'); - } - } - - $checkerObj->restrictToDataboxes($databoxes); - } - if (isset($checker['collections'])) { - - $collections = array(); - foreach ($checker['collections'] as $base_id) { - try { - $collections[] = \collection::get_from_base_id($this->app, $base_id); - } catch (\Exception $e) { - throw new \InvalidArgumentException('Invalid collection option'); - } - } - - $checkerObj->restrictToCollections($collections); - } - $registeredCheckers[] = $checkerObj; - } catch (\InvalidArgumentException $e) { - $this->addUnregisteredCheck($type, $e->getMessage()); - } catch (\LogicException $e) { - $this->addUnregisteredCheck($type, $e->getMessage()); - } - } - - $borderManager->registerCheckers($registeredCheckers); - } - - $this->borderManager = $borderManager; - } - - /** - * Set and return a new Border Manager instance and set the proper checkers - * according to the services configuration - * - * @return Manager - */ - public function getDriver() - { - return $this->borderManager; - } - - /** - * Return the type of the service - * @return string - */ - public function getType() - { - return 'border'; - } - - /** - * Define the mandatory option for the current services - * @return array - */ - public function getMandatoryOptions() - { - return array('enabled', 'checkers'); - } - - /** - * Return all unregistered Checkers - * @return array - */ - public function getUnregisteredCheckers() - { - return $this->unregisteredCheckers; - } - - /** - * Add an unregistered check entry - * - * @param string $type - * @param string $message - */ - private function addUnregisteredCheck($type, $message) - { - $this->unregisteredCheckers[] = array( - 'checker' => $type, - 'message' => $message - ); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Builder.php b/lib/Alchemy/Phrasea/Core/Service/Builder.php deleted file mode 100644 index a4c973f673..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Builder.php +++ /dev/null @@ -1,41 +0,0 @@ -get("type"); - - if ( ! class_exists($classname)) { - throw new Exception\ServiceNotFound(sprintf('Service %s not found', $classname)); - } - - try { - $options = $configuration->get("options") ?: array() ; - } catch (\Exception $e) { - $options = array(); - } - - return new $classname($app, $options); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php deleted file mode 100644 index d527a47744..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php +++ /dev/null @@ -1,45 +0,0 @@ -cache) { - $this->cache = new CacheDriver\ApcCache(); - - $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); - } - - return $this->cache; - } - - public function getType() - { - return 'apc'; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php deleted file mode 100644 index 81b2a52eb6..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php +++ /dev/null @@ -1,42 +0,0 @@ -cache) { - $this->cache = new CacheDriver\ArrayCache(); - - $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); - } - - return $this->cache; - } - - public function getType() - { - return 'array'; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php deleted file mode 100644 index b2a88b5021..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php +++ /dev/null @@ -1,82 +0,0 @@ -getOptions(); - - $this->host = isset($options["host"]) ? $options["host"] : self::DEFAULT_HOST; - - $this->port = isset($options["port"]) ? $options["port"] : self::DEFAULT_PORT; - } - - public function getDriver() - { - if ( ! extension_loaded('memcache')) { - throw new \Exception('The Memcache cache requires the Memcache extension.'); - } - - if (! $this->cache) { - $memcache = new \Memcache(); - - $memcache->addServer($this->host, $this->port); - - $key = sprintf("%s:%s", $this->host, $this->port); - - $stats = @$memcache->getExtendedStats(); - - if (isset($stats[$key]) && false !== $stats[$key]) { - $this->cache = new CacheDriver\MemcacheCache(); - $this->cache->setMemcache($memcache); - - $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); - } else { - throw new \Exception(sprintf("Memcache instance with host '%s' and port '%s' is not reachable", $this->host, $this->port)); - } - } - - return $this->cache; - } - - public function getType() - { - return 'memcache'; - } - - public function getHost() - { - return $this->host; - } - - public function getPort() - { - return $this->port; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php deleted file mode 100644 index 82673f98c5..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php +++ /dev/null @@ -1,83 +0,0 @@ -getOptions(); - - $this->host = isset($options["host"]) ? $options["host"] : self::DEFAULT_HOST; - - $this->port = isset($options["port"]) ? $options["port"] : self::DEFAULT_PORT; - } - - /** - * - * @return Cache\ApcCache - */ - public function getDriver() - { - if ( ! extension_loaded('redis')) { - throw new \Exception('The Redis cache requires the Redis extension.'); - } - - if (! $this->cache) { - $redis = new \Redis(); - - if ($redis->connect($this->host, $this->port)) { - if ( ! $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY)) { - $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); - } - - $this->cache = new CacheDriver\RedisCache(); - $this->cache->setRedis($redis); - $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); - } else { - throw new \Exception(sprintf("Redis instance with host '%s' and port '%s' is not reachable", $this->host, $this->port)); - } - } - - return $this->cache; - } - - public function getType() - { - return 'redis'; - } - - public function getHost() - { - return $this->host; - } - - public function getPort() - { - return $this->port; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/WinCacheCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/WinCacheCache.php deleted file mode 100644 index 2aca1f80a7..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Cache/WinCacheCache.php +++ /dev/null @@ -1,48 +0,0 @@ -cache) { - $this->cache = new CacheDriver\WinCacheCache(); - - $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); - } - - return $this->cache; - } - - public function getType() - { - return 'wincache'; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php deleted file mode 100644 index 154c48e766..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php +++ /dev/null @@ -1,45 +0,0 @@ -cache) { - $this->cache = new CacheDriver\XcacheCache(); - - $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); - } - - return $this->cache; - } - - public function getType() - { - return 'xcache'; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Exception/MissingParameters.php b/lib/Alchemy/Phrasea/Core/Service/Exception/MissingParameters.php deleted file mode 100644 index 2ee34a088d..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Exception/MissingParameters.php +++ /dev/null @@ -1,22 +0,0 @@ -options["output"]) ? $this->options["output"] : self::JSON_OUTPUT; - - $outputs = array( - self::JSON_OUTPUT, self::YAML_OUTPUT, self::VAR_DUMP_OUTPUT - ); - - if ( ! in_array($output, $outputs)) { - throw new \Exception(sprintf( - "The output type '%s' declared in %s service is not valid. - Available types are %s." - , $output - , __CLASS__ - , implode(", ", $outputs) - ) - ); - } - - return new MonologSQLLogger($this->monolog, $output); - } - - public function getType() - { - return 'doctrine_monolog'; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php b/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php deleted file mode 100644 index a44de6a955..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php +++ /dev/null @@ -1,34 +0,0 @@ -logger) { - $this->logger = new Logger('FirePHP'); - - $this->logger->pushHandler(new FirePHPHandler()); - } - - return $this->logger; - } - - public function getType() - { - return 'FirePHP Monolog'; - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php b/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php deleted file mode 100644 index f02c849153..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php +++ /dev/null @@ -1,119 +0,0 @@ - 'RotatingFile' - , 'stream' => 'Stream' - ); - - /** - * - * @var \Monolog\Logger - */ - protected $monolog; - - protected function init() - { - $options = $this->getOptions(); - - if (empty($options)) { - throw new \Exception(sprintf("'%s' service options can not be empty", $this->name)); - } - - //defaut to main handler - $handler = isset($options["handler"]) ? $options["handler"] : false; - - if (! $handler) { - throw new \Exception(sprintf( - "You must specify at least one handler for '%s' service" - , __CLASS__ - ) - ); - } - - if ( ! array_key_exists($handler, $this->handlers)) { - throw new \Exception(sprintf( - "The handler type '%s' declared in %s is not valid. Available types are %s.", $handler, __CLASS__, implode(", ", $this->handlers) - ) - ); - } - - $handlerName = $this->handlers[$handler]; - - $handlerClassName = sprintf('\Monolog\Handler\%sHandler', $handlerName); - - if ( ! class_exists($handlerClassName)) { - throw new \Exception(sprintf( - 'Unable to log monolog handler %s looked for class %s' - , $handlerName - , $handlerClassName) - ); - } - - if ( ! isset($options["filename"])) { - throw new \Exception(sprintf( - "Missing filename option in '%s' service" - , __CLASS__ - ) - ); - } - - $logPath = __DIR__ . '/../../../../../../logs'; - - $file = sprintf('%s/%s', $logPath, $options["filename"]); - - if ($handler == 'rotate') { - $maxDay = isset($options["max_day"]) ? - (int) $options["max_day"] : - self::DEFAULT_MAX_DAY; - - $handlerInstance = new $handlerClassName($file, $maxDay); - } else { - $handlerInstance = new $handlerClassName($file); - } - - $channel = isset($options["channel"]) ? $options["channel"] : "monolog"; - - $monologLogger = new \Monolog\Logger($channel); - - $monologLogger->pushHandler($handlerInstance); - - $this->monolog = $monologLogger; - } - - public function getDriver() - { - return $this->monolog; - } - - public function getType() - { - return 'monolog'; - } - - public function getMandatoryOptions() - { - return array('channel', 'handler', 'filename'); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php b/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php deleted file mode 100644 index 0b615070f1..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php +++ /dev/null @@ -1,214 +0,0 @@ -getOptions(); - - $config = new ORMConfiguration(); - - $this->debug = !!$options["debug"]; - - $logServiceName = isset($options["log"]['service']) ? $options["log"]['service'] : false; - - if ($logServiceName) { - $config->setSQLLogger($this->getLog($logServiceName)); - } - - $cache = isset($options["cache"]) ? $options["cache"] : false; - - if (!$cache || $this->debug) { - $metaCache = $this->app['phraseanet.cache-service']->get('ORMmetadata', 'Cache\\ArrayCache'); - $queryCache = $this->app['phraseanet.cache-service']->get('ORMquery', 'Cache\\ArrayCache'); - } else { - $query = isset($cache["query"]['service']) ? $cache["query"]['service'] : 'Cache\\ArrayCache'; - $meta = isset($cache["metadata"]['service']) ? $cache["metadata"]['service'] : 'Cache\\ArrayCache'; - - $queryCache = $this->app['phraseanet.cache-service']->get('ORMquery', $query); - $metaCache = $this->app['phraseanet.cache-service']->get('ORMmetadata', $meta); - } - - $resultCache = $this->app['phraseanet.cache-service']->get('ORMresult', 'Cache\\ArrayCache'); - - $config->setMetadataCacheImpl($metaCache->getDriver()); - - $config->setQueryCacheImpl($queryCache->getDriver()); - - $config->setResultCacheImpl($resultCache->getDriver()); - - //define autoregeneration of proxies base on debug mode - $config->setAutoGenerateProxyClasses($this->debug); - - $chainDriverImpl = new DriverChain(); - - $driverYaml = new YamlDriver(array(__DIR__ . '/../../../../../conf.d/Doctrine')); - - $chainDriverImpl->addDriver($driverYaml, 'Entities'); - - $chainDriverImpl->addDriver($driverYaml, 'Gedmo\Timestampable'); - - $config->setMetadataDriverImpl($chainDriverImpl); - - $config->setProxyDir(realpath(__DIR__ . '/../../../../../Doctrine/Proxies')); - - $config->setProxyNamespace('Proxies'); - - $connexion = isset($options["dbal"]) ? $options["dbal"] : false; - - if (!$connexion) { - throw new \Exception(sprintf( - "Missing dbal configuration for '%s' service" - , __CLASS__ - ) - ); - } - - try { - $dbalConf = $this->app['phraseanet.configuration'] - ->getConnexion($connexion) - ->all(); - } catch (\Exception $e) { - throw new \Exception("Connexion '%s' is not declared"); - } - - $evm = new EventManager(); - - $evm->addEventSubscriber(new TimestampableListener()); - - try { - $this->entityManager = EntityManager::create($dbalConf, $config, $evm); - } catch (\Exception $e) { - throw new \Exception(sprintf( - "Failed to create doctrine service for the following reason '%s'" - , $e->getMessage() - ) - ); - } - - $this->addTypes(); - - return $this; - } - - protected function addTypes() - { - - $platform = $this->entityManager->getConnection()->getDatabasePlatform(); - - if (!Type::hasType('blob')) { - Type::addType('blob', 'Types\Blob'); - } - - if (!Type::hasType('enum')) { - Type::addType('enum', 'Types\Enum'); - } - - if (!Type::hasType('longblob')) { - Type::addType('longblob', 'Types\LongBlob'); - } - - if (!Type::hasType('varbinary')) { - Type::addType('varbinary', 'Types\VarBinary'); - } - - if (!Type::hasType('binary')) { - Type::addType('binary', 'Types\Binary'); - } - - $platform->registerDoctrineTypeMapping('enum', 'enum'); - $platform->registerDoctrineTypeMapping('blob', 'blob'); - $platform->registerDoctrineTypeMapping('longblob', 'longblob'); - $platform->registerDoctrineTypeMapping('varbinary', 'varbinary'); - $platform->registerDoctrineTypeMapping('binary', 'binary'); - - return; - } - - private function getLog($serviceName) - { - try { - $configuration = $this->app['phraseanet.configuration']->getService($serviceName); - } catch (\Exception $e) { - $message = sprintf( - "%s from %s service" - , $e->getMessage() - , __CLASS__ - ); - - $e = new \Exception($message); - - throw $e; - } - - $type = $configuration->get("type"); - - if (!in_array($type, $this->loggers)) { - throw new \Exception(sprintf( - "The logger type '%s' declared in %s service is not valid. - Available types are %s." - , $type - , __CLASS__ - , implode(", ", $this->loggers) - ) - ); - } - - $service = Builder::create($this->app, $configuration); - - return $service->getDriver(); - } - - public function getDriver() - { - return $this->entityManager; - } - - public function getType() - { - return 'doctrine'; - } - - public function isDebug() - { - return $this->debug; - } - - public function getMandatoryOptions() - { - return array('debug', 'dbal'); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/SearchEngine/PhraseaEngine.php b/lib/Alchemy/Phrasea/Core/Service/SearchEngine/PhraseaEngine.php deleted file mode 100644 index f4125bf93e..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/SearchEngine/PhraseaEngine.php +++ /dev/null @@ -1,42 +0,0 @@ -searchEngine = PhraseaSearchEngine::create($this->app); - - return $this; - } - - public function getDriver() - { - return $this->searchEngine; - } - - public function getType() - { - return 'phrasea'; - } - - public function getMandatoryOptions() - { - return array(); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/SearchEngine/SphinxSearch.php b/lib/Alchemy/Phrasea/Core/Service/SearchEngine/SphinxSearch.php deleted file mode 100644 index cbe7e16c09..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/SearchEngine/SphinxSearch.php +++ /dev/null @@ -1,44 +0,0 @@ -getOptions(); - - $this->searchEngine = new SphinxSearchEngine($this->app, $options['host'], $options['port'], $options['rt_host'], $options['rt_port']); - - return $this; - } - - public function getDriver() - { - return $this->searchEngine; - } - - public function getType() - { - return 'sphinx-search'; - } - - public function getMandatoryOptions() - { - return array('host', 'port', 'rt_host', 'rt_port'); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php b/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php deleted file mode 100644 index 8a2b5da964..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php +++ /dev/null @@ -1,68 +0,0 @@ -app = $app; - $this->options = $options; - - $mandatory = $this->getMandatoryOptions(); - - if ($mandatory !== array_intersect($mandatory, array_keys($options))) { - throw new MissingParameters( - sprintf( - 'Missing parameters %s' - , implode(', ', array_diff($mandatory, array_keys($options))) - ) - ); - } - - $this->init(); - } - - protected function init() - { - return; - } - - /** - * - * @return Array - */ - public function getOptions() - { - return $this->options; - } - - /** - * - * @return Array - */ - public function getMandatoryOptions() - { - return array(); - } -} diff --git a/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php b/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php deleted file mode 100644 index c625747b61..0000000000 --- a/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php +++ /dev/null @@ -1,29 +0,0 @@ -getOptions(); - $logger = $this->extendsLogger(clone $this->app['monolog'], $options); - - $this->taskManager = new \task_manager($this->app, $logger); - } - - private function extendsLogger(Logger $logger, $options) - { - $options = $this->getOptions(); - $registry = $this->app['phraseanet.registry']; - - if (isset($options['syslog_level']) && null !== $syslogLevel = constant($options['syslog_level'])) { - $handler = new SyslogHandler("Phraseanet-Task", "user", $syslogLevel); - $logger->pushHandler($handler); - } - - if (isset($options['maillog_level']) && null !== $maillogLevel = constant($options['maillog_level'])) { - if ('' === $adminMail = trim($registry->get('GV_adminMail'))) { - throw new RuntimeException("Admininstrator mail must be set to get log by mail."); - } - $senderMail = $registry->get('GV_defaultmailsenderaddr'); - - $handler = new NativeMailerHandler($adminMail, "Phraseanet-Task", $senderMail, $maillogLevel); - $logger->pushHandler($handler); - } - - return $logger; - } - - /** - * Set and return a new task_manager instance - * - * @return \task_manager - */ - public function getDriver() - { - return $this->taskManager; - } - - /** - * Return the type of the service - * - * @return string - */ - public function getType() - { - return 'task-manager'; - } - - /** - * Define the mandatory option for the current services - * - * @return array - */ - public function getMandatoryOptions() - { - return array(); - } - -} diff --git a/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php b/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php index 18bd1bf492..c860140da8 100644 --- a/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php +++ b/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php @@ -148,15 +148,13 @@ class PhraseaEngine implements SearchEngineInterface return $this; } - $choosenConnexion = $this->app['phraseanet.configuration']->getPhraseanet()->get('database'); + $connexion = $this->app['phraseanet.configuration']['main']['database']; - $connexion = $this->app['phraseanet.configuration']->getConnexion($choosenConnexion); - - $hostname = $connexion->get('host'); - $port = (int) $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); - $dbname = $connexion->get('dbname'); + $hostname = $connexion['host']; + $port = (int) $connexion['port']; + $user = $connexion['user']; + $password = $connexion['password']; + $dbname = $connexion['dbname']; if (!extension_loaded('phrasea2')) { throw new RuntimeException('Phrasea extension is required'); @@ -478,12 +476,11 @@ class PhraseaEngine implements SearchEngineInterface } /** - * Factory + * {@inheritdoc} * - * @param Application $app * @return PhraseaEngine */ - public static function create(Application $app) + public static function create(Application $app, array $options = array()) { return new static($app); } @@ -527,7 +524,7 @@ class PhraseaEngine implements SearchEngineInterface , $sbas_id , $this->colls[$sbas_id] , $this->arrayq[$sbas_id] - , $this->app['phraseanet.registry']->get('GV_sit') + , $this->app['phraseanet.configuration']['main']['key'] , $this->app['session']->get('usr_id') , false , $this->options->getSearchType() == SearchEngineOptions::RECORD_GROUPING ? PHRASEA_MULTIDOC_REGONLY : PHRASEA_MULTIDOC_DOCONLY diff --git a/lib/Alchemy/Phrasea/SearchEngine/SearchEngineInterface.php b/lib/Alchemy/Phrasea/SearchEngine/SearchEngineInterface.php index 4611493192..d156c12458 100644 --- a/lib/Alchemy/Phrasea/SearchEngine/SearchEngineInterface.php +++ b/lib/Alchemy/Phrasea/SearchEngine/SearchEngineInterface.php @@ -11,6 +11,7 @@ namespace Alchemy\Phrasea\SearchEngine; +use Alchemy\Phrasea\Application; use Alchemy\Phrasea\SearchEngine\SearchEngineOptions; use Alchemy\Phrasea\SearchEngine\SearchEngineResult; use Alchemy\Phrasea\Exception\RuntimeException; @@ -224,4 +225,12 @@ interface SearchEngineInterface * @return SearchEngineInterface */ public function clearAllCache(\DateTime $date = null); + + /** + * Creates the adapter. + * + * @param Application $app + * @param array $options + */ + public static function create(Application $app, array $options = array()); } diff --git a/lib/Alchemy/Phrasea/SearchEngine/SphinxSearch/SphinxSearchEngine.php b/lib/Alchemy/Phrasea/SearchEngine/SphinxSearch/SphinxSearchEngine.php index 85a9208293..4b4d6989d4 100644 --- a/lib/Alchemy/Phrasea/SearchEngine/SphinxSearch/SphinxSearchEngine.php +++ b/lib/Alchemy/Phrasea/SearchEngine/SphinxSearch/SphinxSearchEngine.php @@ -564,6 +564,16 @@ class SphinxSearchEngine implements SearchEngineInterface return $this; } + /** + * {@inheritdoc} + * + * @return SphinxSearchEngine + */ + public static function create(Application $app, array $options = array()) + { + return new static($app, $options['host'], $options['port'], $options['rt_host'], $options['rt_port']); + } + /** * Return unique integer key for a databox * diff --git a/lib/Alchemy/Phrasea/Setup/ConfigurationTester.php b/lib/Alchemy/Phrasea/Setup/ConfigurationTester.php index 59d7cf3eb3..a0b16fd89a 100644 --- a/lib/Alchemy/Phrasea/Setup/ConfigurationTester.php +++ b/lib/Alchemy/Phrasea/Setup/ConfigurationTester.php @@ -74,9 +74,7 @@ class ConfigurationTester */ public function isInstalled() { - return file_exists(__DIR__ . '/../../../../config/config.yml') - && file_exists(__DIR__ . '/../../../../config/connexions.yml') - && file_exists(__DIR__ . '/../../../../config/services.yml'); + return $this->app['phraseanet.configuration']->isSetup(); } /** diff --git a/lib/Alchemy/Phrasea/Setup/Installer.php b/lib/Alchemy/Phrasea/Setup/Installer.php index d469bc8982..f85e60e163 100644 --- a/lib/Alchemy/Phrasea/Setup/Installer.php +++ b/lib/Alchemy/Phrasea/Setup/Installer.php @@ -192,62 +192,22 @@ class Installer private function createConfigFile($abConn, $serverName, $binaryData) { - $this->app['phraseanet.configuration']->initialize(); - - $connexionINI = array(); + $config = $this->app['phraseanet.configuration']->initialize(); foreach ($abConn->get_credentials() as $key => $value) { $key = $key == 'hostname' ? 'host' : $key; - $connexionINI[$key] = (string) $value; + $config['main']['database'][$key] = (string) $value; } - $connexionINI['driver'] = 'pdo_mysql'; - $connexionINI['charset'] = 'UTF8'; + $config['main']['database']['driver'] = 'pdo_mysql'; + $config['main']['database']['charset'] = 'UTF8'; - $connexion = array( - 'main_connexion' => $connexionINI, - 'test_connexion' => array( - 'driver' => 'pdo_sqlite', - 'path' => '/tmp/db.sqlite', - 'charset' => 'UTF8' - )); + $config['binaries'] = $binaryData; - $cacheService = "array_cache"; + $config['main']['servername'] = $serverName; + $config['main']['key'] = md5(mt_rand(100000000, 999999999)); - $this->app['phraseanet.configuration']->setConnexions($connexion); - - $services = $this->app['phraseanet.configuration']->getServices(); - - foreach ($services as $serviceName => $service) { - foreach ($service as $name => $desc) { - if ($name === "doctrine_prod") { - - $services[$serviceName]["doctrine_prod"]["options"]["cache"] = array( - "query" => $cacheService, - "result" => $cacheService, - "metadata" => $cacheService - ); - } - } - } - $this->app['phraseanet.configuration']->setServices($services); - - $arrayConf = $this->app['phraseanet.configuration']->getConfigurations(); - - $arrayConf['key'] = md5(mt_rand(100000000, 999999999)); - $this->app['phraseanet.registry']->setKey($arrayConf['key']); - - foreach ($arrayConf as $key => $value) { - if (is_array($value) && array_key_exists('phraseanet', $value)) { - $arrayConf[$key]["phraseanet"]["servername"] = $serverName; - } - - if (is_array($value) && $key === 'prod') { - $arrayConf[$key]["cache"] = $cacheService; - } - } - - $this->app['phraseanet.configuration']->setConfigurations($arrayConf, $arrayConf['environment']); - $this->app['phraseanet.configuration']->setBinaries(array('binaries' => $binaryData)); + $this->app['phraseanet.registry']->setKey($config['main']['key']); + $this->app['phraseanet.configuration']->setConfig($config); } } diff --git a/lib/Alchemy/Phrasea/Setup/Probe/FilesystemProbe.php b/lib/Alchemy/Phrasea/Setup/Probe/FilesystemProbe.php index 2564fa930b..605cb1c2b2 100644 --- a/lib/Alchemy/Phrasea/Setup/Probe/FilesystemProbe.php +++ b/lib/Alchemy/Phrasea/Setup/Probe/FilesystemProbe.php @@ -23,10 +23,7 @@ class FilesystemProbe extends FilesystemRequirements implements ProbeInterface $baseDir = realpath(__DIR__ . '/../../../../../'); $paths = array( - $baseDir . '/config/config.yml', - $baseDir . '/config/connexions.yml', - $baseDir . '/config/services.yml', - $baseDir . '/config/binaries.yml', + $baseDir . '/config/configuration.yml', ); foreach ($paths as $path) { diff --git a/lib/Alchemy/Phrasea/Setup/Version/Migration/Migration35.php b/lib/Alchemy/Phrasea/Setup/Version/Migration/Migration35.php index 129dd283f9..56812fa069 100644 --- a/lib/Alchemy/Phrasea/Setup/Version/Migration/Migration35.php +++ b/lib/Alchemy/Phrasea/Setup/Version/Migration/Migration35.php @@ -29,7 +29,11 @@ class Migration35 implements MigrationInterface throw new \LogicException('Required config files not found'); } - $this->app['phraseanet.configuration']->initialize(); + $config = $this->app['phraseanet.configuration']->initialize(); + + foreach ($config['registration-fields'] as $key => $field) { + $config['registration-fields'][$key]['required'] = (boolean) $field['required']; + } $retrieve_old_credentials = function() { require __DIR__ . '/../../../../../../config/connexion.inc'; @@ -43,17 +47,11 @@ class Migration35 implements MigrationInterface ); }; - $connexions = $this->app['phraseanet.configuration']->getConnexions(); - foreach ($retrieve_old_credentials() as $key => $value) { $key = $key == 'hostname' ? 'host' : $key; - $connexions['main_connexion'][$key] = (string) $value; + $config['main']['database'][$key] = (string) $value; } - $this->app['phraseanet.configuration']->setConnexions($connexions); - - $configs = $this->app['phraseanet.configuration']->getConfigurations(); - $retrieve_old_parameters = function() { require __DIR__ . '/../../../../../../config/config.inc'; @@ -64,18 +62,11 @@ class Migration35 implements MigrationInterface $old_parameters = $retrieve_old_parameters(); - foreach ($configs as $env => $conf) { - if ( ! is_array($configs[$env]) || ! array_key_exists('phraseanet', $configs[$env])) { - continue; - } - - $configs[$env]['phraseanet']['servername'] = $old_parameters['servername']; - } + $config['main']['servername'] = $old_parameters['servername']; rename(__DIR__ . '/../../../../../../config/connexion.inc', __DIR__ . '/../../../../../../config/connexion.inc.old'); rename(__DIR__ . '/../../../../../../config/config.inc', __DIR__ . '/../../../../../../config/config.inc.old'); - $this->app['phraseanet.configuration']->setConfigurations($configs); - $this->app['phraseanet.configuration']->setEnvironnement('prod'); + $this->app['phraseanet.configuration']->setConfig($config); } } diff --git a/lib/classes/ACL.php b/lib/classes/ACL.php index 680d2a86b4..daf2fd6094 100644 --- a/lib/classes/ACL.php +++ b/lib/classes/ACL.php @@ -1456,7 +1456,7 @@ class ACL implements cache_cacheableInterface foreach ($this->get_granted_base(array(), array($databox->get_sbas_id())) as $collection) { $stmt->execute(array( - ':site_id' => $this->app['phraseanet.registry']->get('GV_sit'), + ':site_id' => $this->app['phraseanet.configuration']['main']['key'], ':usr_id' => $this->user->get_id(), ':coll_id' => $collection->get_coll_id(), ':mask_and' => $this->get_mask_and($collection->get_base_id()), @@ -1484,7 +1484,7 @@ class ACL implements cache_cacheableInterface $sql = 'DELETE FROM collusr WHERE usr_id = :usr_id AND site = :site'; $params = array( ':usr_id' => $this->user->get_id() - , ':site' => $this->app['phraseanet.registry']->get('GV_sit') + , ':site' => $this->app['phraseanet.configuration']['main']['key'] ); $stmt = $databox->get_connection()->prepare($sql); $stmt->execute($params); diff --git a/lib/classes/API/V1/adapter.php b/lib/classes/API/V1/adapter.php index 139a0b6578..4b85b1698a 100644 --- a/lib/classes/API/V1/adapter.php +++ b/lib/classes/API/V1/adapter.php @@ -313,10 +313,10 @@ class API_V1_adapter extends API_V1_Abstract ); $ret['phraseanet']['environment'] = $app->getEnvironment(); - $ret['phraseanet']['debug'] = $app['phraseanet.configuration']->isDebug(); - $ret['phraseanet']['maintenance'] = $app['phraseanet.configuration']->isMaintained(); - $ret['phraseanet']['errorsLog'] = $app['phraseanet.configuration']->isDisplayingErrors(); - $ret['phraseanet']['serverName'] = $app['phraseanet.configuration']->getPhraseanet()->get('servername'); + $ret['phraseanet']['debug'] = $app['debug']; + $ret['phraseanet']['maintenance'] = $app['phraseanet.configuration']['main']['maintenance']; + $ret['phraseanet']['errorsLog'] = $app['debug']; + $ret['phraseanet']['serverName'] = $app['phraseanet.configuration']['main']['servername']; return $ret; } @@ -343,7 +343,7 @@ class API_V1_adapter extends API_V1_Abstract 'httpServer' => array( 'logErrors' => $app['phraseanet.registry']->get('GV_log_errors'), 'phpTimezone' => ini_get('date.timezone'), - 'siteId' => $app['phraseanet.registry']->get('GV_sit'), + 'siteId' => $app['phraseanet.configuration']['main']['key'], 'staticUrl' => $app['phraseanet.registry']->get('GV_STATIC_URL'), 'defaultLanguage' => $app['phraseanet.registry']->get('id_GV_default_lng'), 'allowIndexing' => $app['phraseanet.registry']->get('GV_allow_search_engine'), diff --git a/lib/classes/API/V1/result.php b/lib/classes/API/V1/result.php index dc8f001539..95d8aefb37 100644 --- a/lib/classes/API/V1/result.php +++ b/lib/classes/API/V1/result.php @@ -198,9 +198,9 @@ class API_V1_result $this->app['dispatcher']->dispatch(PhraseaEvents::API_RESULT, new ApiResultEvent()); - $conf = $this->app['phraseanet.configuration']->getPhraseanet(); + $conf = $this->app['phraseanet.configuration']; - if ($conf->has('api-timers') && true === $conf->get('api-timers')) { + if (isset($conf['main']['api-timers']) && true === $conf['main']['api-timers']) { $ret['timers'] = $this->app['api.timers']->toArray(); } diff --git a/lib/classes/Session/Logger.php b/lib/classes/Session/Logger.php index 59fd863a09..d9998cecc5 100644 --- a/lib/classes/Session/Logger.php +++ b/lib/classes/Session/Logger.php @@ -125,7 +125,7 @@ class Session_Logger $params = array( ':ses_id' => $app['session']->get('session_id'), ':usr_login' => $app['authentication']->getUser() ? $app['authentication']->getUser()->get_login() : null, - ':site_id' => $app['phraseanet.registry']->get('GV_sit'), + ':site_id' => $app['phraseanet.configuration']['main']['key'], ':usr_id' => $app['authentication']->isAuthenticated() ? $app['authentication']->getUser()->get_id() : null, ':browser' => $browser->getBrowser(), ':browser_version' => $browser->getExtendedVersion(), @@ -171,7 +171,7 @@ class Session_Logger WHERE site = :site AND sit_session = :ses_id'; $params = array( - ':site' => $app['phraseanet.registry']->get('GV_sit') + ':site' => $app['phraseanet.configuration']['main']['key'] , ':ses_id' => $app['session']->get('session_id') ); diff --git a/lib/classes/appbox.php b/lib/classes/appbox.php index 43b7c42912..d03b51d563 100644 --- a/lib/classes/appbox.php +++ b/lib/classes/appbox.php @@ -63,15 +63,13 @@ class appbox extends base { $this->app = $app; $this->connection = connection::getPDOConnection($app); - $choosenConnexion = $app['phraseanet.configuration']->getPhraseanet()->get('database'); + $connexion = $app['phraseanet.configuration']['main']['database']; - $connexion = $app['phraseanet.configuration']->getConnexion($choosenConnexion); - - $this->host = $connexion->get('host'); - $this->port = $connexion->get('port'); - $this->user = $connexion->get('user'); - $this->passwd = $connexion->get('password'); - $this->dbname = $connexion->get('dbname'); + $this->host = $connexion['host']; + $this->port = $connexion['port']; + $this->user = $connexion['user']; + $this->passwd = $connexion['password']; + $this->dbname = $connexion['dbname']; return $this; } diff --git a/lib/classes/base.php b/lib/classes/base.php index 5a16211aeb..c43fee9a87 100644 --- a/lib/classes/base.php +++ b/lib/classes/base.php @@ -171,7 +171,13 @@ abstract class base implements cache_cacheableInterface \cache_databox::refresh($this->app, $this->id); } - return $this->get_cache()->get($this->get_cache_key($option)); + $data = $this->get_cache()->get($this->get_cache_key($option)); + + if (is_object($data) && method_exists($data, 'hydrate')) { + $data->hydrate($this->app); + } + + return $data; } public function set_data_to_cache($value, $option = null, $duration = 0) diff --git a/lib/classes/connection.php b/lib/classes/connection.php index dbc30df592..604433b5ef 100644 --- a/lib/classes/connection.php +++ b/lib/classes/connection.php @@ -129,15 +129,13 @@ class connection if (trim($name) !== 'appbox') { $connection_params = phrasea::sbas_params($app); } else { - $choosenConnexion = $app['phraseanet.configuration']->getPhraseanet()->get('database'); + $connexion = $app['phraseanet.configuration']['main']['database']; - $connexion = $app['phraseanet.configuration']->getConnexion($choosenConnexion); - - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); - $dbname = $connexion->get('dbname'); + $hostname = $connexion['host']; + $port = $connexion['port']; + $user = $connexion['user']; + $password = $connexion['password']; + $dbname = $connexion['dbname']; } if (isset($connection_params[$name])) { diff --git a/lib/classes/databox.php b/lib/classes/databox.php index 6cebd1abcd..625f45e6c0 100644 --- a/lib/classes/databox.php +++ b/lib/classes/databox.php @@ -356,7 +356,7 @@ class databox extends base $this->app['EM']->flush(); - $params = array(':site_id' => $this->app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $this->app['phraseanet.configuration']['main']['key']); $sql = 'DELETE FROM clients WHERE site_id = :site_id'; $stmt = $this->get_connection()->prepare($sql); @@ -541,26 +541,23 @@ class databox extends base } try { - $this->meta_struct = $this->get_data_from_cache(self::CACHE_META_STRUCT); - - return $this->meta_struct; + $metaStructData = $this->get_data_from_cache(self::CACHE_META_STRUCT); } catch (Exception $e) { - unset($e); + $sql = 'SELECT id, name FROM metadatas_structure ORDER BY sorter ASC'; + $stmt = $this->get_connection()->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + $metaStructData = $rs; + $this->set_data_to_cache($metaStructData, self::CACHE_META_STRUCT); } - $meta_struct = new databox_descriptionStructure(); + $this->meta_struct = new databox_descriptionStructure(); - $sql = 'SELECT id, name FROM metadatas_structure ORDER BY sorter ASC'; - $stmt = $this->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) { - $meta_struct->add_element(databox_field::get_instance($this->app, $this, $row['id'])); + foreach ($metaStructData as $row) { + $this->meta_struct->add_element(databox_field::get_instance($this->app, $this, $row['id'])); } - $this->meta_struct = $meta_struct; - $this->set_data_to_cache($this->meta_struct, self::CACHE_META_STRUCT); return $this->meta_struct; } @@ -1322,6 +1319,28 @@ class databox extends base return $this; } + public function __sleep() + { + $this->_sxml_structure = $this->_dom_structure = $this->_xpath_structure = null; + + $vars = array(); + + foreach ($this as $key => $value) { + if (in_array($key, array('app', 'meta_struct'))) { + continue; + } + + $vars[] = $key; + } + + return $vars; + } + + public function hydrate(Application $app) + { + $this->app = $app; + } + public function delete_data_from_cache($option = null) { switch ($option) { diff --git a/lib/classes/databox/field.php b/lib/classes/databox/field.php index 81c8373803..404c6b4263 100644 --- a/lib/classes/databox/field.php +++ b/lib/classes/databox/field.php @@ -291,6 +291,12 @@ class databox_field implements cache_cacheableInterface return self::$_instance[$instance_id]; } + public function hydrate(Application $app) + { + $this->app = $app; + $this->set_databox($this->app['phraseanet.appbox']->get_databox($this->sbas_id)); + } + /** * * @param databox $databox @@ -483,7 +489,7 @@ class databox_field implements cache_cacheableInterface */ public function get_label($code) { - if (!array_key_exists($code, $this->labels)) { + if (null !== $code && !array_key_exists($code, $this->labels)) { throw new InvalidArgumentException(sprintf('Code %s is not defined', $code)); } @@ -996,7 +1002,7 @@ class databox_field implements cache_cacheableInterface { $vars = array(); foreach ($this as $key => $value) { - if (in_array($key, array('databox'))) + if (in_array($key, array('databox', 'app'))) continue; $vars[] = $key; } @@ -1004,17 +1010,6 @@ class databox_field implements cache_cacheableInterface return $vars; } - /** - * - * @return void - */ - public function __wakeup() - { - $this->set_databox($this->app['phraseanet.appbox']->get_databox($this->sbas_id)); - - return; - } - /** * Part of the cache_cacheableInterface * diff --git a/lib/classes/module/console/checkExtension.php b/lib/classes/module/console/checkExtension.php index 8731520412..5ecfc18f05 100644 --- a/lib/classes/module/console/checkExtension.php +++ b/lib/classes/module/console/checkExtension.php @@ -71,13 +71,12 @@ class module_console_checkExtension extends Command } $configuration = $this->getService('phraseanet.configuration'); - $choosenConnection = $configuration->getPhraseanet()->get('database'); - $connexion = $configuration->getConnexion($choosenConnection); - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); - $dbname = $connexion->get('dbname'); + $connexion = $configuration['main']['database']; + $hostname = $connexion['host']; + $port = $connexion['port']; + $user = $connexion['user']; + $password = $connexion['password']; + $dbname = $connexion['dbname']; $output->writeln("\n-- phrasea_conn --"); @@ -168,7 +167,7 @@ class module_console_checkExtension extends Command , $base["sbas_id"] , $base["searchcoll"] , $base["arrayq"] - , $this->container['phraseanet.registry']->get('GV_sit') + , $this->container['phraseanet.configuration']['main']['key'] , $usrId , false , PHRASEA_MULTIDOC_DOCONLY diff --git a/lib/classes/module/console/fileEnsureDevSetting.php b/lib/classes/module/console/fileEnsureDevSetting.php deleted file mode 100644 index 67f954f061..0000000000 --- a/lib/classes/module/console/fileEnsureDevSetting.php +++ /dev/null @@ -1,828 +0,0 @@ -setDescription('Ensure development settings'); - - $this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null); - $this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not'); - - return $this; - } - - protected function doExecute(InputInterface $input, OutputInterface $output) - { - $this->configuration = $this->container['phraseanet.configuration']; - - $this->checkParse($output); - $output->writeln(sprintf("Will Ensure Development Settings on %s", $this->configuration->getEnvironnement())); - - $this->runTests($output); - - $retval = $this->errors; - - if ($input->getOption('strict')) { - $retval += $this->alerts; - } - - if ($retval > 0) { - $output->writeln("\nSome errors found in your conf"); - } else { - $output->writeln("\nYour dev settings are setted correctly ! Enjoy"); - } - - $output->writeln('End'); - - return $retval; - } - - private function runTests(OutputInterface $output) - { - foreach ($this->testSuite as $test) { - $display = ""; - switch ($test) { - case 'checkPhraseanetScope' : - $display = "Phraseanet Configuration"; - break; - case 'checkDatabaseScope' : - $display = "Database"; - break; - case 'checkTeamplateEngineService' : - $display = "Template Engine"; - break; - case 'checkOrmService' : - $display = "ORM"; - break; - case 'checkCacheService' : - $display = "Cache"; - break; - case 'checkOpcodeCacheService' : - $display = "Opcode"; - break; - case 'checkBorderService' : - $display = "Border"; - break; - default: - throw new \Exception('Unknown test'); - break; - } - - $output->writeln(sprintf("\n||| %s", mb_strtoupper($display))); - - call_user_func(array($this, $test), $output); - } - } - - private function checkParse(OutputInterface $output) - { - - if (!$this->configuration->getConfigurations()) { - throw new \Exception("Unable to load configurations\n"); - } - - if (!$this->configuration->getConnexions()) { - throw new \Exception("Unable to load connexions\n"); - } - - if (!$this->configuration->getServices()) { - throw new \Exception("Unable to load services\n"); - } - - return; - } - - private function checkCacheService(OutputInterface $output) - { - $cache = $this->configuration->getCache(); - - if ($this->probeCacheService($output, $cache)) { - if ($this->recommendedCacheService($output, $cache, true)) { - $work_message = 'Works !'; - } else { - $work_message = 'Cache server recommended'; - $this->alerts++; - } - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $verification = sprintf("\t--> Verify %s : %s", 'MainCache', $work_message); - - $this->printConf($output, "\t" . 'service', $cache, false, $verification); - $this->verifyCacheOptions($output, $cache); - } - - private function checkOpcodeCacheService(OutputInterface $output) - { - $cache = $this->configuration->getOpcodeCache(); - - if ($this->probeCacheService($output, $cache)) { - if ($this->recommendedCacheService($output, $cache, false)) { - $work_message = 'Works !'; - } else { - $work_message = 'No cache required'; - $this->errors++; - } - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $verification = sprintf("\t--> Verify %s : %s", 'OpcodeCache', $work_message); - - $this->printConf($output, "\t" . 'service', $cache, false, $verification); - $this->verifyCacheOptions($output, $cache); - } - - private function checkBorderService(OutputInterface $output) - { - $serviceName = $this->configuration->getBorder(); - $configuration = $this->configuration->getService($serviceName); - - $listChecks = false; - try { - $service = Builder::create($this->container, $configuration); - $work_message = 'Works !'; - $listChecks = true; - } catch (\Exception $e) { - $work_message = 'Failed - could not load Border Manager service !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify Border Manager%s : %s", $serviceName, $work_message)); - - if ($listChecks) { - $borderManager = $service->getDriver(); - - foreach ($service->getUnregisteredCheckers() as $check) { - $output->writeln(sprintf("\t\t--> check %s could not be loaded for the following reason %s", $check['checker'], $check['message'])); - } - } - } - - private function checkPhraseanetScope(OutputInterface $output) - { - $required = array('servername', 'maintenance', 'debug', 'display_errors', 'database'); - - $phraseanet = $this->configuration->getPhraseanet(); - - foreach ($phraseanet->all() as $conf => $value) { - switch ($conf) { - default: - $this->alerts++; - $this->printConf($output, $conf, $value, false, 'Not recognized'); - break; - case 'servername': - $url = $value; - $required = array_diff($required, array($conf)); - - $parseUrl = parse_url($url); - - if (empty($url)) { - $message = "should not be empty"; - $this->errors++; - } elseif ($url == 'http://sub.domain.tld/') { - $this->alerts++; - $message = "may be wrong"; - } elseif (!filter_var($url, FILTER_VALIDATE_URL)) { - $message = "not valid"; - $this->errors++; - } else { - $message = "OK"; - } - $this->printConf($output, $conf, $value, false, $message); - break; - case 'maintenance': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== false) { - $message = 'Should be true'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'debug': - case 'display_errors': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== true) { - $message = 'Should be true'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'database': - $required = array_diff($required, array($conf)); - try { - $service = $this->configuration->getConnexion($value); - if ($this->verifyDatabaseConnexion($service)) { - $message = 'OK'; - } else { - $message = 'Connection not available'; - $this->errors++; - } - } catch (\Exception $e) { - $message = 'Unknown connection'; - $this->errors++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - private function checkDatabaseScope(OutputInterface $output) - { - $connexionName = $this->configuration->getPhraseanet()->get('database'); - $connexion = $this->configuration->getConnexion($connexionName); - - try { - if ($this->verifyDatabaseConnexion($connexion)) { - $work_message = 'Works !'; - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - } catch (\Exception $e) { - - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify connection %s : %s", $connexionName, $work_message)); - - $required = array('driver'); - - if (!$connexion->has('driver')) { - $output->writeln("\nConnection has no driver"); - $this->errors++; - } elseif ($connexion->get('driver') == 'pdo_mysql') { - $required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host'); - } elseif ($connexion->get('driver') == 'pdo_sqlite') { - $required = array('driver', 'path', 'charset'); - } else { - $output->writeln("\nYour driver is not managed"); - $this->errors++; - } - - foreach ($connexion->all() as $conf => $value) { - switch ($conf) { - default: - $this->alerts++; - $this->printConf($output, $conf, $value, false, 'Not recognized'); - break; - case 'charset': - $required = array_diff($required, array($conf)); - $message = 'OK'; - if ($value !== 'UTF8') { - $message = 'Not recognized'; - $this->alerts++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - case 'path': - $required = array_diff($required, array($conf)); - $message = is_writable(dirname($value)) ? 'OK' : 'Not writeable'; - $this->printConf($output, $conf, $value, false, $message); - break; - case 'dbname': - case 'user': - case 'host': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!is_scalar($value)) { - $message = 'Should be scalar'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'port': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!ctype_digit($value)) { - $message = 'Should be ctype_digit'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'password': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!is_scalar($value)) { - $message = 'Should be scalar'; - $this->errors++; - } - - $value = '***********'; - $this->printConf($output, $conf, $value, false, $message); - break; - case 'driver': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== 'pdo_mysql') { - $message = 'MySQL recommended'; - $this->errors++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion) - { - try { - $config = new \Doctrine\DBAL\Configuration(); - $conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config); - - return true; - } catch (\Exception $e) { - - } - - return false; - } - - private function checkTeamplateEngineService(OutputInterface $output) - { - $templateEngineName = $this->configuration->getTemplating(); - $configuration = $this->configuration->getService($templateEngineName); - - try { - Builder::create($this->container, $configuration); - $work_message = 'Works !'; - } catch (\Exception $e) { - $work_message = 'Failed - could not load template engine !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify Template engine %s : %s", $templateEngineName, $work_message)); - - if (!$configuration->has('type')) { - $output->writeln("\nConfiguration has no type"); - $this->errors++; - } elseif ($configuration->get('type') == 'TemplateEngine\\Twig') { - $required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer'); - } else { - $output->writeln("\nYour type is not managed"); - $this->errors++; - } - - foreach ($configuration->all() as $conf => $value) { - switch ($conf) { - case 'type': - $message = 'OK'; - - if ($value !== 'TemplateEngine\\Twig') { - $message = 'Not recognized'; - $this->alerts++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'options': - $message = 'OK'; - - if (!is_array($value)) { - $message = 'Should be array'; - $this->errors++; - } - - $this->printConf($output, $conf, 'array()', false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, $conf, 'unknown', false, 'Not recognized'); - break; - } - } - - foreach ($configuration->get('options') as $conf => $value) { - switch ($conf) { - case 'debug'; - case 'strict_variables'; - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== true) { - $message = 'Should be false'; - $this->errors++; - } - - $this->printConf($output, "\t" . $conf, $value, false, $message); - break; - case 'autoescape'; - case 'optimizer'; - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== true) { - $message = 'Should be true'; - $this->errors++; - } - - $this->printConf($output, "\t" . $conf, $value, false, $message); - break; - case 'charset'; - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== 'utf-8') { - $message = 'Not recognized'; - $this->alerts++; - } - - $this->printConf($output, "\t" . $conf, $value, false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, "\t" . $conf, $value, false, 'Not recognized'); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - private function checkOrmService(OutputInterface $output) - { - $ormName = $this->configuration->getOrm(); - $configuration = $this->configuration->getService($ormName); - - try { - $service = Builder::create($this->container, $configuration); - $work_message = 'Works !'; - } catch (\Exception $e) { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $ormName, $work_message)); - - if (!$configuration->has('type')) { - $output->writeln("\nConfiguration has no type"); - $this->errors++; - } elseif ($configuration->get('type') == 'Orm\\Doctrine') { - $required = array('debug', 'dbal', 'cache'); - } else { - $output->writeln("\nYour type is not managed"); - $this->errors++; - } - - foreach ($configuration->all() as $conf => $value) { - switch ($conf) { - case 'type': - $message = $value == 'Orm\\Doctrine' ? 'OK' : 'Not recognized'; - $this->printConf($output, $conf, $value, false, $message); - break; - case 'options': - $message = 'OK'; - - if (!is_array($value)) { - $message = 'Should be array'; - $this->errors++; - } - - $this->printConf($output, $conf, 'array()', false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, $conf, 'unknown', false, 'Not recognized'); - break; - } - } - - foreach ($configuration->get('options') as $conf => $value) { - switch ($conf) { - case 'log': - $message = 'OK'; - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'cache': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!is_array($value)) { - $message = 'Should be Array'; - $this->errors++; - } - - $this->printConf($output, $conf, 'array()', false, $message); - - $required_caches = array('query', 'result', 'metadata'); - foreach ($value as $name => $cache_type) { - $required_caches = array_diff($required_caches, array($name)); - - foreach ($cache_type as $key_cache => $value_cache) { - switch ($key_cache) { - case 'service': - if ($this->probeCacheService($output, $value_cache)) { - $server = $name === 'result'; - if ($this->recommendedCacheService($output, $value_cache, $server)) { - $work_message = 'Works !'; - } else { - $this->errors++; - $work_message = 'No cache required'; - } - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $verification = sprintf("\t--> Verify %s : %s", $name, $work_message); - - $this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification); - $this->verifyCacheOptions($output, $value_cache); - break; - default: - $this->alerts++; - $this->printConf($output, "\t" . $key_cache, $value_cache, false, 'Not recognized'); - break; - } - if (!isset($cache_type['service'])) { - $output->writeln('Miss service for %s', $cache_type); - $this->errors++; - } - } - } - - if (count($required_caches) > 0) { - $output->writeln(sprintf('Miss required caches %s', implode(', ', $required_caches))); - $this->errors++; - } - break; - case 'debug': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== true) { - $message = 'Should be true'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'dbal': - $required = array_diff($required, array($conf)); - try { - $connexion = $this->configuration->getConnexion($value); - $this->verifyDatabaseConnexion($connexion); - $message = 'OK'; - } catch (\Exception $e) { - $message = 'Failed'; - $this->errors++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, $conf, $value, false, 'Not recognized'); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - protected function verifyCacheOptions(OutputInterface $output, $ServiceName) - { - try { - $conf = $this->configuration->getService($ServiceName); - - $Service = Builder::create($this->container, $conf); - } catch (\Exception $e) { - return false; - } - - $required_options = array(); - - switch ($Service->getType()) { - default: - break; - case 'memcache': - case 'memcached': - case 'redis': - $required_options = array('host', 'port'); - break; - } - - if ($required_options) { - foreach ($conf->get('options') as $conf => $value) { - switch ($conf) { - case 'host'; - $required_options = array_diff($required_options, array($conf)); - $message = 'OK'; - - if (!is_scalar($value)) { - $message = 'Should be scalar'; - $this->errors++; - } - - $this->printConf($output, "\t\t" . $conf, $value, false, $message); - break; - case 'port'; - $required_options = array_diff($required_options, array($conf)); - $message = 'OK'; - - if (!ctype_digit($value)) { - $message = 'Not recognized'; - $this->alerts++; - } - - $this->printConf($output, "\t\t" . $conf, $value, false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, "\t\t" . $conf, $value, false, 'Not recognized'); - break; - } - } - } - - if (count($required_options) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required_options))); - $this->errors++; - } - } - - protected function probeCacheService(OutputInterface $output, $ServiceName) - { - try { - $originalConfiguration = $this->configuration->getService($ServiceName); - - $Service = Builder::create($this->container, $originalConfiguration); - } catch (\Exception $e) { - return false; - } - - try { - $driver = $Service->getDriver(); - } catch (\Exception $e) { - return false; - } - - if ($driver->isServer()) { - switch ($Service->getType()) { - default: - return false; - break; - case 'memcache': - if (!@memcache_connect($Service->getHost(), $Service->getPort())) { - return false; - } - break; - case 'memcached': - $ret = false; - try { - $memcached = new \Memcached(); - $memcached->addServer($Service->getHost(), $Service->getPort()); - $stats = $memcached->getStats(); - - if (!isset($stats[$key]) || !$stats[$key]) { - throw new \Exception('Unable to connect to memcached server'); - } - - $ret = true; - } catch (\Exception $e) { - - } - - unset($memcached); - - return $ret; - break; - case 'redis': - $ret = false; - try { - $redis = new \Redis(); - if (@$redis->connect($Service->getHost(), $Service->getPort())) { - $ret = true; - } - } catch (\Exception $e) { - - } - unset($redis); - - return $ret; - break; - } - } - - return true; - } - - protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server) - { - try { - $originalConfiguration = $this->configuration->getService($ServiceName); - - $Service = Builder::create($this->container, $originalConfiguration); - } catch (\Exception $e) { - return false; - } - - return $Service->getType() === 'array'; - } - - private function printConf($output, $scope, $value, $scopage = false, $message = '') - { - if (is_array($value)) { - foreach ($value as $key => $val) { - if ($scopage) - $key = $scope . ":" . $key; - $this->printConf($output, $key, $val, $scopage, ''); - } - } elseif (is_bool($value)) { - if ($value === false) { - $value = 'false'; - } elseif ($value === true) { - $value = 'true'; - } - $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message)); - } elseif (!empty($value)) { - $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message)); - } - } -} diff --git a/lib/classes/module/console/fileEnsureProductionSetting.php b/lib/classes/module/console/fileEnsureProductionSetting.php deleted file mode 100644 index aa8fb9e4fd..0000000000 --- a/lib/classes/module/console/fileEnsureProductionSetting.php +++ /dev/null @@ -1,850 +0,0 @@ -setDescription('Ensure production settings'); - - $this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null); - $this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not'); - - return $this; - } - - protected function doExecute(InputInterface $input, OutputInterface $output) - { - $this->configuration = $this->container['phraseanet.configuration']; - - $this->checkParse($output); - $output->writeln(sprintf("Will Ensure Production Settings on %s", $this->configuration->getEnvironnement())); - - $this->runTests($output); - - $retval = $this->errors; - if ($input->getOption('strict')) { - $retval += $this->alerts; - } - - if ($retval > 0) { - $output->writeln("\nSome errors found in your conf"); - } else { - $output->writeln("\nYour production settings are setted correctly ! Enjoy"); - } - $output->writeln('End'); - - return $retval; - } - - private function runTests(OutputInterface $output) - { - foreach ($this->testSuite as $test) { - $display = ""; - switch ($test) { - case 'checkPhraseanetScope' : - $display = "Phraseanet Configuration"; - break; - case 'checkDatabaseScope' : - $display = "Database"; - break; - case 'checkTeamplateEngineService' : - $display = "Template Engine"; - break; - case 'checkOrmService' : - $display = "ORM"; - break; - case 'checkSearchEngineService': - $display = 'Search Engine'; - break; - case 'checkCacheService' : - $display = "Cache"; - break; - case 'checkOpcodeCacheService' : - $display = "Opcode"; - break; - case 'checkBorderService' : - $display = "Border"; - break; - default: - throw new \Exception('Unknown test'); - break; - } - - $output->writeln(sprintf("\n||| %s", mb_strtoupper($display))); - - call_user_func(array($this, $test), $output); - } - } - - private function checkParse(OutputInterface $output) - { - - if (!$this->configuration->getConfigurations()) { - throw new \Exception("Unable to load configurations\n"); - } - if (!$this->configuration->getConnexions()) { - throw new \Exception("Unable to load connexions\n"); - } - if (!$this->configuration->getServices()) { - throw new \Exception("Unable to load services\n"); - } - - return; - } - - private function checkCacheService(OutputInterface $output) - { - $cache = $this->configuration->getCache(); - - if ($this->probeCacheService($output, $cache)) { - if ($this->recommendedCacheService($output, $cache, true)) { - $work_message = 'Works !'; - } else { - $work_message = 'Cache server recommended'; - $this->alerts++; - } - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $verification = sprintf("\t--> Verify %s : %s", 'MainCache', $work_message); - - $this->printConf($output, "\t" . 'service', $cache, false, $verification); - $this->verifyCacheOptions($output, $cache); - } - - private function checkOpcodeCacheService(OutputInterface $output) - { - $cache = $this->configuration->getOpcodeCache(); - - if ($this->probeCacheService($output, $cache)) { - if ($this->recommendedCacheService($output, $cache, false)) { - $work_message = 'Works !'; - } else { - $work_message = 'Opcode recommended'; - $this->alerts++; - } - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $verification = sprintf("\t--> Verify %s : %s", 'OpcodeCache', $work_message); - - $this->printConf($output, "\t" . 'service', $cache, false, $verification); - $this->verifyCacheOptions($output, $cache); - } - - private function checkBorderService(OutputInterface $output) - { - $serviceName = $this->configuration->getBorder(); - $configuration = $this->configuration->getService($serviceName); - - $listChecks = false; - try { - $service = Builder::create($this->container, $configuration); - $work_message = 'Works !'; - $listChecks = true; - } catch (\Exception $e) { - $work_message = 'Failed - could not load Border Manager service !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify Border Manager%s : %s", $serviceName, $work_message)); - - if ($listChecks) { - $borderManager = $service->getDriver(); - - foreach ($service->getUnregisteredCheckers() as $check) { - $output->writeln(sprintf("\t\t--> check %s could not be loaded for the following reason %s", $check['checker'], $check['message'])); - } - } - } - - private function checkPhraseanetScope(OutputInterface $output) - { - $required = array('servername', 'maintenance', 'debug', 'display_errors', 'database'); - - $phraseanet = $this->configuration->getPhraseanet(); - - foreach ($phraseanet->all() as $conf => $value) { - switch ($conf) { - default: - $this->alerts++; - $this->printConf($output, $conf, $value, false, 'Not recognized'); - break; - case 'servername': - $url = $value; - $required = array_diff($required, array($conf)); - - $parseUrl = parse_url($url); - - if (empty($url)) { - $message = "should not be empty"; - $this->errors++; - } elseif ($url == 'http://sub.domain.tld/') { - $this->alerts++; - $message = "may be wrong"; - } elseif (!filter_var($url, FILTER_VALIDATE_URL)) { - $message = "not valid"; - $this->errors++; - } elseif ($parseUrl["scheme"] !== "https") { - $this->alerts++; - $message = "should be https"; - } else { - $message = "OK"; - } - $this->printConf($output, $conf, $value, false, $message); - break; - case 'maintenance': - case 'debug': - case 'display_errors': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== false) { - $message = 'Should be false'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'database': - $required = array_diff($required, array($conf)); - try { - $service = $this->configuration->getConnexion($value); - if ($this->verifyDatabaseConnexion($service)) { - $message = 'OK'; - } else { - $message = 'Connection not available'; - $this->errors++; - } - } catch (\Exception $e) { - $message = 'Unknown connection'; - $this->errors++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - private function checkDatabaseScope(OutputInterface $output) - { - $connexionName = $this->configuration->getPhraseanet()->get('database'); - $connexion = $this->configuration->getConnexion($connexionName); - - try { - if ($this->verifyDatabaseConnexion($connexion)) { - $work_message = 'Works !'; - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - } catch (\Exception $e) { - - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify connection %s : %s", $connexionName, $work_message)); - - $required = array('driver'); - - if (!$connexion->has('driver')) { - $output->writeln("\nConnection has no driver"); - $this->errors++; - } elseif ($connexion->get('driver') == 'pdo_mysql') { - $required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host'); - } elseif ($connexion->get('driver') == 'pdo_sqlite') { - $required = array('driver', 'path', 'charset'); - } else { - $output->writeln("\nYour driver is not managed"); - $this->errors++; - } - - foreach ($connexion->all() as $conf => $value) { - switch ($conf) { - default: - $this->alerts++; - $this->printConf($output, $conf, $value, false, 'Not recognized'); - break; - case 'charset': - $required = array_diff($required, array($conf)); - $message = 'OK'; - if ($value !== 'UTF8') { - $message = 'Not recognized'; - $this->alerts++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - case 'path': - $required = array_diff($required, array($conf)); - $message = is_writable(dirname($value)) ? 'OK' : 'Not writeable'; - $this->printConf($output, $conf, $value, false, $message); - break; - case 'dbname': - case 'user': - case 'host': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!is_scalar($value)) { - $message = 'Should be scalar'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'port': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!ctype_digit($value)) { - $message = 'Should be ctype_digit'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'password': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!is_scalar($value)) { - $message = 'Should be scalar'; - $this->errors++; - } - - $value = '***********'; - $this->printConf($output, $conf, $value, false, $message); - break; - case 'driver': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== 'pdo_mysql') { - $message = 'MySQL recommended'; - $this->errors++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion) - { - try { - $config = new \Doctrine\DBAL\Configuration(); - $conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config); - - return true; - } catch (\Exception $e) { - - } - - return false; - } - - private function checkTeamplateEngineService(OutputInterface $output) - { - $templateEngineName = $this->configuration->getTemplating(); - $configuration = $this->configuration->getService($templateEngineName); - - try { - Builder::create($this->container, $configuration); - $work_message = 'Works !'; - } catch (\Exception $e) { - $work_message = 'Failed - could not load template engine !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify Template engine %s : %s", $templateEngineName, $work_message)); - - if (!$configuration->has('type')) { - $output->writeln("\nConfiguration has no type"); - $this->errors++; - } elseif ($configuration->get('type') == 'TemplateEngine\\Twig') { - $required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer'); - } else { - $output->writeln("\nYour type is not managed"); - $this->errors++; - } - - foreach ($configuration->all() as $conf => $value) { - switch ($conf) { - case 'type': - $message = 'OK'; - - if ($value !== 'TemplateEngine\\Twig') { - $message = 'Not recognized'; - $this->alerts++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'options': - $message = 'OK'; - - if (!is_array($value)) { - $message = 'Should be array'; - $this->errors++; - } - - $this->printConf($output, $conf, 'array()', false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, $conf, 'unknown', false, 'Not recognized'); - break; - } - } - - foreach ($configuration->get('options') as $conf => $value) { - switch ($conf) { - case 'debug'; - case 'strict_variables'; - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== false) { - $message = 'Should be false'; - $this->errors++; - } - - $this->printConf($output, "\t" . $conf, $value, false, $message); - break; - case 'autoescape'; - case 'optimizer'; - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== true) { - $message = 'Should be true'; - $this->errors++; - } - - $this->printConf($output, "\t" . $conf, $value, false, $message); - break; - case 'charset'; - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== 'utf-8') { - $message = 'Not recognized'; - $this->alerts++; - } - - $this->printConf($output, "\t" . $conf, $value, false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, "\t" . $conf, $value, false, 'Not recognized'); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - private function checkSearchEngineService(OutputInterface $output) - { - $SEName = $this->configuration->getSearchEngine(); - $configuration = $this->configuration->getService($SEName); - - try { - $service = Builder::create($this->container, $configuration); - $work_message = 'Works !'; - } catch (\Exception $e) { - $work_message = sprintf('Failed : %s !', $e->getMessage()); - $this->errors ++; - } - - $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $SEName, $work_message)); - } - - private function checkOrmService(OutputInterface $output) - { - $ormName = $this->configuration->getOrm(); - $configuration = $this->configuration->getService($ormName); - - try { - $service = Builder::create($this->container, $configuration); - $work_message = 'Works !'; - } catch (\Exception $e) { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $ormName, $work_message)); - - if (!$configuration->has('type')) { - $output->writeln("\nConfiguration has no type"); - $this->errors++; - } elseif ($configuration->get('type') == 'Orm\\Doctrine') { - $required = array('debug', 'dbal', 'cache'); - } else { - $output->writeln("\nYour type is not managed"); - $this->errors++; - } - - foreach ($configuration->all() as $conf => $value) { - switch ($conf) { - case 'type': - $message = $value == 'Orm\\Doctrine' ? 'OK' : 'Not recognized'; - $this->printConf($output, $conf, $value, false, $message); - break; - case 'options': - $message = 'OK'; - - if (!is_array($value)) { - $message = 'Should be array'; - $this->errors++; - } - - $this->printConf($output, $conf, 'array()', false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, $conf, 'unknown', false, 'Not recognized'); - break; - } - } - - foreach ($configuration->get('options') as $conf => $value) { - switch ($conf) { - case 'log': - $message = 'OK'; - - if ($value !== false) { - $message = 'Should be deactivated'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'cache': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if (!is_array($value)) { - $message = 'Should be Array'; - $this->errors++; - } - - $this->printConf($output, $conf, 'array()', false, $message); - - $required_caches = array('query', 'result', 'metadata'); - foreach ($value as $name => $cache_type) { - $required_caches = array_diff($required_caches, array($name)); - - foreach ($cache_type as $key_cache => $value_cache) { - switch ($key_cache) { - case 'service': - if ($this->probeCacheService($output, $value_cache)) { - $server = $name === 'result'; - if ($this->recommendedCacheService($output, $value_cache, $server)) { - $work_message = 'Works !'; - } else { - $this->alerts++; - if ($server) { - $work_message = 'Cache server recommended'; - } else { - $work_message = 'Opcode cache recommended'; - } - } - } else { - $work_message = 'Failed - could not connect !'; - $this->errors++; - } - - $verification = sprintf("\t--> Verify %s : %s", $name, $work_message); - - $this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification); - $this->verifyCacheOptions($output, $value_cache); - break; - default: - $this->alerts++; - $this->printConf($output, "\t" . $key_cache, $value_cache, false, 'Not recognized'); - break; - } - if (!isset($cache_type['service'])) { - $output->writeln('Miss service for %s', $cache_type); - $this->errors++; - } - } - } - - if (count($required_caches) > 0) { - $output->writeln(sprintf('Miss required caches %s', implode(', ', $required_caches))); - $this->errors++; - } - break; - case 'debug': - $required = array_diff($required, array($conf)); - $message = 'OK'; - - if ($value !== false) { - $message = 'Should be false'; - $this->errors++; - } - - $this->printConf($output, $conf, $value, false, $message); - break; - case 'dbal': - $required = array_diff($required, array($conf)); - try { - $connexion = $this->configuration->getConnexion($value); - $this->verifyDatabaseConnexion($connexion); - $message = 'OK'; - } catch (\Exception $e) { - $message = 'Failed'; - $this->errors++; - } - $this->printConf($output, $conf, $value, false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, $conf, $value, false, 'Not recognized'); - break; - } - } - - if (count($required) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required))); - $this->errors++; - } - - return; - } - - protected function verifyCacheOptions(OutputInterface $output, $ServiceName) - { - try { - $conf = $this->configuration->getService($ServiceName); - - $Service = Builder::create($this->container, $conf); - } catch (\Exception $e) { - return false; - } - - $required_options = array(); - - switch ($Service->getType()) { - default: - break; - case 'memcache': - case 'memcached': - case 'redis': - $required_options = array('host', 'port'); - break; - } - - if ($required_options) { - foreach ($conf->get('options') as $conf => $value) { - switch ($conf) { - case 'host'; - $required_options = array_diff($required_options, array($conf)); - $message = 'OK'; - - if (!is_scalar($value)) { - $message = 'Should be scalar'; - $this->errors++; - } - - $this->printConf($output, "\t\t" . $conf, $value, false, $message); - break; - case 'port'; - $required_options = array_diff($required_options, array($conf)); - $message = 'OK'; - - if (!ctype_digit($value)) { - $message = 'Not recognized'; - $this->alerts++; - } - - $this->printConf($output, "\t\t" . $conf, $value, false, $message); - break; - default: - $this->alerts++; - $this->printConf($output, "\t\t" . $conf, $value, false, 'Not recognized'); - break; - } - } - } - - if (count($required_options) > 0) { - $output->writeln(sprintf('Miss required keys %s', implode(', ', $required_options))); - $this->errors++; - } - } - - protected function probeCacheService(OutputInterface $output, $ServiceName) - { - try { - $originalConfiguration = $this->configuration->getService($ServiceName); - - $Service = Builder::create($this->container, $originalConfiguration); - } catch (\Exception $e) { - return false; - } - - try { - $driver = $Service->getDriver(); - } catch (\Exception $e) { - return false; - } - - if ($driver->isServer()) { - switch ($Service->getType()) { - default: - return false; - break; - case 'memcache': - if (!@memcache_connect($Service->getHost(), $Service->getPort())) { - return false; - } - break; - case 'memcached': - $ret = false; - try { - $memcached = new \Memcached(); - $memcached->addServer($Service->getHost(), $Service->getPort()); - $stats = $memcached->getStats(); - - if (!isset($stats[$key]) || !$stats[$key]) { - throw new \Exception('Unable to connect to memcached server'); - } - - $ret = true; - } catch (\Exception $e) { - - } - - unset($memcached); - - return $ret; - break; - case 'redis': - $ret = false; - try { - $redis = new \Redis(); - if (@$redis->connect($Service->getHost(), $Service->getPort())) { - $ret = true; - } - } catch (\Exception $e) { - - } - unset($redis); - - return $ret; - break; - } - } - - return true; - } - - protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server) - { - try { - $originalConfiguration = $this->configuration->getService($ServiceName); - - $Service = Builder::create($this->container, $originalConfiguration); - } catch (\Exception $e) { - return false; - } - - if ($Service->getType() === 'array') { - return false; - } - - return $server === $Service->getDriver()->isServer(); - } - - private function printConf($output, $scope, $value, $scopage = false, $message = '') - { - if (is_array($value)) { - foreach ($value as $key => $val) { - if ($scopage) - $key = $scope . ":" . $key; - $this->printConf($output, $key, $val, $scopage, ''); - } - } elseif (is_bool($value)) { - if ($value === false) { - $value = 'false'; - } elseif ($value === true) { - $value = 'true'; - } - $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message)); - } elseif (!empty($value)) { - $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message)); - } - } -} diff --git a/lib/classes/module/report/activity.php b/lib/classes/module/report/activity.php index 3bddd6f6d6..476a5e81d0 100644 --- a/lib/classes/module/report/activity.php +++ b/lib/classes/module/report/activity.php @@ -625,7 +625,7 @@ class module_report_activity extends module_report $result['top_ten_poiddoc'] = array(); $result['top_ten_poidprev'] = array(); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); $params = array_merge($params, $datefilter['params']); @@ -707,7 +707,7 @@ class module_report_activity extends module_report $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $params = array_merge($params, $datefilter['params'], $collfilter['params']); $sql = " @@ -754,7 +754,7 @@ class module_report_activity extends module_report $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $params = array_merge($params, $datefilter['params'], $collfilter['params']); $sql = " @@ -795,7 +795,7 @@ class module_report_activity extends module_report $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $params = array_merge($params, $datefilter['params'], $collfilter['params']); $sql = " @@ -835,7 +835,7 @@ class module_report_activity extends module_report $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $params = array_merge($params, $datefilter['params'], $collfilter['params']); $sql = " diff --git a/lib/classes/module/report/connexion.php b/lib/classes/module/report/connexion.php index 18a10ed939..78965d2e2e 100644 --- a/lib/classes/module/report/connexion.php +++ b/lib/classes/module/report/connexion.php @@ -141,7 +141,7 @@ class module_report_connexion extends module_report $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); $params = array_merge(array( - ':site_id' => $app['phraseanet.registry']->get('GV_sit') + ':site_id' => $app['phraseanet.configuration']['main']['key'] ), $datefilter['params'], $collfilter['params'] diff --git a/lib/classes/module/report/download.php b/lib/classes/module/report/download.php index f750d0164c..73f6bf9913 100644 --- a/lib/classes/module/report/download.php +++ b/lib/classes/module/report/download.php @@ -174,7 +174,7 @@ class module_report_download extends module_report { $conn = connection::getPDOConnection($app, $sbas_id); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); $params = array_merge($params, $datefilter['params'], $collfilter['params']); @@ -210,7 +210,7 @@ class module_report_download extends module_report $databox = $app['phraseanet.appbox']->get_databox((int) $sbas_id); $conn = $databox->get_connection(); - $params = array(':site_id' => $app['phraseanet.registry']->get('GV_sit')); + $params = array(':site_id' => $app['phraseanet.configuration']['main']['key']); $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); $collfilter = module_report_sqlfilter::constructCollectionFilter($app, $list_coll_id); $params = array_merge($params, $datefilter['params'], $collfilter['params']); diff --git a/lib/classes/module/report/sqlfilter.php b/lib/classes/module/report/sqlfilter.php index eea8f4299f..798a3020a8 100644 --- a/lib/classes/module/report/sqlfilter.php +++ b/lib/classes/module/report/sqlfilter.php @@ -64,7 +64,7 @@ class module_report_sqlfilter { $finalfilter = ''; - $params = array(':log_site' => $this->app['phraseanet.registry']->get('GV_sit')); + $params = array(':log_site' => $this->app['phraseanet.configuration']['main']['key']); if ($this->filter['date']) { $finalfilter .= $this->filter['date']['sql'] . ' AND '; @@ -86,12 +86,9 @@ class module_report_sqlfilter public function getGvSitFilter() { $params = array(); - $sql = '1'; - if ($this->app['phraseanet.registry']->is_set('GV_sit')) { - $sql = 'log.site = :log_site_gv_filter'; - $params[':log_site_gv_filter'] = $this->app['phraseanet.registry']->get('GV_sit'); - } + $sql = 'log.site = :log_site_gv_filter'; + $params[':log_site_gv_filter'] = $this->app['phraseanet.configuration']['main']['key']; return array('sql' => $sql, 'params' => $params); } diff --git a/lib/classes/patch/370a9.php b/lib/classes/patch/370a9.php index 6931cfa7d9..98e7cdbb1a 100644 --- a/lib/classes/patch/370a9.php +++ b/lib/classes/patch/370a9.php @@ -10,7 +10,6 @@ */ use Alchemy\Phrasea\Application; -use Alchemy\Phrasea\Border\Checker; /** * @@ -55,92 +54,13 @@ class patch_370a9 implements patchInterface } /** - * Add new border manager service to services.yml & config.yml configuration files - * * @param base $appbox * @param Application $app */ public function apply(base $appbox, Application $app) { - $services = $app['phraseanet.configuration']->getServices(); + $app['phraseanet.configuration']->setDefault('border-manager'); - if ( ! isset($services['Border'])) { - $services['Border'] = array( - 'border_manager' => array( - 'type' => 'Border\\BorderManager', - 'options' => array( - 'enabled' => true, - 'checkers' => array( - array( - 'type' => 'Checker\\Sha256', - 'enabled' => true, - ), - array( - 'type' => 'Checker\\UUID', - 'enabled' => true, - ), - array( - 'type' => 'Checker\\Colorspace', - 'enabled' => false, - 'options' => array( - 'colorspaces' => array( - Checker\Colorspace::COLORSPACE_CMYK, - Checker\Colorspace::COLORSPACE_GRAYSCALE, - Checker\Colorspace::COLORSPACE_RGB, - ) - ), - ), - array( - 'type' => 'Checker\\Dimension', - 'enabled' => false, - 'options' => array( - 'width' => 80, - 'height' => 80, - ), - ), - array( - 'type' => 'Checker\\Extension', - 'enabled' => false, - 'options' => array( - ), - ), - array( - 'type' => 'Checker\\Filename', - 'enabled' => false, - 'options' => array( - 'sensitive' => true, - ), - ), - array( - 'type' => 'Checker\\MediaType', - 'enabled' => false, - 'options' => array( - 'mediatypes' => array( - Checker\MediaType::TYPE_AUDIO, - Checker\MediaType::TYPE_DOCUMENT, - Checker\MediaType::TYPE_FLASH, - Checker\MediaType::TYPE_IMAGE, - Checker\MediaType::TYPE_VIDEO, - ) - ), - ) - ) - ) - ) - ); - } - - $app['phraseanet.configuration']->setServices($services); - $configs = $app['phraseanet.configuration']->getConfigurations(); - - foreach (array('prod', 'dev', 'test') as $env) { - if (isset($configs[$env]) - && is_array($configs[$env]) - && ! isset($configs[$env]['border-manager'])) { - $configs[$env]['border-manager'] = 'border_manager'; - } - } - - $app['phraseanet.configuration']->setConfigurations($configs); + return true; } } diff --git a/lib/classes/patch/373.php b/lib/classes/patch/373.php index e14aae15b5..ac08cd69ea 100644 --- a/lib/classes/patch/373.php +++ b/lib/classes/patch/373.php @@ -10,7 +10,6 @@ */ use Alchemy\Phrasea\Application; -use Alchemy\Phrasea\Core\Configuration; /** * @@ -103,7 +102,8 @@ class patch_373 implements patchInterface $stmt->closeCursor(); - $app['phraseanet.configuration']->setBinaries(array('binaries' => $binaries)); + $config = $app['phraseanet.configuration']->getConfig(); + $config['binaries'] = $binaries; $sql = 'DELETE FROM registry WHERE `key` = :key'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); @@ -120,9 +120,9 @@ class patch_373 implements patchInterface $row = $stmt->fetch(\PDO::FETCH_ASSOC); $stmt->closeCursor(); - $configs = $app['phraseanet.configuration']->getConfigurations(); - $configs['key'] = $row['value']; - $app['phraseanet.configuration']->setConfigurations($configs); + $config['main']['key'] = $row['value']; + + $app['phraseanet.configuration']->setConfig($config); $sql = 'DELETE FROM registry WHERE `key` = :key'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); diff --git a/lib/classes/patch/380.php b/lib/classes/patch/380.php index 53758cc526..cf7a814aed 100644 --- a/lib/classes/patch/380.php +++ b/lib/classes/patch/380.php @@ -59,12 +59,12 @@ class patch_380 implements patchInterface */ public function apply(base $databox, Application $app) { - $connexions = $app['phraseanet.configuration']->getConnexions(); + $config = $app['phraseanet.configuration']->getConfig(); - if (isset($connexions['test_connexion'])) { - $connexions['test_connexion']['path'] = '/tmp/db.sqlite'; + if (isset($config['main']['database-test'])) { + $config['main']['database-test']['path'] = '/tmp/db.sqlite'; } - $app['phraseanet.configuration']->setConnexions($connexions); + $app['phraseanet.configuration']->setConfig($config); } } diff --git a/lib/classes/patch/3803.php b/lib/classes/patch/3803.php index 87cea0619d..7db67a1b12 100644 --- a/lib/classes/patch/3803.php +++ b/lib/classes/patch/3803.php @@ -60,58 +60,7 @@ class patch_3803 implements patchInterface */ public function apply(base $appbox, Application $app) { - $searchEngine = $app['phraseanet.registry']->get('GV_sphinx') ? 'sphinxsearch' : 'phrasea'; - - $confs = $app['phraseanet.configuration']->getConfigurations(); - - foreach ($confs as $env => $conf) { - - if (in_array($env, array('environment', 'key'))) { - continue; - } - - if (!isset($conf['search-engine'])) { - $confs[$env]['search-engine'] = $searchEngine; - } - } - - $app['phraseanet.configuration']->setConfigurations($confs); - - $services = $app['phraseanet.configuration']->getServices(); - - if (!isset($services['SearchEngine'])) { - $app['phraseanet.configuration']->resetServices('SearchEngine'); - } - - if (!$app['phraseanet.registry']->get('GV_sphinx')) { - - $phraseaConfiguration = $app['phraseanet.SE']->getConfigurationPanel()->getConfiguration(); - - if ($app['phraseanet.registry']->get('GV_phrasea_sort')) { - $phraseaConfiguration['default_sort'] = $app['phraseanet.registry']->get('GV_phrasea_sort'); - } - - $app['phraseanet.SE']->getConfigurationPanel()->saveConfiguration($phraseaConfiguration); - - } else { - - $sphinxConfiguration = $app['phraseanet.SE']->getConfigurationPanel()->getConfiguration(); - - if ($app['phraseanet.registry']->get('GV_sphinx_rt_port')) { - $sphinxConfiguration['rt_port'] = $app['phraseanet.registry']->get('GV_sphinx_rt_port'); - } - if ($app['phraseanet.registry']->get('GV_sphinx_rt_host')) { - $sphinxConfiguration['rt_host'] = $app['phraseanet.registry']->get('GV_sphinx_rt_host'); - } - if ($app['phraseanet.registry']->get('GV_sphinx_port')) { - $sphinxConfiguration['port'] = $app['phraseanet.registry']->get('GV_sphinx_port'); - } - if ($app['phraseanet.registry']->get('GV_sphinx_host')) { - $sphinxConfiguration['host'] = $app['phraseanet.registry']->get('GV_sphinx_host'); - } - - $app['phraseanet.SE']->getConfigurationPanel()->saveConfiguration($sphinxConfiguration); - } + $app['phraseanet.configuration']->setDefault('main', 'search-engine'); return true; } diff --git a/lib/classes/patch/3804.php b/lib/classes/patch/3804.php index 3ada9ceb2a..8e4301715e 100644 --- a/lib/classes/patch/3804.php +++ b/lib/classes/patch/3804.php @@ -54,31 +54,8 @@ class patch_3804 implements patchInterface */ public function apply(base $appbox, Application $app) { - try { - $confs = $app['phraseanet.configuration']->getConfigurations(); + $app['phraseanet.configuration']->setDefault('main', 'task-manager'); - foreach ($confs as $env => $conf) { - if (in_array($env, array('environment', 'key'))) { - continue; - } - if (!isset($conf['task-manager'])) { - $confs[$env]['task-manager'] = 'task_manager'; - } - } - - $app['phraseanet.configuration']->setConfigurations($confs); - - $services = $app['phraseanet.configuration']->getServices(); - - if (!isset($services['TaskManager'])) { - $app['phraseanet.configuration']->resetServices('TaskManager'); - } - - return true; - } catch (\Exception $e) { - throw $e; - } - - return false; + return true; } } diff --git a/lib/classes/patch/3806.php b/lib/classes/patch/3806.php index 604879ee50..e505de518e 100644 --- a/lib/classes/patch/3806.php +++ b/lib/classes/patch/3806.php @@ -10,7 +10,6 @@ */ use Alchemy\Phrasea\Application; -use Symfony\Component\Yaml\Yaml; class patch_3806 implements patchInterface { @@ -49,29 +48,7 @@ class patch_3806 implements patchInterface */ public function apply(base $appbox, Application $app) { - $parser = new Yaml(); - $data = $parser->parse(file_get_contents(__DIR__ . '/../../conf.d/config.yml')); - - $fields = $data['prod']['registration-fields']; - $authentication = $data['prod']['authentication']; - - $confs = $app['phraseanet.configuration']->getConfigurations(); - - foreach ($confs as $env => $conf) { - - if (in_array($env, array('environment', 'key'))) { - continue; - } - - if (!isset($conf['registration-fields'])) { - $confs[$env]['registration-fields'] = $fields; - } - - if (!isset($conf['authentication'])) { - $confs[$env]['authentication'] = $authentication; - } - } - - $app['phraseanet.configuration']->setConfigurations($confs); + $app['phraseanet.configuration']->setDefault('registration-fields'); + $app['phraseanet.configuration']->setDefault('authentication'); } } diff --git a/lib/classes/patch/3807.php b/lib/classes/patch/3807.php new file mode 100644 index 0000000000..a40fe79dfa --- /dev/null +++ b/lib/classes/patch/3807.php @@ -0,0 +1,147 @@ +release; + } + + /** + * {@inheritdoc} + */ + public function require_all_upgrades() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function concern() + { + return $this->concern; + } + + /** + * {@inheritdoc} + */ + public function apply(base $appbox, Application $app) + { + $this->yaml = new Yaml(); + + $this->connexionsYaml = $app['root.path'] . '/config/connexions.yml'; + $this->binariesYaml = $app['root.path'] . '/config/binaries.yml'; + $this->servicesYaml = $app['root.path'] . '/config/services.yml'; + $this->configYaml = $app['root.path'] . '/config/config.yml'; + + $this->migrate($app); + + return true; + } + + private function migrate($app) + { + $conf = $app['phraseanet.configuration']->getConfig(); + + $this->migrateConnexions($conf); + $this->migrateConfigAndServices($conf); + $this->migrateBinaries($conf); + + $app['phraseanet.configuration']->setConfig($conf); + + foreach (array( + $this->configYaml, + $this->connexionsYaml, + $this->binariesYaml, + $this->servicesYaml + ) as $file) { + if (is_file($file)) { + rename($file, $file.'.bkp'); + } + } + } + + private function migrateBinaries(array &$conf) + { + if (is_file($this->binariesYaml)) { + $binaries = $this->yaml->parse($this->binariesYaml); + foreach ($binaries['binaries'] as $key => $value) { + $conf['binaries'][$key] = $value; + } + } + } + + private function migrateConfigAndServices(array &$conf) + { + $opcodeCacheService = $cacheService = null; + + if (is_file($this->configYaml)) { + $data = $this->yaml->parse($this->configYaml); + $conf['main']['key'] = $data['key']; + $env = $data['environment']; + if (isset($data[$env])) { + $conf['main']['servername'] = $data[$env]['phraseanet']['servername']; + $conf['main']['maintenance'] = $data[$env]['phraseanet']['maintenance']; + $opcodeCacheService = $data[$env]['opcodecache']; + $cacheService = $data[$env]['cache']; + } + } + + if (is_file($this->servicesYaml)) { + $services = $this->yaml->parse($this->servicesYaml); + if (null !== $opcodeCacheService) { + $conf['main']['opcodecache']['type'] = str_replace('Cache\\', '', $services['Cache'][$opcodeCacheService]['type']); + if (isset($services['Cache'][$opcodeCacheService]['options'])) { + $conf['main']['opcodecache']['options'] = $services['Cache'][$opcodeCacheService]['options']; + } else { + $conf['main']['opcodecache']['options'] = array(); + } + } + if (null !== $cacheService) { + $conf['main']['cache']['type'] = str_replace('Cache\\', '', $services['Cache'][$cacheService]['type']); + if (isset($services['Cache'][$cacheService]['options'])) { + $conf['main']['cache']['options'] = $services['Cache'][$cacheService]['options']; + } else { + $conf['main']['cache']['options'] = array(); + } + } + $conf['border-manager'] = $services['Border']['border_manager']['options']; + } + } + + private function migrateConnexions(array &$conf) + { + $data = $this->yaml->parse($this->connexionsYaml); + + $conf['main']['database'] = $data['main_connexion']; + $conf['main']['database-test'] = $data['test_connexion']; + } +} diff --git a/lib/classes/record/adapter.php b/lib/classes/record/adapter.php index 975a460d02..b4b09bc901 100644 --- a/lib/classes/record/adapter.php +++ b/lib/classes/record/adapter.php @@ -1945,7 +1945,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface ORDER BY g.ord ASC, dateadd ASC, record_id ASC'; $params = array( - ':GV_site' => $this->app['phraseanet.registry']->get('GV_sit'), + ':GV_site' => $this->app['phraseanet.configuration']['main']['key'], ':usr_id' => $this->app['authentication']->getUser()->get_id(), ':record_id' => $this->get_record_id(), ); @@ -1996,7 +1996,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface WHERE rid_child = :record_id'; $params = array( - ':GV_site' => $this->app['phraseanet.registry']->get('GV_sit') + ':GV_site' => $this->app['phraseanet.configuration']['main']['key'] , ':usr_id' => $this->app['authentication']->getUser()->get_id() , ':record_id' => $this->get_record_id() ); diff --git a/lib/classes/record/preview.php b/lib/classes/record/preview.php index 99f7121a7b..8e2f106183 100644 --- a/lib/classes/record/preview.php +++ b/lib/classes/record/preview.php @@ -336,7 +336,7 @@ class record_preview extends record_adapter if (! $report) { $sql .= ' AND ((l.usrid = :usr_id AND l.site= :site) OR action="add")'; $params[':usr_id'] = $this->app['authentication']->getUser()->get_id(); - $params[':site'] = $this->app['phraseanet.registry']->get('GV_sit'); + $params[':site'] = $this->app['phraseanet.configuration']['main']['key']; } $sql .= 'ORDER BY d.date, usrid DESC'; @@ -441,7 +441,7 @@ class record_preview extends record_adapter $stmt->execute( array( ':record_id' => $this->get_record_id(), - ':site' => $this->app['phraseanet.registry']->get('GV_sit') + ':site' => $this->app['phraseanet.configuration']['main']['key'] ) ); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -604,7 +604,7 @@ class record_preview extends record_adapter $stmt->execute( array( ':record_id' => $this->get_record_id(), - ':site' => $this->app['phraseanet.registry']->get('GV_sit') + ':site' => $this->app['phraseanet.configuration']['main']['key'] ) ); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); diff --git a/lib/classes/registry.php b/lib/classes/registry.php index 937b6a9b7c..2117fc2550 100644 --- a/lib/classes/registry.php +++ b/lib/classes/registry.php @@ -48,19 +48,18 @@ class registry implements registryInterface $this->cache->save('GV_RootPath', dirname(dirname(__DIR__)) . '/'); if ($app['phraseanet.configuration-tester']->isInstalled()) { - $this->cache->save('GV_ServerName', $app['phraseanet.configuration']->getPhraseanet()->get('servername')); - $this->cache->save('GV_debug', $app['phraseanet.configuration']->isDebug()); - $this->cache->save('GV_maintenance', $app['phraseanet.configuration']->isMaintained()); + $this->cache->save('GV_ServerName', $app['phraseanet.configuration']['main']['servername']); + $this->cache->save('GV_debug', $app['debug']); + $this->cache->save('GV_maintenance', $app['phraseanet.configuration']['main']['maintenance']); - $config = $app['phraseanet.configuration']->getConfigurations(); + $config = $app['phraseanet.configuration']->getConfig(); - if (isset($config['key'])) { - $this->cache->save('GV_sit', $config['key']); + if (isset($config['main']['key'])) { + $this->cache->save('GV_sit', $config['main']['key']); } - $binaries = $app['phraseanet.configuration']->getBinaries(); - if (isset($binaries['binaries'])) { - foreach ($binaries['binaries'] as $name => $path) { + if (isset($config['binaries'])) { + foreach ($config['binaries'] as $name => $path) { if ($path) { $this->cache->save($name, $path); } diff --git a/lib/conf.d/config.yml b/lib/conf.d/config.yml deleted file mode 100644 index 859d460474..0000000000 --- a/lib/conf.d/config.yml +++ /dev/null @@ -1,219 +0,0 @@ -#Here's the main configuration file which is loaded when phraseanet bootstraps - -#Declare which environment will be used by the application - -environment : prod -key : null - -#Declare all your environment configurations - -################# -# DEVELOPPEMENT # -################# -dev: - #Phraseanet refers to phraseanet app specific configuration - phraseanet: - servername: 'http://sub.domain.tld/' - maintenance: false - debug: true - display_errors: true - - #Assign your phraseanet application connection - #Connections are defined in connexions.yml configuration file - database: main_connexion - api-timers: true - - #Assign your template engine service & ORM service - #Services are defined in service.yml configuration file - template_engine: twig_debug - orm: doctrine_dev - cache: array_cache - opcodecache: array_cache - border-manager: border_manager - search-engine: phrasea - task-manager: task_manager - authentication: - auto-create: - enabled: false - templates: [] - captcha: - enabled: true - trials-before-failure: 9 - providers: - facebook: - enabled: false - options: - app-id: '' - secret: '' - twitter: - enabled: false - options: - consumer-key: '' - consumer-secret: '' - google-plus: - enabled: false - options: - client-id: '' - client-secret: '' - github: - enabled: false - options: - client-id: '' - client-secret: '' - viadeo: - enabled: false - options: - client-id: '' - client-secret: '' - linkedin: - enabled: false - options: - client-id: '' - client-secret: '' - registration-fields: - - - name: company - required: true - - - name: firstname - required: true - - - name: geonameid - required: true - -############## -# PRODUCTION # -############## -prod: - phraseanet: - servername: 'http://sub.domain.tld/' - maintenance: false - debug: false - display_errors: false - database: main_connexion - api-timers: false - - template_engine: twig - orm: doctrine_prod - cache: array_cache - opcodecache: array_cache - border-manager: border_manager - search-engine: phrasea - task-manager: task_manager - authentication: - auto-create: - enabled: false - templates: [] - captcha: - enabled: true - trials-before-failure: 9 - providers: - facebook: - enabled: false - options: - app-id: '' - secret: '' - twitter: - enabled: false - options: - consumer-key: '' - consumer-secret: '' - google-plus: - enabled: false - options: - client-id: '' - client-secret: '' - github: - enabled: false - options: - client-id: '' - client-secret: '' - viadeo: - enabled: false - options: - client-id: '' - client-secret: '' - linkedin: - enabled: false - options: - client-id: '' - client-secret: '' - registration-fields: - - - name: company - required: true - - - name: firstname - required: true - - - name: geonameid - required: true - -############## -# TEST # -############## -test: - phraseanet: - servername: 'http://sub.domain.tld/' - maintenance: false - debug: true - display_errors: true - database: main_connexion - api-timers: false - - template_engine: twig_debug - orm: doctrine_test - cache: array_cache - opcodecache: array_cache - border-manager: border_manager - search-engine: phrasea - task-manager: task_manager - authentication: - auto-create: - enabled: false - templates: [] - captcha: - enabled: true - trials-before-failure: 9 - providers: - facebook: - enabled: false - options: - app-id: '' - secret: '' - twitter: - enabled: false - options: - consumer-key: '' - consumer-secret: '' - google-plus: - enabled: false - options: - client-id: '' - client-secret: '' - github: - enabled: false - options: - client-id: '' - client-secret: '' - viadeo: - enabled: false - options: - client-id: '' - client-secret: '' - linkedin: - enabled: false - options: - client-id: '' - client-secret: '' - registration-fields: - - - name: company - required: true - - - name: firstname - required: true - - - name: geonameid - required: true - diff --git a/lib/conf.d/configuration.yml b/lib/conf.d/configuration.yml new file mode 100644 index 0000000000..ceb3177653 --- /dev/null +++ b/lib/conf.d/configuration.yml @@ -0,0 +1,113 @@ +main: + servername: 'http://local.phrasea/' + maintenance: false + database: + host: 127.0.0.1 + port: '3306' + user: root + password: '' + dbname: ab_test + driver: pdo_mysql + charset: UTF8 + database-test: + driver: pdo_sqlite + path: '/tmp/db.sqlite' + charset: UTF8 + api-timers: true + cache: + type: MemcacheCache + options: + host: localhost + port: 11211 + opcodecache: + type: ArrayCache + options: [] + search-engine: + type: Alchemy\Phrasea\SearchEngine\Phrasea\PhraseaEngine + options: [] + task-manager: + options: null +binaries: [] +border-manager: + enabled: true + checkers: + - + type: Checker\Sha256 + enabled: true + - + type: Checker\UUID + enabled: true + - + type: Checker\Colorspace + enabled: false + options: + colorspaces: [cmyk, grayscale, rgb] + - + type: Checker\Dimension + enabled: false + options: + width: 80 + height: 160 + - + type: Checker\Extension + enabled: false + options: + extensions: [jpg, jpeg, bmp, tif, gif, png, pdf, doc, odt, mpg, mpeg, mov, avi, xls, flv, mp3, mp2] + - + type: Checker\Filename + enabled: false + options: + sensitive: true + - + type: Checker\MediaType + enabled: false + options: + mediatypes: [Audio, Document, Flash, Image, Video] +authentication: + auto-create: + enabled: false + templates: { } + captcha: + enabled: true + trials-before-failure: 9 + providers: + facebook: + enabled: false + options: + app-id: '' + secret: '' + twitter: + enabled: false + options: + consumer-key: '' + consumer-secret: '' + google-plus: + enabled: false + options: + client-id: '' + client-secret: '' + github: + enabled: false + options: + client-id: '' + client-secret: '' + viadeo: + enabled: false + options: + client-id: '' + client-secret: '' + linkedin: + enabled: false + options: + client-id: '' + client-secret: '' +registration-fields: + - + name: company + required: true + - + name: firstname + required: true + - + name: geonameid + required: true diff --git a/lib/conf.d/connexions.yml b/lib/conf.d/connexions.yml deleted file mode 100644 index 138b4c3ef9..0000000000 --- a/lib/conf.d/connexions.yml +++ /dev/null @@ -1,19 +0,0 @@ -#Here you can define many connexions configurations -#Please refer to Doctrine documentation abstraction layer for database connection configuration -#DBAL connection : http://www.doctrine-project.org/docs/dbal/2.1/en/reference/configuration.html - -#Defines a connexion to MYSQL database named main_connexion -main_connexion: - host: - port: - user: - password: - dbname: - driver: pdo_mysql - charset: UTF8 - -#Defines a connexion to a SQLite database named test_connexion -test_connexion: - driver: pdo_sqlite - path: '/tmp/db.sqlite' - charset: UTF8 diff --git a/lib/conf.d/services.yml b/lib/conf.d/services.yml deleted file mode 100644 index 9a15a5541d..0000000000 --- a/lib/conf.d/services.yml +++ /dev/null @@ -1,215 +0,0 @@ -#base service file -Orm: - #Doctrine developement service options - #Service name - doctrine_dev: - type: Orm\Doctrine - options: - #Set automatically propers values for debug - #Query & result caches are setted to Array cache - #Auto-generating Proxy Classes is setted to false - debug: true - #Assign a connexion from connexions.yml to the DataBase Abstraction Layer - dbal: main_connexion - #Available cache driver [memcached, apc, array] - #Query cache : is used to cache the transformation of a DQL query to its SQL counterpart - #Result cache : is used to cache the results of your queries - #Metadata cache : is used to cache entity class metadatas - #If No cache is provided all cache are setted to default_cache which is an array cache type - cache: - query: - service: Cache\array_cache - result: - service: Cache\array_cache - metadata: - service: Cache\array_cache - # Assign a service to log doctrine queries - log: - service: Log\query_logger - - # Doctrine test service options - doctrine_test: - type: Orm\Doctrine - options: - debug: true - #Doctrine use a different connection configuration base to run tests - dbal: test_connexion - cache: - query: - service: Cache\array_cache - result: - service: Cache\array_cache - metadata: - service: Cache\array_cache - log: - service: Log\query_logger - - # Doctrine production service options - doctrine_prod: - type: Orm\Doctrine - options: - debug: false - dbal: main_connexion - cache: - query: - service: Cache\array_cache - result: - service: Cache\array_cache - metadata: - service: Cache\array_cache - -TemplateEngine: - #Define a template engine service - #Only Twig is avalaible as a template engine service - #see http://twig.sensiolabs.org/ - - #Define the service name first - twig: - #Template engine type - type: TemplateEngine\Twig - options: - #When set to true, the generated templates have a __toString() method that you can use to display the generated nodes - debug: false - #The charset used by the templates - charset: utf-8 - #Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) - #And replace them with a null value. When set to true, Twig throws an exception instead (default to false) - strict_variables: false - autoescape: true - #Optimize the node tree before compilation - optimizer: true - - twig_debug: - type: TemplateEngine\Twig - options: - debug: true - charset: utf-8 - strict_variables: true - autoescape: true - optimizer: true - - -Log: - # Define a Log service - # This one is defined to handle the logs of doctrine queries - # Only Monolog is available as a logger service - # Please Notice that for doctrine ONLY a echo logger service is available, see below - # Monolog logger use the PHP Monolog library to handle logs using differents handlers - query_logger: - type: Log\Doctrine\Monolog - options: - #You can precise the output format - #This option is only available when log are used to log doctrine queries - #Available output [vdump, json, yaml] - # vdump : output logs in a var_dump formatted style - # json : output logs in json - # yml : output logs yml - output: json - #Name used for the Monolog channel - channel: query-logger - #Define how the logs will be handled - #Avalaibale Handler are [rotate, stream] - #Rotate handler is used to stores logs to files that are rotated every day - #And a limited number of files are kept by defining the max_day value - #Stream handler is used to stores logs in a single local file - handler: rotate - max_day: 2 - #Name of the file where logs are written - filename: doctrine-query.log - - # Define a phpecho log service for Doctrine - # phpecho logger logs doctrine queries to the standard output using echo/var_dump - # Notice that phpecho logger do not have options - sql_logger: - type: Log\Doctrine\Phpecho - -Cache: - #Define cache services - #There are Four different cache type available [array, xcache, apc, memcache] - #Only a memcache service can take option to define port & host for the memcache server - array_cache: - type: Cache\ArrayCache - - memcache_cache: - type: Cache\MemcacheCache - options: - host: localhost - port: 11211 - - apc_cache: - type: Cache\ApcCache - - xcache_cache: - type: Cache\XcacheCache - - wincache_cache: - type: Cache\WinCacheCache - -Border: - #Define Border service - #The border service handles checks validation constraints against incoming files - border_manager: - type: Border\BorderManager - options: - #Enable validation on incoming files - enabled: true - checkers: - #Check for duplicated file based on their sha256 check sum - - - type: Checker\Sha256 - enabled: true - #Check for duplicated file based on their UUID - - - type: Checker\UUID - enabled: true - #Check colorspace (if applicable) - - - type: Checker\Colorspace - enabled: false - options: - colorspaces: [cmyk, grayscale, rgb] - #Check file dimension (if applicable) - - - type: Checker\Dimension - enabled: false - options: - width: 80 - height: 160 - #Check file extension - #set to false to enable all file extensions - - - type: Checker\Extension - enabled: false - options: - extensions: [jpg, jpeg, bmp, tif, gif, png, pdf, doc, odt, mpg, mpeg, mov, avi, xls, flv, mp3, mp2] - #Check filename - - - type: Checker\Filename - enabled: false - options: - sensitive: true - #Check media type - #Set to false to enable all mediatype - - - type: Checker\MediaType - enabled: false - options: - mediatypes: [Audio, Document, Flash, Image, Video] -SearchEngine: - phrasea: - type: SearchEngine\PhraseaEngine - sphinxsearch: - type: SearchEngine\SphinxSearch - options: - host: localhost - port: 9306 - rt_host: localhost - rt_port: 9308 -TaskManager: - task_manager: - type: TaskManager\TaskManager - options: - # set the threshold for sending task logs to syslog or by mail - # values : task_abstract::[LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERROR | LOG_CRITICAL | LOG_ALERT] - #syslog_level: task_abstract::LOG_ERROR - #maillog_level: task_abstract::LOG_ERROR diff --git a/tests/Alchemy/Tests/Phrasea/ApplicationTest.php b/tests/Alchemy/Tests/Phrasea/ApplicationTest.php index efa71ccc58..02a6bb9c7b 100644 --- a/tests/Alchemy/Tests/Phrasea/ApplicationTest.php +++ b/tests/Alchemy/Tests/Phrasea/ApplicationTest.php @@ -276,6 +276,16 @@ class ApplicationTest extends \PhraseanetPHPUnitAbstract $this->assertNull($app->getUnlockAccountData()); } + public function testRootPath() + { + $app = new Application('test'); + + $this->assertFileExists($app['root.path'].'/LICENSE'); + $this->assertFileExists($app['root.path'].'/README.md'); + $this->assertFileExists($app['root.path'].'/lib'); + $this->assertFileExists($app['root.path'].'/www'); + } + private function getAppThatReturnLocale() { $app = new Application('test'); diff --git a/tests/Alchemy/Tests/Phrasea/Command/Compile/ConfigurationTest.php b/tests/Alchemy/Tests/Phrasea/Command/Compile/ConfigurationTest.php new file mode 100644 index 0000000000..132348eab4 --- /dev/null +++ b/tests/Alchemy/Tests/Phrasea/Command/Compile/ConfigurationTest.php @@ -0,0 +1,23 @@ +setContainer(self::$DI['app']); + + self::$DI['app']['phraseanet.configuration'] = $this->getMock('Alchemy\Phrasea\Core\Configuration\ConfigurationInterface'); + self::$DI['app']['phraseanet.configuration']->expects($this->once()) + ->method('compileAndWrite'); + + $input = $this->getMock('Symfony\Component\Console\Input\InputInterface'); + $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); + + $command->execute($input, $output); + } +} diff --git a/tests/Alchemy/Tests/Phrasea/Core/Configuration/CompilerTest.php b/tests/Alchemy/Tests/Phrasea/Core/Configuration/CompilerTest.php index d937845ea2..fc534fbb98 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Configuration/CompilerTest.php +++ b/tests/Alchemy/Tests/Phrasea/Core/Configuration/CompilerTest.php @@ -51,4 +51,3 @@ class CompilerTest extends \PHPUnit_Framework_TestCase ); } } - diff --git a/tests/Alchemy/Tests/Phrasea/Core/Configuration/ConfigurationTest.php b/tests/Alchemy/Tests/Phrasea/Core/Configuration/ConfigurationTest.php index 44f2db492b..ef98dd1ca3 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Configuration/ConfigurationTest.php +++ b/tests/Alchemy/Tests/Phrasea/Core/Configuration/ConfigurationTest.php @@ -15,7 +15,6 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase parent::setUp(); $this->compiled = __DIR__ . '/Fixtures/configuration-compiled.php'; $this->clean(); - copy(__DIR__ . '/..' . Configuration::CONFIG_REF, __DIR__ . '/Fixtures/configuration.yml'); } public function tearDown() @@ -26,6 +25,7 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase private function clean() { + copy(__DIR__ . '/..' . Configuration::CONFIG_REF, __DIR__ . '/Fixtures/configuration.yml'); if (is_file($this->compiled)) { unlink($this->compiled); } @@ -313,4 +313,24 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase $this->assertArrayHasKey('path', $data); $this->assertArrayHasKey('charset', $data); } + + public function testCompileAndWrite() + { + $configFile = __DIR__ . '/Fixtures/configuration.yml'; + $compiled = $this->compiled; + + $yaml = new Yaml(); + $compiler = new Compiler(); + + $conf = new Configuration($yaml, $compiler, $configFile, $compiled, false); + // triggers initialization + $this->assertFalse(isset($conf['bim'])); + + file_put_contents($configFile, "\nbim: bam\n", FILE_APPEND); + $this->assertFalse(isset($conf['bim'])); + + $conf->compileAndWrite(); + $this->assertTrue(isset($conf['bim'])); + $this->assertEquals('bam', $conf['bim']); + } } diff --git a/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration-setup.yml b/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration-setup.yml index a2fc7a07b3..ceb3177653 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration-setup.yml +++ b/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration-setup.yml @@ -110,4 +110,4 @@ registration-fields: required: true - name: geonameid - required: true \ No newline at end of file + required: true diff --git a/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration.yml b/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration.yml index a2fc7a07b3..ceb3177653 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration.yml +++ b/tests/Alchemy/Tests/Phrasea/Core/Configuration/Fixtures/configuration.yml @@ -110,4 +110,4 @@ registration-fields: required: true - name: geonameid - required: true \ No newline at end of file + required: true diff --git a/tests/Alchemy/Tests/Phrasea/Core/Provider/AuthenticationManagerServiceProviderTest.php b/tests/Alchemy/Tests/Phrasea/Core/Provider/AuthenticationManagerServiceProviderTest.php index 140493f0b4..fad55d5360 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Provider/AuthenticationManagerServiceProviderTest.php +++ b/tests/Alchemy/Tests/Phrasea/Core/Provider/AuthenticationManagerServiceProviderTest.php @@ -82,6 +82,7 @@ class AuthenticationManagerServiceProvidertest extends ServiceProviderTestCase public function testFailureManagerAttemptsConfiguration() { $app = new Application(); + $app['root.path'] = __DIR__ . '/../../../../../../'; $app->register(new TokensServiceProvider()); $app->register(new AuthenticationManagerServiceProvider()); $app->register(new ConfigurationServiceProvider()); @@ -119,6 +120,7 @@ class AuthenticationManagerServiceProvidertest extends ServiceProviderTestCase public function testAuthNativeWithCaptchaEnabled() { $app = new Application(); + $app['root.path'] = __DIR__ . '/../../../../../../'; $app->register(new AuthenticationManagerServiceProvider()); $app->register(new ConfigurationServiceProvider()); $app['phraseanet.registry'] = $this->getMockBuilder('registry') @@ -156,6 +158,7 @@ class AuthenticationManagerServiceProvidertest extends ServiceProviderTestCase public function testAuthNativeWithCaptchaDisabled() { $app = new Application(); + $app['root.path'] = __DIR__ . '/../../../../../../'; $app->register(new AuthenticationManagerServiceProvider()); $app->register(new ConfigurationServiceProvider()); $app['phraseanet.registry'] = $this->getMockBuilder('registry') diff --git a/tests/Alchemy/Tests/Phrasea/Core/Provider/BorderManagerServiceProviderTest.php b/tests/Alchemy/Tests/Phrasea/Core/Provider/BorderManagerServiceProviderTest.php index b12e06e370..bf2d6e94fd 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Provider/BorderManagerServiceProviderTest.php +++ b/tests/Alchemy/Tests/Phrasea/Core/Provider/BorderManagerServiceProviderTest.php @@ -10,7 +10,11 @@ class BorderManagerServiceProvidertest extends ServiceProviderTestCase public function provideServiceDescription() { return array( - array('Alchemy\Phrasea\Core\Provider\BorderManagerServiceProvider', 'border-manager', 'Alchemy\\Phrasea\\Border\\Manager'), + array( + 'Alchemy\Phrasea\Core\Provider\BorderManagerServiceProvider', + 'border-manager', + 'Alchemy\\Phrasea\\Border\\Manager' + ), ); } } diff --git a/tests/Alchemy/Tests/Phrasea/Core/Provider/CacheServiceProviderTest.php b/tests/Alchemy/Tests/Phrasea/Core/Provider/CacheServiceProviderTest.php index ecc2799ca4..ebc16fcc8d 100644 --- a/tests/Alchemy/Tests/Phrasea/Core/Provider/CacheServiceProviderTest.php +++ b/tests/Alchemy/Tests/Phrasea/Core/Provider/CacheServiceProviderTest.php @@ -10,9 +10,21 @@ class CacheServiceProvidertest extends ServiceProviderTestCase public function provideServiceDescription() { return array( - array('Alchemy\Phrasea\Core\Provider\CacheServiceProvider', 'cache', 'Doctrine\\Common\\Cache\\Cache'), - array('Alchemy\Phrasea\Core\Provider\CacheServiceProvider', 'opcode-cache', 'Doctrine\\Common\\Cache\\Cache'), - array('Alchemy\Phrasea\Core\Provider\CacheServiceProvider', 'phraseanet.cache-service', 'Alchemy\\Phrasea\\Cache\\Manager'), + array( + 'Alchemy\Phrasea\Core\Provider\CacheServiceProvider', + 'cache', + 'Doctrine\\Common\\Cache\\Cache' + ), + array( + 'Alchemy\Phrasea\Core\Provider\CacheServiceProvider', + 'opcode-cache', + 'Doctrine\\Common\\Cache\\Cache' + ), + array( + 'Alchemy\Phrasea\Core\Provider\CacheServiceProvider', + 'phraseanet.cache-service', + 'Alchemy\\Phrasea\\Cache\\Manager' + ), ); } } diff --git a/tests/classes/patch/3807Test.php b/tests/classes/patch/3807Test.php index d0803acb98..dea681d841 100644 --- a/tests/classes/patch/3807Test.php +++ b/tests/classes/patch/3807Test.php @@ -269,4 +269,4 @@ class patch_3807Test extends PHPUnit_Framework_TestCase ), ); } -} \ No newline at end of file +} diff --git a/tests/classes/patch/fixtures-3807/config/binaries.yml b/tests/classes/patch/fixtures-3807/config/binaries.yml index 9ec01c3124..66c151d39f 100644 --- a/tests/classes/patch/fixtures-3807/config/binaries.yml +++ b/tests/classes/patch/fixtures-3807/config/binaries.yml @@ -1,2 +1,2 @@ binaries: - test_binary: /path/to/test/binary/file \ No newline at end of file + test_binary: /path/to/test/binary/file