Remove phraseanet services, update configuration

This commit is contained in:
Romain Neutron
2013-06-11 11:57:43 +02:00
parent 8ecc97e94e
commit 32c2d6154a
99 changed files with 1545 additions and 5049 deletions

View File

@@ -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.

View File

@@ -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 :

View File

@@ -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'));

View File

@@ -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

View File

@@ -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: ''

View File

@@ -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

View File

@@ -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

View File

@@ -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: <HOSTNAME>
port: <PORT>
user: <USERNAME>
password: <PASSWORD>
dbname: <DATABASE_NAME>
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

View File

@@ -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

View File

@@ -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) {

View File

@@ -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

View File

@@ -0,0 +1,142 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Cache;
use Alchemy\Phrasea\Cache\ApcCache;
use Alchemy\Phrasea\Cache\ArrayCache;
use Alchemy\Phrasea\Cache\Cache;
use Alchemy\Phrasea\Cache\MemcacheCache;
use Alchemy\Phrasea\Cache\RedisCache;
use Alchemy\Phrasea\Cache\WinCacheCache;
use Alchemy\Phrasea\Cache\XcacheCache;
use Alchemy\Phrasea\Exception\RuntimeException;
class Factory
{
/**
* @param type $name
* @param type $options
*
* @return Cache
*
* @throws RuntimeException
*/
public function create($name, $options)
{
switch (strtolower($name)) {
case 'apc':
case 'apccache':
$cache = $this->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();
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Command\Compile;
use Alchemy\Phrasea\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Configuration extends Command
{
public function __construct()
{
parent::__construct('compile:configuration');
}
protected function doExecute(InputInterface $input, OutputInterface $output)
{
$this->container['phraseanet.configuration']->compileAndWrite();
return 0;
}
}

View File

@@ -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);

View File

@@ -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) {
}

View File

@@ -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']);

View File

@@ -1,346 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core;
use Alchemy\Phrasea\Core\Configuration\ApplicationSpecification;
use Alchemy\Phrasea\Core\Configuration\SpecificationInterface;
use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/**
* Handle configuration file mechanism of phraseanet
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Configuration
{
const KEYWORD_ENV = 'environment';
/**
* The finale configuration values as an array
* @var ParameterBag\ParameterBag
*/
protected $configuration;
protected $specifications;
/**
* Return the current environnement
* @var string
*/
private $environment;
/**
*
* @param ApplicationSpecification $specifications
* @param type $environment
* @return Configuration
*/
public static function build($specifications = null, $environment = null)
{
if (! $specifications) {
$specifications = new ApplicationSpecification();
}
return new self($specifications, $environment);
}
/**
*
* @param SpecificationInterface $specifications
* @param type $environment
* @return Configuration
*/
public function __construct(SpecificationInterface $specifications, $environment = null)
{
$this->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;
}
}

View File

@@ -1,207 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\Yaml\Yaml;
class ApplicationSpecification implements SpecificationInterface
{
protected $parser;
public function __construct()
{
$this->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);
}
}

View File

@@ -0,0 +1,87 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
class Compiler
{
private $line;
public function __construct($line = PHP_EOL)
{
$this->line = $line;
}
/**
* Compiles data to PHP code
*
* @param array $data
*
* @return string
*/
public function compile(array $data)
{
return '<?php' . $this->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);
}
}

View File

@@ -0,0 +1,243 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Symfony\Component\Yaml\Yaml;
class Configuration implements ConfigurationInterface
{
const CONFIG_REF = '/../../../../../lib/conf.d/configuration.yml';
private $parser;
private $compiler;
private $config;
private $compiled;
private $autoReload;
public function __construct(Yaml $yaml, Compiler $compiler, $config, $compiled, $autoReload)
{
$this->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);
}
}
}

View File

@@ -0,0 +1,66 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
interface ConfigurationInterface extends \ArrayAccess
{
/**
* Initialize configuration file in setup.
*
* Creates the configuration, compiles it.
*
* @return ConfigurationInterface
*/
public function initialize();
/**
* Deletes the current configuration.
*
* @return ConfigurationInterface
*/
public function delete();
/**
* Returns true if a configuration exists.
*
* @return Boolean
*/
public function isSetup();
/**
* Reset a configuration key to the default one.
*
* @return ConfigurationInterface
*/
public function setDefault($name);
/**
* Gets the configuration values as array
*
* @return array
*/
public function getConfig();
/**
* Sets the configuration
*
* @param array $config
*
* @return ConfigurationInterface
*/
public function setConfig(array $config);
/**
* Load YAML configuration, compiles and writes.
*/
public function compileAndWrite();
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Configuration;
/**
* A interface to precise some specific configuration file mechanism
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
interface SpecificationInterface
{
public function setConfigurations($configurations);
public function setConnexions($connexions);
public function setServices($services);
public function resetServices($name = null);
public function setBinaries($binaries);
public function getConfigurations();
public function getConnexions();
public function getServices();
public function getBinaries();
public function initialize();
public function delete();
public function isSetup();
}

View File

@@ -52,7 +52,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface
});
$app['authentication.providers.account-creator'] = $app->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'];
}

View File

@@ -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;
});
}

View File

@@ -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']);
});
}

View File

@@ -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']
);
});
}

View File

@@ -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;
});
}

View File

@@ -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){

View File

@@ -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) {

View File

@@ -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)
{
}
}

View File

@@ -1,172 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Border;
use Alchemy\Phrasea\Border\Manager;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
/**
* Define a Border Manager service which handles checks on files that comes in
* Phraseanet
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class BorderManager extends ServiceAbstract
{
/**
* @var Manager
*/
protected $borderManager;
/**
* Get all unregistered checkers due to bad configuration
* @var array
*/
protected $unregisteredCheckers = array();
/**
* {@inheritdoc}
*/
protected function init()
{
$borderManager = new Manager($this->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
);
}
}

View File

@@ -1,41 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service;
use Alchemy\Phrasea\Application;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Builder
{
public static function create(Application $app, ParameterBag $configuration)
{
$classname = __NAMESPACE__ . '\\' . $configuration->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);
}
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Cache;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Alchemy\Phrasea\Cache as CacheDriver;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class ApcCache extends ServiceAbstract
{
protected $cache;
public function getDriver()
{
if ( ! extension_loaded('apc')) {
throw new \Exception('The APC cache requires the APC extension.');
}
if (! $this->cache) {
$this->cache = new CacheDriver\ApcCache();
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
}
return $this->cache;
}
public function getType()
{
return 'apc';
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Cache;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Alchemy\Phrasea\Cache as CacheDriver;
/**
* Array cache
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class ArrayCache extends ServiceAbstract
{
protected $cache;
public function getDriver()
{
if (! $this->cache) {
$this->cache = new CacheDriver\ArrayCache();
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
}
return $this->cache;
}
public function getType()
{
return 'array';
}
}

View File

@@ -1,82 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Cache;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Alchemy\Phrasea\Cache as CacheDriver;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class MemcacheCache extends ServiceAbstract
{
const DEFAULT_HOST = "localhost";
const DEFAULT_PORT = "11211";
protected $cache;
protected $host;
protected $port;
protected function init()
{
$options = $this->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;
}
}

View File

@@ -1,83 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Cache;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Alchemy\Phrasea\Cache as CacheDriver;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class RedisCache extends ServiceAbstract
{
const DEFAULT_HOST = "localhost";
const DEFAULT_PORT = "6379";
protected $cache;
protected $host;
protected $port;
protected function init()
{
$options = $this->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;
}
}

View File

@@ -1,48 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Cache;
use Alchemy\Phrasea\Core,
Alchemy\Phrasea\Core\Service,
Alchemy\Phrasea\Core\Service\ServiceAbstract,
Alchemy\Phrasea\Core\Service\ServiceInterface,
Alchemy\Phrasea\Cache as CacheDriver;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class WinCacheCache extends ServiceAbstract
{
protected $cache;
public function getDriver()
{
if ( ! extension_loaded('wincache')) {
throw new \Exception('The WinCache cache requires the WinCache extension.');
}
if (! $this->cache) {
$this->cache = new CacheDriver\WinCacheCache();
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
}
return $this->cache;
}
public function getType()
{
return 'wincache';
}
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Cache;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Alchemy\Phrasea\Cache as CacheDriver;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class XcacheCache extends ServiceAbstract
{
protected $cache;
public function getDriver()
{
if ( ! extension_loaded('xcache')) {
throw new \Exception('The XCache cache requires the XCache extension.');
}
if (! $this->cache) {
$this->cache = new CacheDriver\XcacheCache();
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
}
return $this->cache;
}
public function getType()
{
return 'xcache';
}
}

View File

@@ -1,22 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Exception;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class MissingParameters extends \Exception
{
}

View File

@@ -1,22 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Exception;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class ServiceNotFound extends \Exception
{
}

View File

@@ -1,54 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Log\Doctrine;
use Alchemy\Phrasea\Core\Service\Log\Monolog as ParentLog;
use Doctrine\Logger\MonologSQLLogger;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Monolog extends ParentLog
{
const JSON_OUTPUT = 'json';
const YAML_OUTPUT = 'yaml';
const VAR_DUMP_OUTPUT = 'vdump';
public function getDriver()
{
$output = isset($this->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';
}
}

View File

@@ -1,34 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Log\Doctrine;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Doctrine\DBAL\Logging\EchoSQLLogger;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Phpecho extends ServiceAbstract
{
public function getDriver()
{
return new EchoSQLLogger();
}
public function getType()
{
return 'phpecho';
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Log;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Monolog\Logger;
use Monolog\Handler\FirePHPHandler;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class FirePHP extends ServiceAbstract
{
protected $logger;
public function getDriver()
{
if (! $this->logger) {
$this->logger = new Logger('FirePHP');
$this->logger->pushHandler(new FirePHPHandler());
}
return $this->logger;
}
public function getType()
{
return 'FirePHP Monolog';
}
}

View File

@@ -1,119 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Log;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Monolog extends ServiceAbstract
{
const DEFAULT_MAX_DAY = 10;
protected $handlers = array(
'rotate' => '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');
}
}

View File

@@ -1,214 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\Orm;
use Alchemy\Phrasea\Core\Service\Builder;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
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 Gedmo\Timestampable\TimestampableListener;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class Doctrine extends ServiceAbstract
{
protected $loggers = array(
'Log\\Doctrine\Monolog'
, 'Log\\Doctrine\\Phpecho'
);
protected $entityManager;
protected $debug;
protected function init()
{
$options = $this->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');
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\SearchEngine;
use Alchemy\Phrasea\SearchEngine\Phrasea\PhraseaEngine as PhraseaSearchEngine;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
class PhraseaEngine extends ServiceAbstract
{
protected $searchEngine;
protected function init()
{
$this->searchEngine = PhraseaSearchEngine::create($this->app);
return $this;
}
public function getDriver()
{
return $this->searchEngine;
}
public function getType()
{
return 'phrasea';
}
public function getMandatoryOptions()
{
return array();
}
}

View File

@@ -1,44 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\SearchEngine;
use Alchemy\Phrasea\SearchEngine\SphinxSearch\SphinxSearchEngine;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
class SphinxSearch extends ServiceAbstract
{
protected $searchEngine;
protected function init()
{
$options = $this->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');
}
}

View File

@@ -1,68 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service;
use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Core\Service\Exception\MissingParameters;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
abstract class ServiceAbstract implements ServiceInterface
{
protected $app;
protected $options;
final public function __construct(Application $app, Array $options)
{
$this->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();
}
}

View File

@@ -1,29 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service;
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
interface ServiceInterface
{
public function getType();
public function getDriver();
public function getOptions();
public function getMandatoryOptions();
}

View File

@@ -1,91 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Core\Service\TaskManager;
use Alchemy\Phrasea\Core\Service\ServiceAbstract;
use Symfony\Bridge\Monolog\Logger;
use Monolog\Handler\SyslogHandler;
use Monolog\Handler\NativeMailerHandler;
use Alchemy\Phrasea\Exception\RuntimeException;
class TaskManager extends ServiceAbstract
{
/** `
* `@var \task_manager
*/
protected $taskManager;
/**
* {@inheritdoc}
*/
protected function init()
{
$options = $this->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();
}
}

View File

@@ -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

View File

@@ -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());
}

View File

@@ -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
*

View File

@@ -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();
}
/**

View File

@@ -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);
}
}

View File

@@ -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) {

View File

@@ -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);
}
}

View File

@@ -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);

View File

@@ -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'),

View File

@@ -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();
}

View File

@@ -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')
);

View File

@@ -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;
}

View File

@@ -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)

View File

@@ -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])) {

View File

@@ -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) {

View File

@@ -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
*

View File

@@ -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

View File

@@ -1,828 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Alchemy\Phrasea\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Alchemy\Phrasea\Core\Service\Builder;
/**
* @todo write tests
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_console_fileEnsureDevSetting extends Command
{
const ALERT = 1;
const ERROR = 0;
/**
*
* @var \Alchemy\Phrasea\Core\Configuration
*/
protected $configuration;
protected $testSuite = array(
'checkPhraseanetScope'
, 'checkDatabaseScope'
, 'checkTeamplateEngineService'
, 'checkOrmService'
, 'checkCacheService'
, 'checkOpcodeCacheService'
, 'checkBorderService'
);
protected $errors = 0;
protected $alerts = 0;
public function __construct($name = null)
{
parent::__construct($name);
$this->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 <info>%s</info>", $this->configuration->getEnvironnement()));
$this->runTests($output);
$retval = $this->errors;
if ($input->getOption('strict')) {
$retval += $this->alerts;
}
if ($retval > 0) {
$output->writeln("\n<error>Some errors found in your conf</error>");
} else {
$output->writeln("\n<info>Your dev settings are setted correctly ! Enjoy</info>");
}
$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 = '<info>Works !</info>';
} else {
$work_message = '<comment>Cache server recommended</comment>';
$this->alerts++;
}
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %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 = '<info>Works !</info>';
} else {
$work_message = '<error>No cache required</error>';
$this->errors++;
}
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %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 = '<info>Works !</info>';
$listChecks = true;
} catch (\Exception $e) {
$work_message = '<error>Failed - could not load Border Manager service !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify Border Manager<info>%s</info> : %s", $serviceName, $work_message));
if ($listChecks) {
$borderManager = $service->getDriver();
foreach ($service->getUnregisteredCheckers() as $check) {
$output->writeln(sprintf("\t\t--> <comment>check %s could not be loaded for the following reason %s</comment>", $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, '<comment>Not recognized</comment>');
break;
case 'servername':
$url = $value;
$required = array_diff($required, array($conf));
$parseUrl = parse_url($url);
if (empty($url)) {
$message = "<error>should not be empty</error>";
$this->errors++;
} elseif ($url == 'http://sub.domain.tld/') {
$this->alerts++;
$message = "<comment>may be wrong</comment>";
} elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
$message = "<error>not valid</error>";
$this->errors++;
} else {
$message = "<info>OK</info>";
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'maintenance':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false) {
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'debug':
case 'display_errors':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true) {
$message = '<error>Should be true</error>';
$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 = '<info>OK</info>';
} else {
$message = '<error>Connection not available</error>';
$this->errors++;
}
} catch (\Exception $e) {
$message = '<error>Unknown connection</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>Works !</info>';
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
} catch (\Exception $e) {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify connection <info>%s</info> : %s", $connexionName, $work_message));
$required = array('driver');
if (!$connexion->has('driver')) {
$output->writeln("\n<error>Connection has no driver</error>");
$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("\n<error>Your driver is not managed</error>");
$this->errors++;
}
foreach ($connexion->all() as $conf => $value) {
switch ($conf) {
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
case 'charset':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'UTF8') {
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'path':
$required = array_diff($required, array($conf));
$message = is_writable(dirname($value)) ? '<info>OK</info>' : '<error>Not writeable</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'dbname':
case 'user':
case 'host':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value)) {
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'port':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value)) {
$message = '<error>Should be ctype_digit</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'password':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value)) {
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$value = '***********';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'driver':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'pdo_mysql') {
$message = '<error>MySQL recommended</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>Works !</info>';
} catch (\Exception $e) {
$work_message = '<error>Failed - could not load template engine !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify Template engine <info>%s</info> : %s", $templateEngineName, $work_message));
if (!$configuration->has('type')) {
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
} elseif ($configuration->get('type') == 'TemplateEngine\\Twig') {
$required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
} else {
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value) {
switch ($conf) {
case 'type':
$message = '<info>OK</info>';
if ($value !== 'TemplateEngine\\Twig') {
$message = '<error>Not recognized</error>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value)) {
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value) {
switch ($conf) {
case 'debug';
case 'strict_variables';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true) {
$message = '<error>Should be false</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'autoescape';
case 'optimizer';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true) {
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'charset';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'utf-8') {
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>Works !</info>';
} catch (\Exception $e) {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify ORM engine <info>%s</info> : %s", $ormName, $work_message));
if (!$configuration->has('type')) {
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
} elseif ($configuration->get('type') == 'Orm\\Doctrine') {
$required = array('debug', 'dbal', 'cache');
} else {
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value) {
switch ($conf) {
case 'type':
$message = $value == 'Orm\\Doctrine' ? '<info>OK</info>' : '<error>Not recognized</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value)) {
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value) {
switch ($conf) {
case 'log':
$message = '<info>OK</info>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'cache':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_array($value)) {
$message = '<error>Should be Array</error>';
$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 = '<info>Works !</info>';
} else {
$this->errors++;
$work_message = '<error>No cache required</error>';
}
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %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, '<comment>Not recognized</comment>');
break;
}
if (!isset($cache_type['service'])) {
$output->writeln('<error>Miss service for %s</error>', $cache_type);
$this->errors++;
}
}
}
if (count($required_caches) > 0) {
$output->writeln(sprintf('<error>Miss required caches %s</error>', implode(', ', $required_caches)));
$this->errors++;
}
break;
case 'debug':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true) {
$message = '<error>Should be true</error>';
$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 = '<info>OK</info>';
} catch (\Exception $e) {
$message = '<error>Failed</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>OK</info>';
if (!is_scalar($value)) {
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
case 'port';
$required_options = array_diff($required_options, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value)) {
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
}
if (count($required_options) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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));
}
}
}

View File

@@ -1,850 +0,0 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2013 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Alchemy\Phrasea\Command\Command;
use Alchemy\Phrasea\Core\Service\Builder;
/**
* @todo write tests
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class module_console_fileEnsureProductionSetting extends Command
{
const ALERT = 1;
const ERROR = 0;
/**
*
* @var \Alchemy\Phrasea\Core\Configuration
*/
protected $configuration;
protected $testSuite = array(
'checkPhraseanetScope'
, 'checkDatabaseScope'
, 'checkTeamplateEngineService'
, 'checkOrmService'
, 'checkSearchEngineService'
, 'checkCacheService'
, 'checkOpcodeCacheService'
, 'checkBorderService'
);
protected $errors = 0;
protected $alerts = 0;
public function __construct($name = null)
{
parent::__construct($name);
$this->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 <info>%s</info>", $this->configuration->getEnvironnement()));
$this->runTests($output);
$retval = $this->errors;
if ($input->getOption('strict')) {
$retval += $this->alerts;
}
if ($retval > 0) {
$output->writeln("\n<error>Some errors found in your conf</error>");
} else {
$output->writeln("\n<info>Your production settings are setted correctly ! Enjoy</info>");
}
$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 = '<info>Works !</info>';
} else {
$work_message = '<comment>Cache server recommended</comment>';
$this->alerts++;
}
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %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 = '<info>Works !</info>';
} else {
$work_message = '<comment>Opcode recommended</comment>';
$this->alerts++;
}
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %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 = '<info>Works !</info>';
$listChecks = true;
} catch (\Exception $e) {
$work_message = '<error>Failed - could not load Border Manager service !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify Border Manager<info>%s</info> : %s", $serviceName, $work_message));
if ($listChecks) {
$borderManager = $service->getDriver();
foreach ($service->getUnregisteredCheckers() as $check) {
$output->writeln(sprintf("\t\t--> <comment>check %s could not be loaded for the following reason %s</comment>", $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, '<comment>Not recognized</comment>');
break;
case 'servername':
$url = $value;
$required = array_diff($required, array($conf));
$parseUrl = parse_url($url);
if (empty($url)) {
$message = "<error>should not be empty</error>";
$this->errors++;
} elseif ($url == 'http://sub.domain.tld/') {
$this->alerts++;
$message = "<comment>may be wrong</comment>";
} elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
$message = "<error>not valid</error>";
$this->errors++;
} elseif ($parseUrl["scheme"] !== "https") {
$this->alerts++;
$message = "<comment>should be https</comment>";
} else {
$message = "<info>OK</info>";
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'maintenance':
case 'debug':
case 'display_errors':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false) {
$message = '<error>Should be false</error>';
$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 = '<info>OK</info>';
} else {
$message = '<error>Connection not available</error>';
$this->errors++;
}
} catch (\Exception $e) {
$message = '<error>Unknown connection</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>Works !</info>';
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
} catch (\Exception $e) {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify connection <info>%s</info> : %s", $connexionName, $work_message));
$required = array('driver');
if (!$connexion->has('driver')) {
$output->writeln("\n<error>Connection has no driver</error>");
$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("\n<error>Your driver is not managed</error>");
$this->errors++;
}
foreach ($connexion->all() as $conf => $value) {
switch ($conf) {
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
case 'charset':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'UTF8') {
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'path':
$required = array_diff($required, array($conf));
$message = is_writable(dirname($value)) ? '<info>OK</info>' : '<error>Not writeable</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'dbname':
case 'user':
case 'host':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value)) {
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'port':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value)) {
$message = '<error>Should be ctype_digit</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'password':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_scalar($value)) {
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$value = '***********';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'driver':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'pdo_mysql') {
$message = '<error>MySQL recommended</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>Works !</info>';
} catch (\Exception $e) {
$work_message = '<error>Failed - could not load template engine !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify Template engine <info>%s</info> : %s", $templateEngineName, $work_message));
if (!$configuration->has('type')) {
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
} elseif ($configuration->get('type') == 'TemplateEngine\\Twig') {
$required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
} else {
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value) {
switch ($conf) {
case 'type':
$message = '<info>OK</info>';
if ($value !== 'TemplateEngine\\Twig') {
$message = '<error>Not recognized</error>';
$this->alerts++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value)) {
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value) {
switch ($conf) {
case 'debug';
case 'strict_variables';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false) {
$message = '<error>Should be false</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'autoescape';
case 'optimizer';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== true) {
$message = '<error>Should be true</error>';
$this->errors++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
case 'charset';
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== 'utf-8') {
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>Works !</info>';
} catch (\Exception $e) {
$work_message = sprintf('<error>Failed : %s !</error>', $e->getMessage());
$this->errors ++;
}
$output->writeln(sprintf("\t--> Verify ORM engine <info>%s</info> : %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 = '<info>Works !</info>';
} catch (\Exception $e) {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$output->writeln(sprintf("\t--> Verify ORM engine <info>%s</info> : %s", $ormName, $work_message));
if (!$configuration->has('type')) {
$output->writeln("\n<error>Configuration has no type</error>");
$this->errors++;
} elseif ($configuration->get('type') == 'Orm\\Doctrine') {
$required = array('debug', 'dbal', 'cache');
} else {
$output->writeln("\n<error>Your type is not managed</error>");
$this->errors++;
}
foreach ($configuration->all() as $conf => $value) {
switch ($conf) {
case 'type':
$message = $value == 'Orm\\Doctrine' ? '<info>OK</info>' : '<error>Not recognized</error>';
$this->printConf($output, $conf, $value, false, $message);
break;
case 'options':
$message = '<info>OK</info>';
if (!is_array($value)) {
$message = '<error>Should be array</error>';
$this->errors++;
}
$this->printConf($output, $conf, 'array()', false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, 'unknown', false, '<comment>Not recognized</comment>');
break;
}
}
foreach ($configuration->get('options') as $conf => $value) {
switch ($conf) {
case 'log':
$message = '<info>OK</info>';
if ($value !== false) {
$message = '<error>Should be deactivated</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
case 'cache':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if (!is_array($value)) {
$message = '<error>Should be Array</error>';
$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 = '<info>Works !</info>';
} else {
$this->alerts++;
if ($server) {
$work_message = '<comment>Cache server recommended</comment>';
} else {
$work_message = '<comment>Opcode cache recommended</comment>';
}
}
} else {
$work_message = '<error>Failed - could not connect !</error>';
$this->errors++;
}
$verification = sprintf("\t--> Verify <info>%s</info> : %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, '<comment>Not recognized</comment>');
break;
}
if (!isset($cache_type['service'])) {
$output->writeln('<error>Miss service for %s</error>', $cache_type);
$this->errors++;
}
}
}
if (count($required_caches) > 0) {
$output->writeln(sprintf('<error>Miss required caches %s</error>', implode(', ', $required_caches)));
$this->errors++;
}
break;
case 'debug':
$required = array_diff($required, array($conf));
$message = '<info>OK</info>';
if ($value !== false) {
$message = '<error>Should be false</error>';
$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 = '<info>OK</info>';
} catch (\Exception $e) {
$message = '<error>Failed</error>';
$this->errors++;
}
$this->printConf($output, $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
if (count($required) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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 = '<info>OK</info>';
if (!is_scalar($value)) {
$message = '<error>Should be scalar</error>';
$this->errors++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
case 'port';
$required_options = array_diff($required_options, array($conf));
$message = '<info>OK</info>';
if (!ctype_digit($value)) {
$message = '<comment>Not recognized</comment>';
$this->alerts++;
}
$this->printConf($output, "\t\t" . $conf, $value, false, $message);
break;
default:
$this->alerts++;
$this->printConf($output, "\t\t" . $conf, $value, false, '<comment>Not recognized</comment>');
break;
}
}
}
if (count($required_options) > 0) {
$output->writeln(sprintf('<error>Miss required keys %s</error>', 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));
}
}
}

View File

@@ -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 = "

View File

@@ -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']

View File

@@ -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']);

View File

@@ -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);
}

View File

@@ -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;
}
}

View File

@@ -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);

View File

@@ -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);
}
}

View File

@@ -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;
}

View File

@@ -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;
}
}

View File

@@ -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');
}
}

147
lib/classes/patch/3807.php Normal file
View File

@@ -0,0 +1,147 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2012 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Alchemy\Phrasea\Application;
use Symfony\Component\Yaml\Yaml;
class patch_3807 implements patchInterface
{
/** @var string */
private $release = '3.8.0.a7';
/** @var array */
private $concern = array(base::APPLICATION_BOX);
private $yaml;
private $connexionsYaml;
private $binariesYaml;
private $servicesYaml;
private $configYaml;
/**
* {@inheritdoc}
*/
public function get_release()
{
return $this->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'];
}
}

View File

@@ -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()
);

View File

@@ -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);

View File

@@ -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);
}

View File

@@ -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

View File

@@ -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

View File

@@ -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: <HOSTNAME>
port: <PORT>
user: <USERNAME>
password: <PASSWORD>
dbname: <DATABASE_NAME>
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

View File

@@ -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

View File

@@ -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');

View File

@@ -0,0 +1,23 @@
<?php
namespace Alchemy\Phrasea\Command\Compile;
use Alchemy\Phrasea\Command\Compile\Configuration;
class ConfigurationTest extends \PhraseanetPHPUnitAbstract
{
public function testExecute()
{
$command = new Configuration();
$command->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);
}
}

View File

@@ -51,4 +51,3 @@ class CompilerTest extends \PHPUnit_Framework_TestCase
);
}
}

View File

@@ -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']);
}
}

View File

@@ -110,4 +110,4 @@ registration-fields:
required: true
-
name: geonameid
required: true
required: true

View File

@@ -110,4 +110,4 @@ registration-fields:
required: true
-
name: geonameid
required: true
required: true

View File

@@ -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')

View File

@@ -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'
),
);
}
}

View File

@@ -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'
),
);
}
}

View File

@@ -269,4 +269,4 @@ class patch_3807Test extends PHPUnit_Framework_TestCase
),
);
}
}
}

View File

@@ -1,2 +1,2 @@
binaries:
test_binary: /path/to/test/binary/file
test_binary: /path/to/test/binary/file