This commit is contained in:
Romain Neutron
2012-04-26 00:55:53 +02:00
parent edbfff226e
commit ade22295ad
631 changed files with 92375 additions and 101763 deletions

View File

@@ -29,9 +29,8 @@ $result_code = 1;
$result_code = 1; $result_code = 1;
try try {
{ $app = new Application("
$app = new Application("
_____ _ _ _____ _____ ______ _ _ ______ _______ _____ _ _ _____ _____ ______ _ _ ______ _______
| __ \| | | | __ \ /\ / ____| ____| /\ | \ | | ____|__ __| | __ \| | | | __ \ /\ / ____| ____| /\ | \ | | ____|__ __|
| |__) | |__| | |__) | / \ | (___ | |__ / \ | \| | |__ | | | |__) | |__| | |__) | / \ | (___ | |__ / \ | \| | |__ | |
@@ -47,45 +46,43 @@ try
This program comes with ABSOLUTELY NO WARRANTY. This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it This is free software, and you are welcome to redistribute it
under certain conditions; type `about:license' for details.\n\n" under certain conditions; type `about:license' for details.\n\n"
. ' KONSOLE KOMMANDER', \Alchemy\Phrasea\Core\Version::getName() . ' KONSOLE KOMMANDER', \Alchemy\Phrasea\Core\Version::getName()
. ' ' . \Alchemy\Phrasea\Core\Version::getNumber()); . ' ' . \Alchemy\Phrasea\Core\Version::getNumber());
$app->add(new module_console_aboutAuthors('about:authors')); $app->add(new module_console_aboutAuthors('about:authors'));
$app->add(new module_console_aboutLicense('about:license')); $app->add(new module_console_aboutLicense('about:license'));
$app->add(new module_console_checkExtension('check:extension')); $app->add(new module_console_checkExtension('check:extension'));
$app->add(new module_console_systemUpgrade('system:upgrade')); $app->add(new module_console_systemUpgrade('system:upgrade'));
$app->add(new module_console_sphinxGenerateSuggestion('sphinx:generate-suggestions')); $app->add(new module_console_sphinxGenerateSuggestion('sphinx:generate-suggestions'));
$app->add(new module_console_systemMailCheck('system:mailCheck')); $app->add(new module_console_systemMailCheck('system:mailCheck'));
$app->add(new module_console_systemBackupDB('system:backupDB')); $app->add(new module_console_systemBackupDB('system:backupDB'));
$app->add(new module_console_systemClearCache('system:clearCache')); $app->add(new module_console_systemClearCache('system:clearCache'));
$app->add(new module_console_systemTemplateGenerator('system:templateGenerator')); $app->add(new module_console_systemTemplateGenerator('system:templateGenerator'));
$app->add(new module_console_systemExport('system:export')); $app->add(new module_console_systemExport('system:export'));
$app->add(new module_console_taskrun('task:run')); $app->add(new module_console_taskrun('task:run'));
$app->add(new module_console_tasklist('task:list')); $app->add(new module_console_tasklist('task:list'));
$app->add(new module_console_schedulerState('scheduler:state')); $app->add(new module_console_schedulerState('scheduler:state'));
$app->add(new module_console_schedulerStop('scheduler:stop')); $app->add(new module_console_schedulerStop('scheduler:stop'));
$app->add(new module_console_schedulerStart('scheduler:start')); $app->add(new module_console_schedulerStart('scheduler:start'));
$app->add(new module_console_fileEnsureProductionSetting('check:ensureProductionSettings')); $app->add(new module_console_fileEnsureProductionSetting('check:ensureProductionSettings'));
$app->add(new module_console_fileEnsureDevSetting('check:ensureDevSettings')); $app->add(new module_console_fileEnsureDevSetting('check:ensureDevSettings'));
$app->add(new module_console_systemConfigCheck('check:system')); $app->add(new module_console_systemConfigCheck('check:system'));
$app->add(new module_console_fieldsList('fields:list')); $app->add(new module_console_fieldsList('fields:list'));
$app->add(new module_console_fieldsDelete('fields:delete')); $app->add(new module_console_fieldsDelete('fields:delete'));
$app->add(new module_console_fieldsRename('fields:rename')); $app->add(new module_console_fieldsRename('fields:rename'));
$app->add(new module_console_fieldsMerge('fields:merge')); $app->add(new module_console_fieldsMerge('fields:merge'));
$result_code = $app->run() === 0 ? : 1; $result_code = $app->run() === 0 ? : 1;
} } catch (Exception $e) {
catch (Exception $e) echo sprintf("an error occured : %s", $e->getMessage());
{
echo sprintf("an error occured : %s", $e->getMessage());
} }
exit($result_code); exit($result_code);

View File

@@ -26,63 +26,58 @@ use Alchemy\Phrasea;
$Core = require_once dirname(__FILE__) . '/../lib/bootstrap.php'; $Core = require_once dirname(__FILE__) . '/../lib/bootstrap.php';
try try {
{ $configuration = \Alchemy\Phrasea\Core\Configuration::build();
$configuration = \Alchemy\Phrasea\Core\Configuration::build();
$serviceName = $configuration->getOrm(); $serviceName = $configuration->getOrm();
$confService = $configuration->getService($serviceName); $confService = $configuration->getService($serviceName);
if ($confService->get("type") !== 'Orm\\Doctrine') if ($confService->get("type") !== 'Orm\\Doctrine') {
{ exit(sprintf("Doctrine is not declared as your ORM but %s is", $confService->get("type")));
exit(sprintf("Doctrine is not declared as your ORM but %s is", $confService->get("type"))); }
}
$ormService = \Alchemy\Phrasea\Core\Service\Builder::create( $ormService = \Alchemy\Phrasea\Core\Service\Builder::create(
$Core $Core
, $confService , $confService
); );
$em = $ormService->getDriver(); $em = $ormService->getDriver();
/* @var $em \Doctrine\ORM\EntityManager */ /* @var $em \Doctrine\ORM\EntityManager */
$app = new Application("Phraseanet Doctrine Console"); $app = new Application("Phraseanet Doctrine Console");
$helpers = array( $helpers = array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
); );
$helperSet = $app->getHelperSet(); $helperSet = $app->getHelperSet();
foreach ($helpers as $name => $helper) foreach ($helpers as $name => $helper) {
{ $helperSet->set($helper, $name);
$helperSet->set($helper, $name); }
}
$app->addCommands(array( $app->addCommands(array(
// DBAL Commands // DBAL Commands
new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
// ORM Commands // ORM Commands
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(), new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(), new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(), new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(), new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(), new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
)); ));
$app->run(); $app->run();
} } catch (Exception $e) {
catch (Exception $e) echo "an error occured : " . $e->getMessage();
{
echo "an error occured : " . $e->getMessage();
} }

View File

@@ -30,75 +30,70 @@ printf('Remove files ...' . PHP_EOL);
$finder = new Finder(); $finder = new Finder();
$finder $finder
->files() ->files()
->name('.gitmodules') ->name('.gitmodules')
->name('.gitignore') ->name('.gitignore')
->name('check_cs.php') ->name('check_cs.php')
->name('cleaner.php') ->name('cleaner.php')
->name('lib/phpunit.xml.dist') ->name('lib/phpunit.xml.dist')
->name('launchpadToLocales.php') ->name('launchpadToLocales.php')
->name('localesToLaunchPad.php') ->name('localesToLaunchPad.php')
->name('pom.xml') ->name('pom.xml')
->name('vendors.php') ->name('vendors.php')
->name('builder.php') ->name('builder.php')
->ignoreDotFiles(false) ->ignoreDotFiles(false)
->ignoreVCS(false) ->ignoreVCS(false)
->in(__DIR__); ->in(__DIR__);
$files = array(); $files = array();
foreach ($finder as $file) foreach ($finder as $file) {
{ $files[] = $file->getPathname();
$files[] = $file->getPathname();
} }
foreach ($files as $file) foreach ($files as $file) {
{ echo "rm $file\n";
echo "rm $file\n"; unlink($file);
unlink($file);
} }
$finder = new Finder(); $finder = new Finder();
$finder $finder
->directories() ->directories()
->name('test') ->name('test')
->name('tests') ->name('tests')
->name('demos') ->name('demos')
->name('demo') ->name('demo')
->name('example') ->name('example')
->name('examples') ->name('examples')
->name('docs') ->name('docs')
->name('documentation') ->name('documentation')
->name('doc') ->name('doc')
->name('as-docs') ->name('as-docs')
->name('hudson') ->name('hudson')
->name('.svn') ->name('.svn')
->name('.git') ->name('.git')
->name('flash') ->name('flash')
->ignoreDotFiles(false) ->ignoreDotFiles(false)
->ignoreVCS(false) ->ignoreVCS(false)
->in(__DIR__); ->in(__DIR__);
$dirs = array(); $dirs = array();
foreach ($finder as $dir) foreach ($finder as $dir) {
{ $dirs[] = $dir->getPathname();
$dirs[] = $dir->getPathname();
} }
foreach ($dirs as $dir) foreach ($dirs as $dir) {
{ if ( ! is_dir($dir)) {
if (!is_dir($dir)) continue;
{ }
continue;
}
$cmd = sprintf('rm -Rf %s' . PHP_EOL, escapeshellarg($dir)); $cmd = sprintf('rm -Rf %s' . PHP_EOL, escapeshellarg($dir));
printf($cmd); printf($cmd);
system($cmd); system($cmd);
} }
exit(0); exit(0);

View File

@@ -24,92 +24,85 @@ $fix = isset($argv[1]) && 'fix' == $argv[1];
$finder = new Finder(); $finder = new Finder();
$finder $finder
->files() ->files()
->name('*.md') ->name('*.md')
->name('*.php') ->name('*.php')
->name('*.inc') ->name('*.inc')
->name('*.php.dist') ->name('*.php.dist')
->name('*.twig') ->name('*.twig')
->name('*.xml') ->name('*.xml')
->name('*.xml.dist') ->name('*.xml.dist')
->name('*.yml') ->name('*.yml')
->in( ->in(
array( array(
__DIR__ . '/lib', __DIR__ . '/lib',
__DIR__ . '/bin', __DIR__ . '/bin',
__DIR__ . '/config', __DIR__ . '/config',
__DIR__ . '/www', __DIR__ . '/www',
__DIR__ . '/templates' __DIR__ . '/templates'
)
) )
) ->notName(basename(__FILE__))
->notName(basename(__FILE__)) ->exclude('.git')
->exclude('.git') ->exclude('vendor')
->exclude('vendor') ->exclude('Doctrine/Proxies')
->exclude('Doctrine/Proxies')
; ;
$count = 0; $count = 0;
foreach ($finder as $file) foreach ($finder as $file) {
{
/* @var $file Symfony\Component\Finder\SplFileInfo */ /* @var $file Symfony\Component\Finder\SplFileInfo */
$old = file_get_contents($file->getRealpath()); $old = file_get_contents($file->getRealpath());
$new = $old; $new = $old;
// [Structure] Never use short tags (<?) // [Structure] Never use short tags (<?)
$new = str_replace('<? ', '<?php ', $new); $new = str_replace('<? ', '<?php ', $new);
// [Structure] Indentation is done by steps of four spaces (tabs are never allowed) // [Structure] Indentation is done by steps of four spaces (tabs are never allowed)
$new = preg_replace_callback('/^( *)(\t+)/m', function ($matches) use ($new) $new = preg_replace_callback('/^( *)(\t+)/m', function ($matches) use ($new) {
{ return $matches[1] . str_repeat(' ', strlen($matches[2]));
return $matches[1] . str_repeat(' ', strlen($matches[2])); }, $new);
}, $new);
// [Structure] Use the linefeed character (0x0A) to end lines // [Structure] Use the linefeed character (0x0A) to end lines
$new = str_replace("\r\n", "\n", $new); $new = str_replace("\r\n", "\n", $new);
// [Structure] Don't add trailing spaces at the end of lines // [Structure] Don't add trailing spaces at the end of lines
$new = preg_replace('/[ \t]*$/m', '', $new); $new = preg_replace('/[ \t]*$/m', '', $new);
// [Structure] Convert tabs to spaces // [Structure] Convert tabs to spaces
$new = preg_replace('/\t/m', ' ', $new); $new = preg_replace('/\t/m', ' ', $new);
// [Structure] Add a blank line before return statements // [Structure] Add a blank line before return statements
$new = preg_replace_callback('/(^.*$)\n(^ +return)/m', function ($match) $new = preg_replace_callback('/(^.*$)\n(^ +return)/m', function ($match) {
{ // don't add it if the previous line is ...
// don't add it if the previous line is ... if (
if ( preg_match('/\{$/m', $match[1]) || // ... ending with an opening brace
preg_match('/\{$/m', $match[1]) || // ... ending with an opening brace preg_match('/\:$/m', $match[1]) || // ... ending with a colon (e.g. a case statement)
preg_match('/\:$/m', $match[1]) || // ... ending with a colon (e.g. a case statement) preg_match('%^ *//%m', $match[1]) || // ... an inline comment
preg_match('%^ *//%m', $match[1]) || // ... an inline comment preg_match('/^$/m', $match[1]) // ... already blank
preg_match('/^$/m', $match[1]) // ... already blank ) {
) return $match[1] . "\n" . $match[2];
{ }
return $match[1] . "\n" . $match[2];
}
return $match[1] . "\n\n" . $match[2]; return $match[1] . "\n\n" . $match[2];
}, $new); }, $new);
// [Structure] A file must always ends with a linefeed character // [Structure] A file must always ends with a linefeed character
if (strlen($new) && "\n" != substr($new, -1)) if (strlen($new) && "\n" != substr($new, -1)) {
{ $new .= "\n";
$new .= "\n"; }
}
if ($new != $old) {
if ($new != $old) $count ++;
{
$count++; if ($fix) {
file_put_contents($file->getRealpath(), $new);
if ($fix) }
{ printf('%4d) %s' . PHP_EOL, $count, $file->getRelativePathname());
file_put_contents($file->getRealpath(), $new);
} }
printf('%4d) %s' . PHP_EOL, $count, $file->getRelativePathname());
}
} }
exit($count ? 1 : 0); exit($count ? 1 : 0);

View File

@@ -17,50 +17,45 @@ set_time_limit(0);
$finder = new Finder(); $finder = new Finder();
$finder $finder
->files() ->files()
->name('*.gif') ->name('*.gif')
->name('*.jpeg') ->name('*.jpeg')
->name('*.jpg') ->name('*.jpg')
->name('*.png') ->name('*.png')
->notName('ui-*.png') ->notName('ui-*.png')
->exclude( ->exclude(
array( array(
'substitution' 'substitution'
, 'client/959595/images' , 'client/959595/images'
, 'client/000000/images' , 'client/000000/images'
, 'client/FFFFFF/images' , 'client/FFFFFF/images'
, 'skins/lng' , 'skins/lng'
) )
) )
->in(__DIR__ . '/www/skins'); ->in(__DIR__ . '/www/skins');
$files = array(); $files = array();
foreach ($finder as $file) foreach ($finder as $file) {
{ $result = '';
$result = '';
foreach (array('templates', 'lib/Alchemy', 'lib/Doctrine', 'lib/classes', 'www') as $dir) foreach (array('templates', 'lib/Alchemy', 'lib/Doctrine', 'lib/classes', 'www') as $dir) {
{ $cmd = "grep -IR -m 1 --exclude='(*\.git*)' '" . str_replace(array(), array(), $file->getFilename()) . "' " . __DIR__ . '/' . $dir;
$cmd = "grep -IR -m 1 --exclude='(*\.git*)' '" . str_replace(array(), array(), $file->getFilename()) . "' " . __DIR__.'/'.$dir; $result .= @exec($cmd);
$result .= @exec($cmd);
if (trim($result) !== '') if (trim($result) !== '') {
{ break;
break; }
} }
}
if (trim($result) === '') if (trim($result) === '') {
{ $files[] = $file->getPathname();
$files[] = $file->getPathname(); }
}
} }
foreach ($files as $file) foreach ($files as $file) {
{ echo "rm $file\n";
echo "rm $file\n"; unlink($file);
unlink($file);
} }
exit(0); exit(0);

View File

@@ -20,45 +20,42 @@ use Symfony\Component\Finder\Finder;
\Alchemy\Phrasea\Core::initAutoloads(); \Alchemy\Phrasea\Core::initAutoloads();
if (!isset($argv[1]) || !is_dir(__DIR__ . '/' . $argv[1])) if ( ! isset($argv[1]) || ! is_dir(__DIR__ . '/' . $argv[1])) {
{ echo "You need to specify a directory with the latest launchpad locales" . PHP_EOL;
echo "You need to specify a directory with the latest launchpad locales" . PHP_EOL; exit(1);
exit(1);
} }
chdir(__DIR__); chdir(__DIR__);
$finder = new Finder(); $finder = new Finder();
$finder $finder
->files() ->files()
->name('phraseanet-*.po') ->name('phraseanet-*.po')
->in( ->in(
array( array(
__DIR__ . '/' . $argv[1], __DIR__ . '/' . $argv[1],
)
) )
)
; ;
$count = 0; $count = 0;
foreach ($finder as $file) foreach ($finder as $file) {
{ preg_match('/phraseanet-(.*)\.po/', $file->getFileName(), $matches);
preg_match('/phraseanet-(.*)\.po/', $file->getFileName(), $matches);
$current_file = $file->getRealPath(); $current_file = $file->getRealPath();
$locale = $matches[1]; $locale = $matches[1];
$dest_file = __DIR__ . '/locale/' . $locale . '/LC_MESSAGES/phraseanet.po'; $dest_file = __DIR__ . '/locale/' . $locale . '/LC_MESSAGES/phraseanet.po';
if (!file_exists($dest_file)) if ( ! file_exists($dest_file)) {
{ echo "Destination $dest_file does not exists" . PHP_EOL;
echo "Destination $dest_file does not exists" . PHP_EOL; continue;
continue; }
}
system(sprintf('cp %s %s', $current_file, $dest_file)); system(sprintf('cp %s %s', $current_file, $dest_file));
$count++; $count ++;
} }
echo "$count files upgraded" . PHP_EOL; echo "$count files upgraded" . PHP_EOL;

View File

@@ -21,24 +21,23 @@ use Alchemy\Phrasea\Controller\Utils as ControllerUtils;
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func( return call_user_func(
function() function() {
{ $app = new \Silex\Application();
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore(); $app['Core'] = \bootstrap::getCore();
$app->mount('/', new Controller\Root()); $app->mount('/', new Controller\Root());
$app->mount('/publications', new Controller\Publications()); $app->mount('/publications', new Controller\Publications());
$app->mount('/users', new Controller\Users()); $app->mount('/users', new Controller\Users());
$app->mount('/fields', new Controller\Fields()); $app->mount('/fields', new Controller\Fields());
$app->mount('/subdefs', new Controller\Subdefs); $app->mount('/subdefs', new Controller\Subdefs);
$app->mount('/description', new Controller\Description()); $app->mount('/description', new Controller\Description());
$app->mount('/tests/connection', new ControllerUtils\ConnectionTest()); $app->mount('/tests/connection', new ControllerUtils\ConnectionTest());
$app->mount('/tests/pathurl', new ControllerUtils\PathFileTest()); $app->mount('/tests/pathurl', new ControllerUtils\PathFileTest());
$app->error(function($e){ $app->error(function($e) {
return new \Symfony\Component\HttpFoundation\Response($e->getMessage(), 403); return new \Symfony\Component\HttpFoundation\Response($e->getMessage(), 403);
}); });
return $app; return $app;
}); });

File diff suppressed because it is too large Load Diff

View File

@@ -21,45 +21,43 @@ use Symfony\Component\HttpKernel\Exception;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func(function() return call_user_func(function() {
{
$app = new \Silex\Application(); $app = new \Silex\Application();
$app["Core"] = \bootstrap::getCore(); $app["Core"] = \bootstrap::getCore();
$app["appbox"] = \appbox::get_instance($app['Core']); $app["appbox"] = \appbox::get_instance($app['Core']);
$app->get( $app->get(
'/', function() use ($app) '/', function() use ($app) {
{ $registry = $app["Core"]->getRegistry();
$registry = $app["Core"]->getRegistry();
$apiAdapter = new \API_V1_adapter(false, $app["appbox"], $app["Core"]); $apiAdapter = new \API_V1_adapter(false, $app["appbox"], $app["Core"]);
$versionNumber = (float) \Alchemy\Phrasea\Core\Version::getNumber(); $versionNumber = (float) \Alchemy\Phrasea\Core\Version::getNumber();
$ret = array( $ret = array(
'install_name' => $registry->get('GV_homeTitle'), 'install_name' => $registry->get('GV_homeTitle'),
'description' => $registry->get('GV_metaDescription'), 'description' => $registry->get('GV_metaDescription'),
'documentation' => 'https://docs.phraseanet.com/Devel', 'documentation' => 'https://docs.phraseanet.com/Devel',
'versions' => array( 'versions' => array(
'1' => array( '1' => array(
'number' => $apiAdapter->get_version(), 'number' => $apiAdapter->get_version(),
'uri' => '/api/v1/', 'uri' => '/api/v1/',
'authenticationProtocol' => 'OAuth2', 'authenticationProtocol' => 'OAuth2',
'authenticationVersion' => 'draft#v9', 'authenticationVersion' => 'draft#v9',
'authenticationEndPoints' => array( 'authenticationEndPoints' => array(
'authorization_token' => '/api/oauthv2/authorize', 'authorization_token' => '/api/oauthv2/authorize',
'access_token' => '/api/oauthv2/token' 'access_token' => '/api/oauthv2/token'
) )
) )
) )
); );
$json = $app["Core"]['Serializer']->serialize($ret, 'json'); $json = $app["Core"]['Serializer']->serialize($ret, 'json');
return new Response($json, 200, array('content-type' => 'application/json')); return new Response($json, 200, array('content-type' => 'application/json'));
});
return $app;
}); });
return $app;
});

File diff suppressed because it is too large Load Diff

View File

@@ -28,452 +28,401 @@ use Symfony\Component\HttpFoundation\Request;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func(function() return call_user_func(function() {
{ $app = new \Silex\Application();
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore(); $app['Core'] = \bootstrap::getCore();
$app->register(new \Silex\Provider\ValidatorServiceProvider(), array( $app->register(new \Silex\Provider\ValidatorServiceProvider(), array(
'validator.class_path' => __DIR__ . '/../../../../vendor/symfony/validator', 'validator.class_path' => __DIR__ . '/../../../../vendor/symfony/validator',
)); ));
$app['appbox'] = function() use ($app) $app['appbox'] = function() use ($app) {
{ return \appbox::get_instance($app['Core']);
return \appbox::get_instance($app['Core']); };
};
$app['oauth'] = function($app) $app['oauth'] = function($app) {
{ return new \API_OAuth2_Adapter($app['appbox']);
return new \API_OAuth2_Adapter($app['appbox']); };
};
/** /**
* Protected Closure * Protected Closure
* @var Closure * @var Closure
* @return Symfony\Component\HttpFoundation\Response * @return Symfony\Component\HttpFoundation\Response
*/ */
$app['response'] = $app->protect(function ($template, $variable) use ($app) $app['response'] = $app->protect(function ($template, $variable) use ($app) {
{ /* @var $twig \Twig_Environment */
/* @var $twig \Twig_Environment */ $twig = $app['Core']->getTwig();
$twig = $app['Core']->getTwig();
$response = new Response( $response = new Response(
$twig->render($template, $variable) $twig->render($template, $variable)
, 200 , 200
, array('Content-Type' => 'text/html') , array('Content-Type' => 'text/html')
); );
$response->setCharset('UTF-8'); $response->setCharset('UTF-8');
return $response; return $response;
}); });
/* * ******************************************************************* /* * *******************************************************************
* AUTHENTIFICATION API * AUTHENTIFICATION API
*/ */
/** /**
* AUTHORIZE ENDPOINT * AUTHORIZE ENDPOINT
* *
* Authorization endpoint - used to obtain authorization from the * Authorization endpoint - used to obtain authorization from the
* resource owner via user-agent redirection. * resource owner via user-agent redirection.
*/ */
$authorize_func = function() use ($app) $authorize_func = function() use ($app) {
{ $request = $app['request'];
$request = $app['request']; $oauth2_adapter = $app['oauth'];
$oauth2_adapter = $app['oauth']; /* @var $twig \Twig_Environment */
/* @var $twig \Twig_Environment */ $twig = $app['Core']->getTwig();
$twig = $app['Core']->getTwig(); $session = $app['appbox']->get_session();
$session = $app['appbox']->get_session();
//Check for auth params, send error or redirect if not valid //Check for auth params, send error or redirect if not valid
$params = $oauth2_adapter->getAuthorizationRequestParameters($request); $params = $oauth2_adapter->getAuthorizationRequestParameters($request);
$authenticated = $session->is_authenticated(); $authenticated = $session->is_authenticated();
$app_authorized = false; $app_authorized = false;
$errorMessage = false; $errorMessage = false;
$client = \API_OAuth2_Application::load_from_client_id($app['appbox'], $params['client_id']); $client = \API_OAuth2_Application::load_from_client_id($app['appbox'], $params['client_id']);
$oauth2_adapter->setClient($client); $oauth2_adapter->setClient($client);
$action_accept = $request->get("action_accept", null); $action_accept = $request->get("action_accept", null);
$action_login = $request->get("action_login", null); $action_login = $request->get("action_login", null);
$template = "api/auth/end_user_authorization.twig"; $template = "api/auth/end_user_authorization.twig";
$custom_template = sprintf( $custom_template = sprintf(
"%sconfig/templates/web/api/auth/end_user_authorization/%s.twig" "%sconfig/templates/web/api/auth/end_user_authorization/%s.twig"
, $app['appbox']->get_registry()->get('GV_RootPath') , $app['appbox']->get_registry()->get('GV_RootPath')
, $client->get_id() , $client->get_id()
); );
if (file_exists($custom_template)) if (file_exists($custom_template)) {
{ $template = sprintf(
$template = sprintf( 'api/auth/end_user_authorization/%s.twig'
'api/auth/end_user_authorization/%s.twig' , $client->get_id()
, $client->get_id() );
); }
}
if ( ! $authenticated) if ( ! $authenticated) {
{ if ($action_login !== null) {
if ($action_login !== null) try {
{ $login = $request->get("login");
try $password = $request->get("password");
{ $auth = new \Session_Authentication_Native($app['appbox'], $login, $password);
$login = $request->get("login"); $session->authenticate($auth);
$password = $request->get("password"); } catch (\Exception $e) {
$auth = new \Session_Authentication_Native($app['appbox'], $login, $password);
$session->authenticate($auth);
}
catch (\Exception $e)
{
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => true
, "user" => $app['Core']->getAuthenticatedUser()
);
$html = $twig->render($template, $params);
return new Response($html, 200, array("content-type" => "text/html"));
}
}
else
{
$params = array( $params = array(
"auth" => $oauth2_adapter "auth" => $oauth2_adapter
, "session" => $session , "session" => $session
, "errorMessage" => $errorMessage , "errorMessage" => true
, "user" => $app['Core']->getAuthenticatedUser() , "user" => $app['Core']->getAuthenticatedUser()
); );
$html = $twig->render($template, $params); $html = $twig->render($template, $params);
return new Response($html, 200, array("content-type" => "text/html")); return new Response($html, 200, array("content-type" => "text/html"));
}
} }
} else {
//check if current client is already authorized by current user $params = array(
$user_auth_clients = \API_OAuth2_Application::load_authorized_app_by_user( "auth" => $oauth2_adapter
$app['appbox'] , "session" => $session
, $app['Core']->getAuthenticatedUser() , "errorMessage" => $errorMessage
, "user" => $app['Core']->getAuthenticatedUser()
); );
$html = $twig->render($template, $params);
foreach ($user_auth_clients as $auth_client) return new Response($html, 200, array("content-type" => "text/html"));
{ }
if ($client->get_client_id() == $auth_client->get_client_id()) }
$app_authorized = true;
}
$account = $oauth2_adapter->updateAccount($session->get_usr_id()); //check if current client is already authorized by current user
$user_auth_clients = \API_OAuth2_Application::load_authorized_app_by_user(
$app['appbox']
, $app['Core']->getAuthenticatedUser()
);
$params['account_id'] = $account->get_id(); foreach ($user_auth_clients as $auth_client) {
if ($client->get_client_id() == $auth_client->get_client_id())
$app_authorized = true;
}
if ( ! $app_authorized && $action_accept === null) $account = $oauth2_adapter->updateAccount($session->get_usr_id());
{
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['Core']->getAuthenticatedUser()
);
$html = $twig->render($template, $params); $params['account_id'] = $account->get_id();
return new Response($html, 200, array("content-type" => "text/html")); if ( ! $app_authorized && $action_accept === null) {
} $params = array(
elseif ( ! $app_authorized && $action_accept !== null) "auth" => $oauth2_adapter
{ , "session" => $session
$app_authorized = ! ! $action_accept; , "errorMessage" => $errorMessage
$account->set_revoked( ! $app_authorized); , "user" => $app['Core']->getAuthenticatedUser()
} );
//if native app show template $html = $twig->render($template, $params);
if ($oauth2_adapter->isNativeApp($params['redirect_uri']))
{
$params = $oauth2_adapter->finishNativeClientAuthorization($app_authorized, $params);
$params['user'] = $app['Core']->getAuthenticatedUser();
$html = $twig->render("api/auth/native_app_access_token.twig", $params);
return new Response($html, 200, array("content-type" => "text/html")); return new Response($html, 200, array("content-type" => "text/html"));
} } elseif ( ! $app_authorized && $action_accept !== null) {
else $app_authorized = ! ! $action_accept;
{ $account->set_revoked( ! $app_authorized);
$oauth2_adapter->finishClientAuthorization($app_authorized, $params); }
}
};
$route = '/authorize'; //if native app show template
$app->get($route, $authorize_func); if ($oauth2_adapter->isNativeApp($params['redirect_uri'])) {
$app->post($route, $authorize_func); $params = $oauth2_adapter->finishNativeClientAuthorization($app_authorized, $params);
$params['user'] = $app['Core']->getAuthenticatedUser();
$html = $twig->render("api/auth/native_app_access_token.twig", $params);
return new Response($html, 200, array("content-type" => "text/html"));
} else {
$oauth2_adapter->finishClientAuthorization($app_authorized, $params);
}
};
$route = '/authorize';
$app->get($route, $authorize_func);
$app->post($route, $authorize_func);
/** /**
* TOKEN ENDPOINT * TOKEN ENDPOINT
* Token endpoint - used to exchange an authorization grant for an access token. * Token endpoint - used to exchange an authorization grant for an access token.
*/ */
$route = '/token'; $route = '/token';
$app->post($route, function(\Silex\Application $app, Request $request) $app->post($route, function(\Silex\Application $app, Request $request) {
{ if ( ! $request->isSecure()) {
if(!$request->isSecure()) throw new HttpException(400, 'require the use of the https', null, array('content-type' => 'application/json'));
{ }
throw new HttpException(400, 'require the use of the https', null, array('content-type'=> 'application/json'));
}
$app['oauth']->grantAccessToken(); $app['oauth']->grantAccessToken();
ob_flush(); ob_flush();
flush(); flush();
return; return;
});
/**
* MANAGEMENT APPS
*
*
*/
/**
* list of all authorized apps by logged user
*/
$route = '/applications';
$app->get($route, function() use ($app)
{
$apps = \API_OAuth2_Application::load_app_by_user($app['appbox'], $app['Core']->getAuthenticatedUser());
return $app['response']('api/auth/applications.twig', array("apps" => $apps, 'user' => $app['Core']->getAuthenticatedUser()));
});
/**
* list of apps created by user
*/
$route = "/applications/dev";
$app->get($route, function() use ($app)
{
$rs = \API_OAuth2_Application::load_dev_app_by_user($app['appbox'], $app['Core']->getAuthenticatedUser());
return $app['response']('api/auth/application_dev.twig', array("apps" => $rs));
});
/**
* display a new app form
*/
$route = "/applications/dev/new";
$app->get($route, function() use ($app)
{
$var = array("violations" => null, 'form' => null, 'request' => $app['request']);
return $app['response']('api/auth/application_dev_new.twig', $var);
});
$route = "/applications/dev/create";
$app->post($route, function() use ($app)
{
$submit = false;
if ($app['request']->get("type") == "desktop")
{
$post = new \API_OAuth2_Form_DevAppDesktop($app['request']);
}
else
{
$post = new \API_OAuth2_Form_DevAppInternet($app['request']);
}
$violations = $app['validator']->validate($post);
if ($violations->count() == 0)
$submit = true;
$request = $app['request'];
if ($submit)
{
$application = \API_OAuth2_Application::create($app['appbox'], $app['Core']->getAuthenticatedUser(), $post->getName());
$application->set_description($post->getDescription())
->set_redirect_uri($post->getSchemeCallback() . $post->getCallback())
->set_type($post->getType())
->set_website($post->getSchemeWebsite() . $post->getWebsite());
return $app->redirect("/api/oauthv2/applications/dev/" . $application->get_id() . "/show");
}
$var = array(
"violations" => $violations,
"form" => $post
);
return $app['response']('api/auth/application_dev_new.twig', $var);
});
/**
* show details of app identified by its id
*/
$route = "/applications/dev/{id}/show";
$app->get($route, function($id) use ($app)
{
$client = new \API_OAuth2_Application($app['appbox'], $id);
$token = $client->get_user_account($app['Core']->getAuthenticatedUser())->get_token()->get_value();
$var = array("app" => $client, "user" => $app['Core']->getAuthenticatedUser(), "token" => $token);
return $app['response']('api/auth/application_dev_show.twig', $var);
})->assert('id', '\d+');
/**
* revoke access from a user to the app
* identified by account id
*/
$route = "/applications/revoke_access/";
$app->post($route, function() use ($app)
{
$result = array("ok" => false);
try
{
$account = new \API_OAuth2_Account($app['appbox'], $app['request']->get('account_id'));
$account->set_revoked((bool) $app['request']->get('revoke'));
$result['ok'] = true;
}
catch (\Exception $e)
{
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
});
$route = "/applications/{id}/generate_access_token/";
$app->post($route, function($id) use ($app)
{
$result = array("ok" => false);
try
{
$client = new \API_OAuth2_Application($app['appbox'], $id);
$account = $client->get_user_account($app['Core']->getAuthenticatedUser());
$token = $account->get_token();
if ($token instanceof API_OAuth2_Token)
$token->renew();
else
$token = \API_OAuth2_Token::create($app['appbox'], $account);
$result = array(
"ok" => true
, 'token' => $token->get_value()
);
}
catch (\Exception $e)
{
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
})->assert('id', '\d+');
$route = "/applications/oauth_callback";
$app->post($route, function() use ($app)
{
$app_id = $app['request']->request->get("app_id");
$app_callback = $app["request"]->request->get("callback");
$result = array("success" => false);
try
{
$client = new \API_OAuth2_Application($app['appbox'], $app_id);
$client->set_redirect_uri($app_callback);
$result['success'] = true;
}
catch (\Exception $e)
{
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
});
$route = "/applications/{id}";
$app->delete($route, function($id) use ($app)
{
$result = array("success" => false);
try
{
$client = new \API_OAuth2_Application($app['appbox'], $id);
$client->delete();
$result['success'] = true;
}
catch (\Exception $e)
{
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
})->assert('id', '\d+');
/**
* *******************************************************************
*
* Route Errors
*
*/
$app->error(function (\Exception $e) use ($app)
{
if ($e instanceof NotFoundHttpException || $e instanceof \Exception_NotFound)
{
return new Response('The requested page could not be found.', 404);
}
$code = 500;
$msg = 'We are sorry, but something went wrong';
$headers = array();
if($e instanceof HttpExceptionInterface)
{
$headers = $e->getHeaders();
$msg = $e->getMessage();
$code = $e->getStatusCode();
if(isset($headers['content-type']) && $headers['content-type'] == 'application/json')
{
$obj = new \stdClass();
$obj->msg = $msg;
$obj->code = $code;
$msg = json_encode($obj);
}
}
return new Response($msg, $code, $headers);
});
return $app;
}); });
/**
* MANAGEMENT APPS
*
*
*/
/**
* list of all authorized apps by logged user
*/
$route = '/applications';
$app->get($route, function() use ($app) {
$apps = \API_OAuth2_Application::load_app_by_user($app['appbox'], $app['Core']->getAuthenticatedUser());
return $app['response']('api/auth/applications.twig', array("apps" => $apps, 'user' => $app['Core']->getAuthenticatedUser()));
});
/**
* list of apps created by user
*/
$route = "/applications/dev";
$app->get($route, function() use ($app) {
$rs = \API_OAuth2_Application::load_dev_app_by_user($app['appbox'], $app['Core']->getAuthenticatedUser());
return $app['response']('api/auth/application_dev.twig', array("apps" => $rs));
});
/**
* display a new app form
*/
$route = "/applications/dev/new";
$app->get($route, function() use ($app) {
$var = array("violations" => null, 'form' => null, 'request' => $app['request']);
return $app['response']('api/auth/application_dev_new.twig', $var);
});
$route = "/applications/dev/create";
$app->post($route, function() use ($app) {
$submit = false;
if ($app['request']->get("type") == "desktop") {
$post = new \API_OAuth2_Form_DevAppDesktop($app['request']);
} else {
$post = new \API_OAuth2_Form_DevAppInternet($app['request']);
}
$violations = $app['validator']->validate($post);
if ($violations->count() == 0)
$submit = true;
$request = $app['request'];
if ($submit) {
$application = \API_OAuth2_Application::create($app['appbox'], $app['Core']->getAuthenticatedUser(), $post->getName());
$application->set_description($post->getDescription())
->set_redirect_uri($post->getSchemeCallback() . $post->getCallback())
->set_type($post->getType())
->set_website($post->getSchemeWebsite() . $post->getWebsite());
return $app->redirect("/api/oauthv2/applications/dev/" . $application->get_id() . "/show");
}
$var = array(
"violations" => $violations,
"form" => $post
);
return $app['response']('api/auth/application_dev_new.twig', $var);
});
/**
* show details of app identified by its id
*/
$route = "/applications/dev/{id}/show";
$app->get($route, function($id) use ($app) {
$client = new \API_OAuth2_Application($app['appbox'], $id);
$token = $client->get_user_account($app['Core']->getAuthenticatedUser())->get_token()->get_value();
$var = array("app" => $client, "user" => $app['Core']->getAuthenticatedUser(), "token" => $token);
return $app['response']('api/auth/application_dev_show.twig', $var);
})->assert('id', '\d+');
/**
* revoke access from a user to the app
* identified by account id
*/
$route = "/applications/revoke_access/";
$app->post($route, function() use ($app) {
$result = array("ok" => false);
try {
$account = new \API_OAuth2_Account($app['appbox'], $app['request']->get('account_id'));
$account->set_revoked((bool) $app['request']->get('revoke'));
$result['ok'] = true;
} catch (\Exception $e) {
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
});
$route = "/applications/{id}/generate_access_token/";
$app->post($route, function($id) use ($app) {
$result = array("ok" => false);
try {
$client = new \API_OAuth2_Application($app['appbox'], $id);
$account = $client->get_user_account($app['Core']->getAuthenticatedUser());
$token = $account->get_token();
if ($token instanceof API_OAuth2_Token)
$token->renew();
else
$token = \API_OAuth2_Token::create($app['appbox'], $account);
$result = array(
"ok" => true
, 'token' => $token->get_value()
);
} catch (\Exception $e) {
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
})->assert('id', '\d+');
$route = "/applications/oauth_callback";
$app->post($route, function() use ($app) {
$app_id = $app['request']->request->get("app_id");
$app_callback = $app["request"]->request->get("callback");
$result = array("success" => false);
try {
$client = new \API_OAuth2_Application($app['appbox'], $app_id);
$client->set_redirect_uri($app_callback);
$result['success'] = true;
} catch (\Exception $e) {
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
});
$route = "/applications/{id}";
$app->delete($route, function($id) use ($app) {
$result = array("success" => false);
try {
$client = new \API_OAuth2_Application($app['appbox'], $id);
$client->delete();
$result['success'] = true;
} catch (\Exception $e) {
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($result, 'json')
, 200
, array("content-type" => "application/json")
);
})->assert('id', '\d+');
/**
* *******************************************************************
*
* Route Errors
*
*/
$app->error(function (\Exception $e) use ($app) {
if ($e instanceof NotFoundHttpException || $e instanceof \Exception_NotFound) {
return new Response('The requested page could not be found.', 404);
}
$code = 500;
$msg = 'We are sorry, but something went wrong';
$headers = array();
if ($e instanceof HttpExceptionInterface) {
$headers = $e->getHeaders();
$msg = $e->getMessage();
$code = $e->getStatusCode();
if (isset($headers['content-type']) && $headers['content-type'] == 'application/json') {
$obj = new \stdClass();
$obj->msg = $msg;
$obj->code = $code;
$msg = json_encode($obj);
}
}
return new Response($msg, $code, $headers);
});
return $app;
});

View File

@@ -23,235 +23,199 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func( return call_user_func(
function() function() {
{
$app = new \Silex\Application(); $app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore(); $app['Core'] = \bootstrap::getCore();
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$session = $appbox->get_session(); $session = $appbox->get_session();
$deliver_content = function(\Session_Handler $session, \record_adapter $record, $subdef, $watermark, $stamp, $app) $deliver_content = function(\Session_Handler $session, \record_adapter $record, $subdef, $watermark, $stamp, $app) {
{
$file = $record->get_subdef($subdef); $file = $record->get_subdef($subdef);
if ($file->get_baseurl() !== '') if ($file->get_baseurl() !== '') {
{ return $app->redirect($file->get_url());
return $app->redirect($file->get_url()); }
}
$pathIn = $pathOut = $file->get_pathfile(); $pathIn = $pathOut = $file->get_pathfile();
if ($watermark === true && $file->get_type() === \media_subdef::TYPE_IMAGE) if ($watermark === true && $file->get_type() === \media_subdef::TYPE_IMAGE) {
{ $pathOut = \recordutils_image::watermark($record->get_base_id(), $record->get_record_id());
$pathOut = \recordutils_image::watermark($record->get_base_id(), $record->get_record_id()); } elseif ($stamp === true && $file->get_type() === \media_subdef::TYPE_IMAGE) {
} $pathOut = \recordutils_image::stamp($record->get_base_id(), $record->get_record_id());
elseif ($stamp === true && $file->get_type() === \media_subdef::TYPE_IMAGE) }
{
$pathOut = \recordutils_image::stamp($record->get_base_id(), $record->get_record_id());
}
$log_id = null; $log_id = null;
try try {
{ $registry = \registry::get_instance();
$registry = \registry::get_instance(); $logger = $session->get_logger($record->get_databox());
$logger = $session->get_logger($record->get_databox()); $log_id = $logger->get_id();
$log_id = $logger->get_id();
$referrer = 'NO REFERRER'; $referrer = 'NO REFERRER';
if (isset($_SERVER['HTTP_REFERER'])) if (isset($_SERVER['HTTP_REFERER']))
$referrer = $_SERVER['HTTP_REFERER']; $referrer = $_SERVER['HTTP_REFERER'];
$record->log_view($log_id, $referrer, $registry->get('GV_sit')); $record->log_view($log_id, $referrer, $registry->get('GV_sit'));
} } catch (\Exception $e) {
catch (\Exception $e)
{
} }
return \set_export::stream_file($pathOut, $file->get_file(), $file->get_mime(), 'attachment'); return \set_export::stream_file($pathOut, $file->get_file(), $file->get_mime(), 'attachment');
}; };
$app->get('/datafiles/{sbas_id}/{record_id}/{subdef}/', function($sbas_id, $record_id, $subdef) use ($app, $session, $deliver_content) $app->get('/datafiles/{sbas_id}/{record_id}/{subdef}/', function($sbas_id, $record_id, $subdef) use ($app, $session, $deliver_content) {
{
$databox = \databox::get_instance((int) $sbas_id); $databox = \databox::get_instance((int) $sbas_id);
$record = new \record_adapter($sbas_id, $record_id); $record = new \record_adapter($sbas_id, $record_id);
$record->get_type(); $record->get_type();
if ( ! $session->is_authenticated()) if ( ! $session->is_authenticated())
throw new \Exception_Session_NotAuthenticated(); throw new \Exception_Session_NotAuthenticated();
$user = \User_Adapter::getInstance($session->get_usr_id(), \appbox::get_instance($app['Core'])); $user = \User_Adapter::getInstance($session->get_usr_id(), \appbox::get_instance($app['Core']));
if ( ! $user->ACL()->has_access_to_subdef($record, $subdef)) if ( ! $user->ACL()->has_access_to_subdef($record, $subdef))
throw new \Exception_UnauthorizedAction(); throw new \Exception_UnauthorizedAction();
$stamp = false; $stamp = false;
$watermark = ! $user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark'); $watermark = ! $user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark');
if ($watermark) if ($watermark) {
{ $subdef_class = $databox
$subdef_class = $databox ->get_subdef_structure()
->get_subdef_structure() ->get_subdef($record->get_type(), $subdef)
->get_subdef($record->get_type(), $subdef) ->get_class();
->get_class();
if ($subdef_class == \databox_subdef::CLASS_PREVIEW && $user->ACL()->has_preview_grant($record)) if ($subdef_class == \databox_subdef::CLASS_PREVIEW && $user->ACL()->has_preview_grant($record)) {
{ $watermark = false;
$watermark = false; } elseif ($subdef_class == \databox_subdef::CLASS_DOCUMENT && $user->ACL()->has_hd_grant($record)) {
} $watermark = false;
elseif ($subdef_class == \databox_subdef::CLASS_DOCUMENT && $user->ACL()->has_hd_grant($record)) }
{ }
$watermark = false;
}
}
if ($watermark) if ($watermark) {
{
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\BasketElement'); $repository = $em->getRepository('\Entities\BasketElement');
/* @var $repository \Repositories\BasketElementRepository */ /* @var $repository \Repositories\BasketElementRepository */
$ValidationByRecord = $repository->findReceivedValidationElementsByRecord($record, $user); $ValidationByRecord = $repository->findReceivedValidationElementsByRecord($record, $user);
$ReceptionByRecord = $repository->findReceivedElementsByRecord($record, $user); $ReceptionByRecord = $repository->findReceivedElementsByRecord($record, $user);
if ($ValidationByRecord && $ValidationByRecord->count() > 0) if ($ValidationByRecord && $ValidationByRecord->count() > 0) {
{ $watermark = false;
$watermark = false; } elseif ($ReceptionByRecord && $ReceptionByRecord->count() > 0) {
} $watermark = false;
elseif ($ReceptionByRecord && $ReceptionByRecord->count() > 0) }
{ }
$watermark = false;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app); return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/view/' $app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/view/'
, function($label, $sbas_id, $record_id, $key, $subdef) use($app) , function($label, $sbas_id, $record_id, $key, $subdef) use($app) {
{
$databox = \databox::get_instance((int) $sbas_id); $databox = \databox::get_instance((int) $sbas_id);
$record = \media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef); $record = \media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef);
if ( ! ($record instanceof \record_adapter)) if ( ! ($record instanceof \record_adapter))
throw new \Exception('bad luck'); throw new \Exception('bad luck');
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
$params = array( $params = array(
'subdef_name' => $subdef 'subdef_name' => $subdef
, 'module_name' => 'overview' , 'module_name' => 'overview'
, 'module' => 'overview' , 'module' => 'overview'
, 'view' => 'overview' , 'view' => 'overview'
, 'record' => $record , 'record' => $record
); );
return $twig->render('overview.twig', $params); return $twig->render('overview.twig', $params);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/' $app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/'
, function($label, $sbas_id, $record_id, $key, $subdef) use ($app, $session, $deliver_content) , function($label, $sbas_id, $record_id, $key, $subdef) use ($app, $session, $deliver_content) {
{ $databox = \databox::get_instance((int) $sbas_id);
$databox = \databox::get_instance((int) $sbas_id); $record = \media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef);
$record = \media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef); if ( ! ($record instanceof \record_adapter))
if ( ! ($record instanceof \record_adapter)) throw new \Exception('bad luck');
throw new \Exception('bad luck');
$watermark = $stamp = false; $watermark = $stamp = false;
if ($session->is_authenticated()) if ($session->is_authenticated()) {
{ $user = \User_Adapter::getInstance($session->get_usr_id(), \appbox::get_instance($app['Core']));
$user = \User_Adapter::getInstance($session->get_usr_id(), \appbox::get_instance($app['Core']));
$watermark = ! $user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark'); $watermark = ! $user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark');
if ($watermark) if ($watermark) {
{
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\BasketElement'); $repository = $em->getRepository('\Entities\BasketElement');
if ($repository->findReceivedValidationElementsByRecord($record, $user)->count() > 0) if ($repository->findReceivedValidationElementsByRecord($record, $user)->count() > 0) {
{ $watermark = false;
$watermark = false; } elseif ($repository->findReceivedElementsByRecord($record, $user)->count() > 0) {
} $watermark = false;
elseif ($repository->findReceivedElementsByRecord($record, $user)->count() > 0) }
{ }
$watermark = false;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app); return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
} } else {
else $collection = \collection::get_from_base_id($record->get_base_id());
{ switch ($collection->get_pub_wm()) {
$collection = \collection::get_from_base_id($record->get_base_id()); default:
switch ($collection->get_pub_wm()) case 'none':
{ $watermark = false;
default: break;
case 'none': case 'stamp':
$watermark = false; $stamp = true;
break; break;
case 'stamp': case 'wm':
$stamp = true; $watermark = false;
break; break;
case 'wm': }
$watermark = false; }
break;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app); return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
} }
) )
->assert('sbas_id', '\d+')->assert('record_id', '\d+'); ->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->error(function (\Exception $e) $app->error(function (\Exception $e) {
{ if ($e instanceof \Exception_Session_NotAuthenticated) {
if ($e instanceof \Exception_Session_NotAuthenticated) $code = 403;
{ $message = 'Forbidden';
$code = 403; } elseif ($e instanceof \Exception_NotAllowed) {
$message = 'Forbidden'; $code = 403;
} $message = 'Forbidden';
elseif ($e instanceof \Exception_NotAllowed) } elseif ($e instanceof \Exception_NotFound) {
{ $code = 404;
$code = 403; $message = 'Not Found';
$message = 'Forbidden'; } else {
} $code = 404;
elseif ($e instanceof \Exception_NotFound) $message = 'Not Found';
{ }
$code = 404;
$message = 'Not Found';
}
else
{
$code = 404;
$message = 'Not Found';
}
return new Response($message, $code); return new Response($message, $code);
}); });
return $app; return $app;
} }
); );

View File

@@ -21,113 +21,98 @@ use Alchemy\Phrasea\Controller\Prod as Controller;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func(function() return call_user_func(function() {
{ $app = new \Silex\Application();
$app = new \Silex\Application(); $app['Core'] = \bootstrap::getCore();
$app['Core'] = \bootstrap::getCore();
$app->before(function(Request $request) $app->before(function(Request $request) {
{ $request->setRequestFormat(
$request->setRequestFormat( $request->getFormat(
$request->getFormat( array_shift(
array_shift( $request->getAcceptableContentTypes()
$request->getAcceptableContentTypes() )
) )
) );
); });
$app->mount('/UserPreferences/', new Controller\UserPreferences());
$app->mount('/query/', new Controller\Query());
$app->mount('/baskets', new Controller\Basket());
$app->mount('/story', new Controller\Story());
$app->mount('/WorkZone', new Controller\WorkZone());
$app->mount('/lists', new Controller\UsrLists());
$app->mount('/MustacheLoader', new Controller\MustacheLoader());
$app->mount('/records/edit', new Controller\Edit());
$app->mount('/records/movecollection', new Controller\MoveCollection());
$app->mount('/bridge/', new Controller\Bridge());
$app->mount('/push/', new Controller\Push());
$app->mount('/printer/', new Controller\Printer());
$app->mount('/TOU/', new Controller\TOU());
$app->mount('/feeds', new Controller\Feed());
$app->mount('/tooltip', new Controller\Tooltip());
$app->mount('/language', new Controller\Language());
$app->mount('/tools/', new Controller\Tools());
$app->mount('/', new Controller\Root());
$app->error(function (\Exception $e, $code) use ($app) {
/* @var $request \Symfony\Component\HttpFoundation\Request */
$request = $app['request'];
if ($e instanceof \Bridge_Exception) {
$params = array(
'message' => $e->getMessage()
, 'file' => $e->getFile()
, 'line' => $e->getLine()
, 'r_method' => $request->getMethod()
, 'r_action' => $request->getRequestUri()
, 'r_parameters' => ($request->getMethod() == 'GET' ? array() : $request->request->all())
);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
if ($e instanceof \Bridge_Exception_ApiConnectorNotConfigured) {
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/notconfigured.twig', $params), 200);
} elseif ($e instanceof \Bridge_Exception_ApiConnectorNotConnected) {
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/disconnected.twig', $params), 200);
} elseif ($e instanceof \Bridge_Exception_ApiConnectorAccessTokenFailed) {
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/disconnected.twig', $params), 200);
} elseif ($e instanceof \Bridge_Exception_ApiDisabled) {
$params = array_merge($params, array('api' => $e->get_api()));
return new response($twig->render('/prod/actions/Bridge/deactivated.twig', $params), 200);
}
return new response($twig->render('/prod/actions/Bridge/error.twig', $params), 200);
}
if ($request->getRequestFormat() == 'json') {
$datas = array(
'success' => false
, 'message' => $e->getMessage()
);
$json = $app['Core']['Serializer']->serialize($datas, 'json');
return new Response($json, 200, array('Content-Type' => 'application/json'));
}
if ($e instanceof \Exception_BadRequest) {
return new Response('Bad Request', 400);
}
if ($e instanceof \Exception_NotFound) {
return new Response('Not Found', 404);
}
if ($e instanceof \Exception_Forbidden) {
return new Response('Not Found', 403);
}
});
return $app;
}); });
$app->mount('/UserPreferences/', new Controller\UserPreferences());
$app->mount('/query/', new Controller\Query());
$app->mount('/baskets', new Controller\Basket());
$app->mount('/story', new Controller\Story());
$app->mount('/WorkZone', new Controller\WorkZone());
$app->mount('/lists', new Controller\UsrLists());
$app->mount('/MustacheLoader', new Controller\MustacheLoader());
$app->mount('/records/edit', new Controller\Edit());
$app->mount('/records/movecollection', new Controller\MoveCollection());
$app->mount('/bridge/', new Controller\Bridge());
$app->mount('/push/', new Controller\Push());
$app->mount('/printer/', new Controller\Printer());
$app->mount('/TOU/', new Controller\TOU());
$app->mount('/feeds', new Controller\Feed());
$app->mount('/tooltip', new Controller\Tooltip());
$app->mount('/language', new Controller\Language());
$app->mount('/tools/', new Controller\Tools());
$app->mount('/', new Controller\Root());
$app->error(function (\Exception $e, $code) use ($app)
{
/* @var $request \Symfony\Component\HttpFoundation\Request */
$request = $app['request'];
if ($e instanceof \Bridge_Exception)
{
$params = array(
'message' => $e->getMessage()
, 'file' => $e->getFile()
, 'line' => $e->getLine()
, 'r_method' => $request->getMethod()
, 'r_action' => $request->getRequestUri()
, 'r_parameters' => ($request->getMethod() == 'GET' ? array() : $request->request->all())
);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
if ($e instanceof \Bridge_Exception_ApiConnectorNotConfigured)
{
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/notconfigured.twig', $params), 200);
}
elseif ($e instanceof \Bridge_Exception_ApiConnectorNotConnected)
{
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/disconnected.twig', $params), 200);
}
elseif ($e instanceof \Bridge_Exception_ApiConnectorAccessTokenFailed)
{
$params = array_merge($params, array('account' => $app['current_account']));
return new response($twig->render('/prod/actions/Bridge/disconnected.twig', $params), 200);
}
elseif ($e instanceof \Bridge_Exception_ApiDisabled)
{
$params = array_merge($params, array('api' => $e->get_api()));
return new response($twig->render('/prod/actions/Bridge/deactivated.twig', $params), 200);
}
return new response($twig->render('/prod/actions/Bridge/error.twig', $params), 200);
}
if ($request->getRequestFormat() == 'json')
{
$datas = array(
'success' => false
, 'message' => $e->getMessage()
);
$json = $app['Core']['Serializer']->serialize($datas, 'json');
return new Response($json, 200, array('Content-Type' => 'application/json'));
}
if ($e instanceof \Exception_BadRequest)
{
return new Response('Bad Request', 400);
}
if ($e instanceof \Exception_NotFound)
{
return new Response('Not Found', 404);
}
if ($e instanceof \Exception_Forbidden)
{
return new Response('Not Found', 403);
}
});
return $app;
});

View File

@@ -23,58 +23,48 @@ use Alchemy\Phrasea\Controller\Root as Controller;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func(function() return call_user_func(function() {
{ $app = new \Silex\Application();
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore(); $app['Core'] = \bootstrap::getCore();
if (!\setup::is_installed()) if ( ! \setup::is_installed()) {
{ $response = new \Symfony\Component\HttpFoundation\RedirectResponse('/setup/');
$response = new \Symfony\Component\HttpFoundation\RedirectResponse('/setup/');
return $response->send(); return $response->send();
} }
$app->get('/', function() use ($app) $app->get('/', function() use ($app) {
{ $browser = \Browser::getInstance();
$browser = \Browser::getInstance(); if ($browser->isMobile())
if ($browser->isMobile()) return $app->redirect("/login/?redirect=/lightbox");
elseif ($browser->isNewGeneration())
return $app->redirect("/login/?redirect=/prod");
else
return $app->redirect("/login/?redirect=/client");
});
return $app->redirect("/login/?redirect=/lightbox"); $app->get('/robots.txt', function() use ($app) {
elseif ($browser->isNewGeneration()) $appbox = \appbox::get_instance($app['Core']);
return $app->redirect("/login/?redirect=/prod"); $registry = $appbox->get_registry();
else
return $app->redirect("/login/?redirect=/client"); if ($registry->get('GV_allow_search_engine') === true) {
}); $buffer = "User-Agent: *\n"
. "Allow: /\n";
} else {
$buffer = "User-Agent: *\n"
. "Disallow: /\n";
}
$app->get('/robots.txt', function() use ($app) $response = new Response($buffer, 200, array('Content-Type' => 'text/plain'));
{ $response->setCharset('UTF-8');
$appbox = \appbox::get_instance($app['Core']);
$registry = $appbox->get_registry(); return $response;
});
if ($registry->get('GV_allow_search_engine') === true) $app->mount('/feeds/', new Controller\RSSFeeds());
{
$buffer = "User-Agent: *\n"
. "Allow: /\n";
}
else
{
$buffer = "User-Agent: *\n"
. "Disallow: /\n";
}
$response = new Response($buffer, 200, array('Content-Type' => 'text/plain')); return $app;
$response->setCharset('UTF-8'); }
return $response;
});
$app->mount('/feeds/', new Controller\RSSFeeds());
return $app;
}
); );

View File

@@ -22,72 +22,59 @@ use Alchemy\Phrasea\Controller\Utils as ControllerUtils;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
return call_user_func(function() return call_user_func(function() {
{ $app = new \Silex\Application();
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore(); $app['Core'] = \bootstrap::getCore();
$app['install'] = false; $app['install'] = false;
$app['upgrade'] = false; $app['upgrade'] = false;
$app->before(function($a) use ($app) $app->before(function($a) use ($app) {
{ if (\setup::is_installed()) {
if (\setup::is_installed()) $appbox = \appbox::get_instance($app['Core']);
{
$appbox = \appbox::get_instance($app['Core']);
if (!$appbox->need_major_upgrade()) if ( ! $appbox->need_major_upgrade()) {
{ throw new \Exception_Setup_PhraseaAlreadyInstalled();
throw new \Exception_Setup_PhraseaAlreadyInstalled(); }
}
$app['upgrade'] = true; $app['upgrade'] = true;
} } elseif (\setup::needUpgradeConfigurationFile()) {
elseif (\setup::needUpgradeConfigurationFile()) $connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
{ $configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
$connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
$configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
$configuration = \Alchemy\Phrasea\Core\Configuration::build(); $configuration = \Alchemy\Phrasea\Core\Configuration::build();
$configuration->upgradeFromOldConf($configInc, $connexionInc); $configuration->upgradeFromOldConf($configInc, $connexionInc);
$app['install'] = true; $app['install'] = true;
} } else {
else $app['install'] = true;
{ }
$app['install'] = true;
}
return; return;
});
$app->get('/', function() use ($app) {
if ($app['install'] === true)
return $app->redirect('/setup/installer/');
if ($app['upgrade'] === true)
return $app->redirect('/setup/upgrader/');
});
$app->mount('/installer/', new Controller\Installer());
$app->mount('/upgrader/', new Controller\Upgrader());
$app->mount('/test', new ControllerUtils\PathFileTest());
$app->mount('/connection_test', new ControllerUtils\ConnectionTest());
$app->error(function($e) use ($app) {
if ($e instanceof \Exception_Setup_PhraseaAlreadyInstalled) {
return $app->redirect('/login/');
}
return new Response('Internal Server Error', 500);
});
return $app;
}); });
$app->get('/', function() use ($app)
{
if ($app['install'] === true)
return $app->redirect('/setup/installer/');
if ($app['upgrade'] === true)
return $app->redirect('/setup/upgrader/');
});
$app->mount('/installer/', new Controller\Installer());
$app->mount('/upgrader/', new Controller\Upgrader());
$app->mount('/test', new ControllerUtils\PathFileTest());
$app->mount('/connection_test', new ControllerUtils\ConnectionTest());
$app->error(function($e) use ($app)
{
if ($e instanceof \Exception_Setup_PhraseaAlreadyInstalled)
{
return $app->redirect('/login/');
}
return new Response('Internal Server Error', 500);
});
return $app;
});

View File

@@ -22,29 +22,26 @@ use Doctrine\Common\Cache\ApcCache as DoctrineApc;
class ApcCache extends DoctrineApc implements Cache class ApcCache extends DoctrineApc implements Cache
{ {
public function isServer() public function isServer()
{
return false;
}
public function get($key)
{
if (!$this->contains($key))
{ {
throw new Exception('Unable to retrieve the value'); return false;
} }
return $this->fetch($key); public function get($key)
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
{ {
$this->delete($id); if ( ! $this->contains($key)) {
throw new Exception('Unable to retrieve the value');
}
return $this->fetch($key);
} }
return $this; public function deleteMulti(array $array_keys)
} {
foreach ($array_keys as $id) {
$this->delete($id);
}
return $this;
}
} }

View File

@@ -22,30 +22,27 @@ use Doctrine\Common\Cache\ArrayCache as DoctrineArray;
class ArrayCache extends DoctrineArray implements Cache class ArrayCache extends DoctrineArray implements Cache
{ {
public function isServer() public function isServer()
{
return false;
}
public function get($id)
{
if (!$this->contains($id))
{ {
throw new Exception(sprintf('Unable to find key %s', $id));
return false;
} }
return $this->fetch($id); public function get($id)
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
{ {
$this->delete($id); if ( ! $this->contains($id)) {
throw new Exception(sprintf('Unable to find key %s', $id));
}
return $this->fetch($id);
} }
return; public function deleteMulti(array $array_keys)
} {
foreach ($array_keys as $id) {
$this->delete($id);
}
return;
}
} }

View File

@@ -22,10 +22,9 @@ use Doctrine\Common\Cache\Cache as DoctrineCache;
interface Cache extends DoctrineCache interface Cache extends DoctrineCache
{ {
public function isServer(); public function isServer();
public function get($key); public function get($key);
public function deleteMulti(array $array_keys);
public function deleteMulti(array $array_keys);
} }

View File

@@ -22,100 +22,92 @@ use \Alchemy\Phrasea\Core\Service\Builder,
*/ */
class Manager class Manager
{ {
/**
*
* @var \SplFileObject
*/
protected $cacheFile;
protected $core;
/** /**
* *
* @var \SplFileObject * @var \Alchemy\Phrasea\Core\Configuration\Parser
*/ */
protected $cacheFile; protected $parser;
protected $core;
/** /**
* *
* @var \Alchemy\Phrasea\Core\Configuration\Parser * @var array
*/ */
protected $parser; protected $registry = array();
/** public function __construct(Core $core, \SplFileObject $file)
*
* @var array
*/
protected $registry = array();
public function __construct(Core $core, \SplFileObject $file)
{
$this->cacheFile = $file;
$this->parser = new \Symfony\Component\Yaml\Yaml();
$this->core = $core;
$this->registry = $this->parser->parse($file) ? : array();
}
protected function exists($name)
{
return isset($this->registry[$name]);
}
public function flushAll()
{
foreach ($this->registry as $cacheKey => $service_name)
{ {
$this->get($cacheKey, $service_name)->getDriver()->flushAll(); $this->cacheFile = $file;
$this->parser = new \Symfony\Component\Yaml\Yaml();
$this->core = $core;
$this->registry = $this->parser->parse($file) ? : array();
} }
file_put_contents($this->cacheFile->getPathname(), ''); protected function exists($name)
return $this;
}
public function get($cacheKey, $service_name)
{
try
{ {
$configuration = $this->core->getConfiguration()->getService($service_name); return isset($this->registry[$name]);
$service = Builder::create($this->core, $configuration);
$driver = $service->getDriver();
$write = true;
}
catch (\Exception $e)
{
$configuration = new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag(
array('type' => 'Cache\\ArrayCache')
);
$service = Builder::create($this->core, $configuration);
$driver = $service->getDriver();
$write = false;
} }
if ($this->hasChange($cacheKey, $service_name)) public function flushAll()
{ {
$service->getDriver()->flushAll(); foreach ($this->registry as $cacheKey => $service_name) {
if ($write) $this->get($cacheKey, $service_name)->getDriver()->flushAll();
{ }
$this->registry[$cacheKey] = $service_name;
$this->save($cacheKey, $service_name); file_put_contents($this->cacheFile->getPathname(), '');
}
return $this;
} }
return $service; public function get($cacheKey, $service_name)
} {
try {
$configuration = $this->core->getConfiguration()->getService($service_name);
$service = Builder::create($this->core, $configuration);
$driver = $service->getDriver();
$write = true;
} catch (\Exception $e) {
$configuration = new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag(
array('type' => 'Cache\\ArrayCache')
);
$service = Builder::create($this->core, $configuration);
$driver = $service->getDriver();
$write = false;
}
protected function hasChange($name, $driver) if ($this->hasChange($cacheKey, $service_name)) {
{ $service->getDriver()->flushAll();
return $this->exists($name) ? $this->registry[$name] !== $driver : true; if ($write) {
} $this->registry[$cacheKey] = $service_name;
$this->save($cacheKey, $service_name);
}
}
protected function save($name, $driver) return $service;
{ }
$date = new \DateTime();
$this->registry[$name] = $driver; protected function hasChange($name, $driver)
{
return $this->exists($name) ? $this->registry[$name] !== $driver : true;
}
$datas = sprintf("#LastUpdate: %s\n", $date->format(DATE_ISO8601)) protected function save($name, $driver)
{
$date = new \DateTime();
$this->registry[$name] = $driver;
$datas = sprintf("#LastUpdate: %s\n", $date->format(DATE_ISO8601))
. $this->parser->dump($this->registry, 6); . $this->parser->dump($this->registry, 6);
file_put_contents($this->cacheFile->getPathname(), $datas); file_put_contents($this->cacheFile->getPathname(), $datas);
} }
} }

View File

@@ -22,29 +22,26 @@ use \Doctrine\Common\Cache\MemcacheCache as DoctrineMemcache;
class MemcacheCache extends DoctrineMemcache implements Cache class MemcacheCache extends DoctrineMemcache implements Cache
{ {
public function isServer() public function isServer()
{
return true;
}
public function get($key)
{
if (!$this->contains($key))
{ {
throw new Exception('Unable to retrieve the value'); return true;
} }
return $this->fetch($key); public function get($key)
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
{ {
$this->delete($id); if ( ! $this->contains($key)) {
throw new Exception('Unable to retrieve the value');
}
return $this->fetch($key);
} }
return $this; public function deleteMulti(array $array_keys)
} {
foreach ($array_keys as $id) {
$this->delete($id);
}
return $this;
}
} }

View File

@@ -21,110 +21,103 @@ use Doctrine\Common\Cache\CacheProvider;
*/ */
class RedisCache extends CacheProvider class RedisCache extends CacheProvider
{ {
/**
* @var \Redis
*/
private $_redis;
/** /**
* @var \Redis * Sets the redis instance to use.
*/ *
private $_redis; * @param Redis $memcache
*/
/** public function setRedis(\Redis $redis)
* Sets the redis instance to use.
*
* @param Redis $memcache
*/
public function setRedis(\Redis $redis)
{
$this->_redis = $redis;
}
/**
* Gets the memcache instance used by the cache.
*
* @return Memcache
*/
public function getRedis()
{
return $this->_redis;
}
/**
* {@inheritdoc}
*/
protected function doFetch($id)
{
return $this->_redis->get($id);
}
/**
* {@inheritdoc}
*/
protected function doContains($id)
{
return (bool) $this->_redis->get($id);
}
/**
* {@inheritdoc}
*/
protected function doSave($id, $data, $lifeTime = 0)
{
if (0 === $lifeTime)
{ {
return $this->_redis->set($id, $data); $this->_redis = $redis;
}
else
{
return $this->_redis->setex($id, $lifeTime, $data);
}
}
/**
* {@inheritdoc}
*/
protected function doDelete($id)
{
return $this->_redis->delete($id);
}
/**
* {@inheritdoc}
*/
protected function doFlush()
{
return $this->_redis->flushAll();
}
/**
* {@inheritdoc}
*/
protected function doGetStats()
{
return $this->_redis->info();
}
public function isServer()
{
return true;
}
public function get($key)
{
if (!$this->contains($key))
{
throw new Exception('Unable to retrieve the value');
} }
return $this->fetch($key); /**
} * Gets the memcache instance used by the cache.
*
public function deleteMulti(array $array_keys) * @return Memcache
{ */
foreach ($array_keys as $id) public function getRedis()
{ {
$this->delete($id); return $this->_redis;
} }
return $this; /**
} * {@inheritdoc}
*/
protected function doFetch($id)
{
return $this->_redis->get($id);
}
/**
* {@inheritdoc}
*/
protected function doContains($id)
{
return (bool) $this->_redis->get($id);
}
/**
* {@inheritdoc}
*/
protected function doSave($id, $data, $lifeTime = 0)
{
if (0 === $lifeTime) {
return $this->_redis->set($id, $data);
} else {
return $this->_redis->setex($id, $lifeTime, $data);
}
}
/**
* {@inheritdoc}
*/
protected function doDelete($id)
{
return $this->_redis->delete($id);
}
/**
* {@inheritdoc}
*/
protected function doFlush()
{
return $this->_redis->flushAll();
}
/**
* {@inheritdoc}
*/
protected function doGetStats()
{
return $this->_redis->info();
}
public function isServer()
{
return true;
}
public function get($key)
{
if ( ! $this->contains($key)) {
throw new Exception('Unable to retrieve the value');
}
return $this->fetch($key);
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id) {
$this->delete($id);
}
return $this;
}
} }

View File

@@ -22,29 +22,26 @@ use Doctrine\Common\Cache\XcacheCache as DoctrineXcache;
class XcacheCache extends DoctrineXcache implements Cache class XcacheCache extends DoctrineXcache implements Cache
{ {
public function isServer() public function isServer()
{
return false;
}
public function get($key)
{
if (!$this->contains($key))
{ {
throw new Exception('Unable to retrieve the value'); return false;
} }
return $this->fetch($key); public function get($key)
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
{ {
$this->delete($id); if ( ! $this->contains($key)) {
throw new Exception('Unable to retrieve the value');
}
return $this->fetch($key);
} }
return $this; public function deleteMulti(array $array_keys)
} {
foreach ($array_keys as $id) {
$this->delete($id);
}
return $this;
}
} }

View File

@@ -29,150 +29,127 @@ use Silex\ControllerCollection;
class Description implements ControllerProviderInterface class Description implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/{sbas_id}/', function(Application $app, $sbas_id) $controllers->post('/{sbas_id}/', function(Application $app, $sbas_id) {
{ $Core = $app['Core'];
$Core = $app['Core']; $user = $Core->getAuthenticatedUser();
$user = $Core->getAuthenticatedUser();
$request = $app['request']; $request = $app['request'];
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct')) if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct')) {
{ throw new \Exception_Forbidden('You are not allowed to access this zone');
throw new \Exception_Forbidden('You are not allowed to access this zone');
}
$databox = \databox::get_instance((int) $sbas_id);
$fields = $databox->get_meta_structure();
$available_fields = \databox::get_available_metadatas();
$available_dc_fields = $databox->get_available_dcfields();
$databox->get_connection()->beginTransaction();
$error = false;
try
{
if (is_array($request->get('field_ids')))
{
foreach ($request->get('field_ids') as $id)
{
try
{
$field = \databox_field::get_instance($databox, $id);
$field->set_name($request->get('name_' . $id));
$field->set_thumbtitle($request->get('thumbtitle_' . $id));
$field->set_source($request->get('src_' . $id));
$field->set_multi($request->get('multi_' . $id));
$field->set_business($request->get('business_' . $id));
$field->set_indexable($request->get('indexable_' . $id));
$field->set_required($request->get('required_' . $id));
$field->set_separator($request->get('separator_' . $id));
$field->set_readonly($request->get('readonly_' . $id));
$field->set_type($request->get('type_' . $id));
$field->set_tbranch($request->get('tbranch_' . $id));
$field->set_report($request->get('report_' . $id));
$field->setVocabularyControl(null);
$field->setVocabularyRestricted(false);
try
{
$vocabulary = \Alchemy\Phrasea\Vocabulary\Controller::get($request->get('vocabulary_' . $id));
$field->setVocabularyControl($vocabulary);
$field->setVocabularyRestricted($request->get('vocabularyrestricted_' . $id));
}
catch (\Exception $e)
{
}
$dces_element = null;
$class = 'databox_Field_DCES_' . $request->get('dces_' . $id);
if (class_exists($class))
$dces_element = new $class();
$field->set_dces_element($dces_element);
$field->save();
}
catch (\Exception $e)
{
continue;
}
}
} }
if ($request->get('newfield')) $databox = \databox::get_instance((int) $sbas_id);
{ $fields = $databox->get_meta_structure();
$field = \databox_field::create($databox, $request->get('newfield')); $available_fields = \databox::get_available_metadatas();
$available_dc_fields = $databox->get_available_dcfields();
$databox->get_connection()->beginTransaction();
$error = false;
try {
if (is_array($request->get('field_ids'))) {
foreach ($request->get('field_ids') as $id) {
try {
$field = \databox_field::get_instance($databox, $id);
$field->set_name($request->get('name_' . $id));
$field->set_thumbtitle($request->get('thumbtitle_' . $id));
$field->set_source($request->get('src_' . $id));
$field->set_multi($request->get('multi_' . $id));
$field->set_business($request->get('business_' . $id));
$field->set_indexable($request->get('indexable_' . $id));
$field->set_required($request->get('required_' . $id));
$field->set_separator($request->get('separator_' . $id));
$field->set_readonly($request->get('readonly_' . $id));
$field->set_type($request->get('type_' . $id));
$field->set_tbranch($request->get('tbranch_' . $id));
$field->set_report($request->get('report_' . $id));
$field->setVocabularyControl(null);
$field->setVocabularyRestricted(false);
try {
$vocabulary = \Alchemy\Phrasea\Vocabulary\Controller::get($request->get('vocabulary_' . $id));
$field->setVocabularyControl($vocabulary);
$field->setVocabularyRestricted($request->get('vocabularyrestricted_' . $id));
} catch (\Exception $e) {
}
$dces_element = null;
$class = 'databox_Field_DCES_' . $request->get('dces_' . $id);
if (class_exists($class))
$dces_element = new $class();
$field->set_dces_element($dces_element);
$field->save();
} catch (\Exception $e) {
continue;
}
}
}
if ($request->get('newfield')) {
$field = \databox_field::create($databox, $request->get('newfield'));
}
if (is_array($request->get('todelete_ids'))) {
foreach ($request->get('todelete_ids') as $id) {
try {
$field = \databox_field::get_instance($databox, $id);
$field->delete();
} catch (\Exception $e) {
}
}
}
} catch (\Exception $e) {
$error = true;
} }
if (is_array($request->get('todelete_ids'))) if ($error)
{ $databox->get_connection()->rollBack();
foreach ($request->get('todelete_ids') as $id) else
{ $databox->get_connection()->commit();
try
{
$field = \databox_field::get_instance($databox, $id);
$field->delete();
}
catch (\Exception $e)
{
} return new RedirectResponse('/admin/description/' . $sbas_id . '/');
}
}
}
catch (\Exception $e)
{
$error = true;
}
if ($error)
$databox->get_connection()->rollBack();
else
$databox->get_connection()->commit();
return new RedirectResponse('/admin/description/' . $sbas_id . '/');
})->assert('sbas_id', '\d+'); })->assert('sbas_id', '\d+');
$controllers->get('/{sbas_id}/', function(Application $app, $sbas_id) $controllers->get('/{sbas_id}/', function(Application $app, $sbas_id) {
{
$Core = $app['Core']; $Core = $app['Core'];
$user = $Core->getAuthenticatedUser(); $user = $Core->getAuthenticatedUser();
$request = $app['request']; $request = $app['request'];
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct')) if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct')) {
{ throw new \Exception_Forbidden('You are not allowed to access this zone');
throw new \Exception_Forbidden('You are not allowed to access this zone'); }
}
$databox = \databox::get_instance((int) $sbas_id); $databox = \databox::get_instance((int) $sbas_id);
$fields = $databox->get_meta_structure(); $fields = $databox->get_meta_structure();
$available_fields = \databox::get_available_metadatas(); $available_fields = \databox::get_available_metadatas();
$available_dc_fields = $databox->get_available_dcfields(); $available_dc_fields = $databox->get_available_dcfields();
$params = array( $params = array(
'databox' => $databox, 'databox' => $databox,
'fields' => $fields, 'fields' => $fields,
'available_fields' => $available_fields, 'available_fields' => $available_fields,
'available_dc_fields' => $available_dc_fields, 'available_dc_fields' => $available_dc_fields,
'vocabularies' => \Alchemy\Phrasea\Vocabulary\Controller::getAvailable(), 'vocabularies' => \Alchemy\Phrasea\Vocabulary\Controller::getAvailable(),
); );
return new Response($Core->getTwig()->render('admin/databox/doc_structure.twig', $params)); return new Response($Core->getTwig()->render('admin/databox/doc_structure.twig', $params));
})->assert('sbas_id', '\d+'); })->assert('sbas_id', '\d+');
return $controllers; return $controllers;
} }
} }

View File

@@ -28,56 +28,53 @@ use Silex\ControllerCollection;
class Fields implements ControllerProviderInterface class Fields implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/checkmulti/', function() use ($app, $appbox) $controllers->get('/checkmulti/', function() use ($app, $appbox) {
{ $request = $app['request'];
$request = $app['request'];
$multi = ($request->get('multi') === 'true'); $multi = ($request->get('multi') === 'true');
$metadata = \databox_field::load_class_from_xpath($request->get('source')); $metadata = \databox_field::load_class_from_xpath($request->get('source'));
$datas = array( $datas = array(
'result' => ($multi === $metadata->is_multi()) 'result' => ($multi === $metadata->is_multi())
, 'is_multi' => $metadata->is_multi() , 'is_multi' => $metadata->is_multi()
); );
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize($datas, 'json') $Serializer->serialize($datas, 'json')
, 200 , 200
, array('Content-Type' => 'application/json') , array('Content-Type' => 'application/json')
); );
}); });
$controllers->get('/checkreadonly/', function() use ($app, $appbox) $controllers->get('/checkreadonly/', function() use ($app, $appbox) {
{ $request = $app['request'];
$request = $app['request']; $readonly = ($request->get('readonly') === 'true');
$readonly = ($request->get('readonly') === 'true');
$metadata = \databox_field::load_class_from_xpath($request->get('source')); $metadata = \databox_field::load_class_from_xpath($request->get('source'));
$datas = array( $datas = array(
'result' => ($readonly === $metadata->is_readonly()) 'result' => ($readonly === $metadata->is_readonly())
, 'is_readonly' => $metadata->is_readonly() , 'is_readonly' => $metadata->is_readonly()
); );
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize($datas, 'json') $Serializer->serialize($datas, 'json')
, 200 , 200
, array('Content-Type' => 'application/json') , array('Content-Type' => 'application/json')
); );
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -28,178 +28,153 @@ use Silex\ControllerCollection;
class Publications implements ControllerProviderInterface class Publications implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$session = $appbox->get_session(); $session = $appbox->get_session();
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/list/', function() use ($app, $appbox) $controllers->get('/list/', function() use ($app, $appbox) {
{ $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $feeds = \Feed_Collection::load_all($appbox, $user);
$feeds = \Feed_Collection::load_all($appbox, $user);
$template = 'admin/publications/list.html'; $template = 'admin/publications/list.html';
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render($template, array('feeds' => $feeds)); return $twig->render($template, array('feeds' => $feeds));
}); });
$controllers->post('/create/', function() use ($app, $appbox) $controllers->post('/create/', function() use ($app, $appbox) {
{
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$request = $app['request']; $request = $app['request'];
$feed = \Feed_Adapter::create($appbox, $user, $request->get('title'), $request->get('subtitle')); $feed = \Feed_Adapter::create($appbox, $user, $request->get('title'), $request->get('subtitle'));
if ($request->get('public') == '1') if ($request->get('public') == '1')
$feed->set_public(true); $feed->set_public(true);
elseif ($request->get('base_id')) elseif ($request->get('base_id'))
$feed->set_collection(\collection::get_from_base_id($request->get('base_id'))); $feed->set_collection(\collection::get_from_base_id($request->get('base_id')));
return $app->redirect('/admin/publications/list/'); return $app->redirect('/admin/publications/list/');
}); });
$controllers->get('/feed/{id}/', function($id) use ($app, $appbox) $controllers->get('/feed/{id}/', function($id) use ($app, $appbox) {
{
$feed = new \Feed_Adapter($appbox, $id);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render('admin/publications/fiche.html'
, array(
'feed' => $feed
, 'error' => $app['request']->get('error')
)
);
})->assert('id', '\d+');
$controllers->post('/feed/{id}/update/', function($id) use ($app, $appbox)
{
$feed = new \Feed_Adapter($appbox, $id);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
if (!$feed->is_owner($user))
return $app->redirect('/admin/publications/feed/' . $id . '/?error=' . _('You are not the owner of this feed, you can not edit it'));
$request = $app['request'];
try
{
$collection = \collection::get_from_base_id($request->get('base_id'));
}
catch (\Exception $e)
{
$collection = null;
}
$feed->set_title($request->get('title'));
$feed->set_subtitle($request->get('subtitle'));
$feed->set_collection($collection);
$feed->set_public($request->get('public'));
return $app->redirect('/admin/publications/list/');
})->assert('id', '\d+');
$controllers->post('/feed/{id}/iconupload/', function($id) use ($app, $appbox)
{
$feed = new \Feed_Adapter($appbox, $id);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
if (!$feed->is_owner($user))
return new Response('ERROR:you are not allowed');
$request = $app["request"];
$fileData = $request->files->get("Filedata");
if ($fileData['error'] !== 0)
return new Response('ERROR:error while upload');
$file = new \system_file($fileData['tmp_name']);
if (!in_array($file->get_mime(), array('image/jpeg', 'image/jpg', 'image/gif')))
return new Response('ERROR:bad filetype');
if ($file->getSize() > 200000)
return new Response('ERROR:file too large');
$datas = $file->get_technical_datas();
if (!isset($datas[\system_file::TC_DATAS_WIDTH]) || !isset($datas[\system_file::TC_DATAS_HEIGHT]))
return new Response('ERROR:file is not square');
if ($datas[\system_file::TC_DATAS_WIDTH] != $datas[\system_file::TC_DATAS_HEIGHT])
return new Response('ERROR:file is not square');
$feed->set_icon($file);
unlink($file->getPathname());
return new Response('FILEHREF:' . $feed->get_icon_url() . '?' . mt_rand(100000, 999999));
})->assert('id', '\d+');
$controllers->post('/feed/{id}/addpublisher/', function($id) use ($app, $appbox)
{
$error = '';
try
{
$request = $app['request'];
$user = \User_Adapter::getInstance($request->get('usr_id'), $appbox);
$feed = new \Feed_Adapter($appbox, $id); $feed = new \Feed_Adapter($appbox, $id);
$feed->add_publisher($user);
}
catch (\Exception $e)
{
$error = $e->getMessage();
}
return $app->redirect('/admin/publications/feed/' . $id . '/?err=' . $error); /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render('admin/publications/fiche.html'
, array(
'feed' => $feed
, 'error' => $app['request']->get('error')
)
);
})->assert('id', '\d+'); })->assert('id', '\d+');
$controllers->post('/feed/{id}/removepublisher/', function($id) use ($app, $appbox) $controllers->post('/feed/{id}/update/', function($id) use ($app, $appbox) {
{
try
{
$request = $app['request'];
$feed = new \Feed_Adapter($appbox, $id); $feed = new \Feed_Adapter($appbox, $id);
$publisher = new \Feed_Publisher_Adapter($appbox, $request->get('publisher_id')); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$user = $publisher->get_user();
if ($feed->is_publisher($user) === true && $feed->is_owner($user) === false)
$publisher->delete();
}
catch (\Exception $e)
{
$error = $e->getMessage();
}
return $app->redirect('/admin/publications/feed/' . $id . '/?err=' . $error); if ( ! $feed->is_owner($user))
return $app->redirect('/admin/publications/feed/' . $id . '/?error=' . _('You are not the owner of this feed, you can not edit it'));
$request = $app['request'];
try {
$collection = \collection::get_from_base_id($request->get('base_id'));
} catch (\Exception $e) {
$collection = null;
}
$feed->set_title($request->get('title'));
$feed->set_subtitle($request->get('subtitle'));
$feed->set_collection($collection);
$feed->set_public($request->get('public'));
return $app->redirect('/admin/publications/list/');
})->assert('id', '\d+'); })->assert('id', '\d+');
$controllers->post('/feed/{id}/delete/', function($id) use ($app, $appbox)
{
$feed = new \Feed_Adapter($appbox, $id);
$feed->delete();
return $app->redirect('/admin/publications/list/'); $controllers->post('/feed/{id}/iconupload/', function($id) use ($app, $appbox) {
$feed = new \Feed_Adapter($appbox, $id);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
if ( ! $feed->is_owner($user))
return new Response('ERROR:you are not allowed');
$request = $app["request"];
$fileData = $request->files->get("Filedata");
if ($fileData['error'] !== 0)
return new Response('ERROR:error while upload');
$file = new \system_file($fileData['tmp_name']);
if ( ! in_array($file->get_mime(), array('image/jpeg', 'image/jpg', 'image/gif')))
return new Response('ERROR:bad filetype');
if ($file->getSize() > 200000)
return new Response('ERROR:file too large');
$datas = $file->get_technical_datas();
if ( ! isset($datas[\system_file::TC_DATAS_WIDTH]) || ! isset($datas[\system_file::TC_DATAS_HEIGHT]))
return new Response('ERROR:file is not square');
if ($datas[\system_file::TC_DATAS_WIDTH] != $datas[\system_file::TC_DATAS_HEIGHT])
return new Response('ERROR:file is not square');
$feed->set_icon($file);
unlink($file->getPathname());
return new Response('FILEHREF:' . $feed->get_icon_url() . '?' . mt_rand(100000, 999999));
})->assert('id', '\d+'); })->assert('id', '\d+');
return $controllers; $controllers->post('/feed/{id}/addpublisher/', function($id) use ($app, $appbox) {
} $error = '';
try {
$request = $app['request'];
$user = \User_Adapter::getInstance($request->get('usr_id'), $appbox);
$feed = new \Feed_Adapter($appbox, $id);
$feed->add_publisher($user);
} catch (\Exception $e) {
$error = $e->getMessage();
}
return $app->redirect('/admin/publications/feed/' . $id . '/?err=' . $error);
})->assert('id', '\d+');
$controllers->post('/feed/{id}/removepublisher/', function($id) use ($app, $appbox) {
try {
$request = $app['request'];
$feed = new \Feed_Adapter($appbox, $id);
$publisher = new \Feed_Publisher_Adapter($appbox, $request->get('publisher_id'));
$user = $publisher->get_user();
if ($feed->is_publisher($user) === true && $feed->is_owner($user) === false)
$publisher->delete();
} catch (\Exception $e) {
$error = $e->getMessage();
}
return $app->redirect('/admin/publications/feed/' . $id . '/?err=' . $error);
})->assert('id', '\d+');
$controllers->post('/feed/{id}/delete/', function($id) use ($app, $appbox) {
$feed = new \Feed_Adapter($appbox, $id);
$feed->delete();
return $app->redirect('/admin/publications/list/');
})->assert('id', '\d+');
return $controllers;
}
} }

View File

@@ -33,82 +33,74 @@ use Silex\ControllerCollection;
class Root implements ControllerProviderInterface class Root implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function(Application $app, Request $request) $controllers->get('/', function(Application $app, Request $request) {
{
$Core = $app['Core']; $Core = $app['Core'];
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$user = $Core->getAuthenticatedUser(); $user = $Core->getAuthenticatedUser();
\User_Adapter::updateClientInfos(3); \User_Adapter::updateClientInfos(3);
$section = $request->get('section', false); $section = $request->get('section', false);
$available = array( $available = array(
'connected' 'connected'
, 'registrations' , 'registrations'
, 'taskmanager' , 'taskmanager'
, 'base' , 'base'
, 'bases' , 'bases'
, 'collection' , 'collection'
, 'user' , 'user'
, 'users' , 'users'
); );
$feature = 'connected'; $feature = 'connected';
$featured = false; $featured = false;
$position = explode(':', $section); $position = explode(':', $section);
if (count($position) > 0) if (count($position) > 0) {
{ if (in_array($position[0], $available)) {
if (in_array($position[0], $available)) $feature = $position[0];
{ if (isset($position[1]))
$feature = $position[0]; $featured = $position[1];
if (isset($position[1])) }
$featured = $position[1];
} }
}
$databoxes = $off_databoxes = array(); $databoxes = $off_databoxes = array();
foreach ($appbox->get_databoxes() as $databox) foreach ($appbox->get_databoxes() as $databox) {
{ try {
try if ( ! $user->ACL()->has_access_to_sbas($databox->get_sbas_id()))
{ continue;
if (!$user->ACL()->has_access_to_sbas($databox->get_sbas_id()))
continue;
$connbas = $databox->get_connection(); $connbas = $databox->get_connection();
} catch (\Exception $e) {
$off_databoxes[] = $databox;
continue;
}
$databoxes[] = $databox;
} }
catch (\Exception $e)
{
$off_databoxes[] = $databox;
continue;
}
$databoxes[] = $databox;
}
$twig = $Core->getTwig(); $twig = $Core->getTwig();
return new Response($twig->render('admin/index.html.twig', array( return new Response($twig->render('admin/index.html.twig', array(
'module' => 'admin' 'module' => 'admin'
, 'events' => \eventsmanager_broker::getInstance($appbox, $Core) , 'events' => \eventsmanager_broker::getInstance($appbox, $Core)
, 'module_name' => 'Admin' , 'module_name' => 'Admin'
, 'notice' => $request->get("notice") , 'notice' => $request->get("notice")
, 'feature' => $feature , 'feature' => $feature
, 'featured' => $featured , 'featured' => $featured
, 'databoxes' => $databoxes , 'databoxes' => $databoxes
, 'off_databoxes' => $off_databoxes , 'off_databoxes' => $off_databoxes
, 'tree' => \module_admin::getTree($section) , 'tree' => \module_admin::getTree($section)
)) ))
); );
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -29,109 +29,95 @@ use Silex\ControllerCollection;
class Subdefs implements ControllerProviderInterface class Subdefs implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/{sbas_id}/', function(Application $app, $sbas_id) $controllers->get('/{sbas_id}/', function(Application $app, $sbas_id) {
{ $databox = \databox::get_instance((int) $sbas_id);
$databox = \databox::get_instance((int) $sbas_id);
return new response($app['Core']->getTwig()->render( return new response($app['Core']->getTwig()->render(
'admin/subdefs.twig', array( 'admin/subdefs.twig', array(
'databox' => $databox, 'databox' => $databox,
'subdefs' => $databox->get_subdef_structure() 'subdefs' => $databox->get_subdef_structure()
) )
) )
); );
})->assert('sbas_id', '\d+'); })->assert('sbas_id', '\d+');
$controllers->post('/{sbas_id}/', function(Application $app, Request $request, $sbas_id) $controllers->post('/{sbas_id}/', function(Application $app, Request $request, $sbas_id) {
{ $delete_subdef = $request->get('delete_subdef');
$delete_subdef = $request->get('delete_subdef'); $toadd_subdef = $request->get('add_subdef');
$toadd_subdef = $request->get('add_subdef'); $Parmsubdefs = $request->get('subdefs', array());
$Parmsubdefs = $request->get('subdefs', array());
$databox = \databox::get_instance((int) $sbas_id); $databox = \databox::get_instance((int) $sbas_id);
$add_subdef = array('class' => null, 'name' => null, 'group' => null); $add_subdef = array('class' => null, 'name' => null, 'group' => null);
foreach ($add_subdef as $k => $v) foreach ($add_subdef as $k => $v) {
{ if ( ! isset($toadd_subdef[$k]) || trim($toadd_subdef[$k]) === '')
if (!isset($toadd_subdef[$k]) || trim($toadd_subdef[$k]) === '') unset($add_subdef[$k]);
unset($add_subdef[$k]); else
else $add_subdef[$k] = $toadd_subdef[$k];
$add_subdef[$k] = $toadd_subdef[$k];
}
if ($delete_subdef)
{
$delete_subef = explode('_', $delete_subdef);
$group = $delete_subef[0];
$name = $delete_subef[1];
$subdefs = $databox->get_subdef_structure();
$subdefs->delete_subdef($group, $name);
}
elseif (count($add_subdef) === 3)
{
$subdefs = $databox->get_subdef_structure();
$UnicodeProcessor = new \unicode();
$group = $add_subdef['group'];
$name = $UnicodeProcessor->remove_nonazAZ09($add_subdef['name'], false);
$class = $add_subdef['class'];
$subdefs->add_subdef($group, $name, $class);
}
else
{
$subdefs = $databox->get_subdef_structure();
$options = array();
foreach ($Parmsubdefs as $post_sub)
{
$post_sub_ex = explode('_', $post_sub);
$group = $post_sub_ex[0];
$name = $post_sub_ex[1];
$class = $request->get($post_sub . '_class');
$downloadable = $request->get($post_sub . '_downloadable');
$defaults = array('path', 'baseurl', 'meta', 'mediatype');
foreach ($defaults as $def)
{
$parm_loc = $request->get($post_sub . '_' . $def);
if ($def == 'meta' && !$parm_loc)
{
$parm_loc = "no";
}
$options[$def] = $parm_loc;
}
$mediatype = $request->get($post_sub . '_mediatype');
$media = $request->get($post_sub . '_' . $mediatype, array());
foreach ($media as $option => $value)
{
if ($option == 'resolution' && $mediatype == 'image')
{
$option = 'dpi';
}
$options[$option] = $value;
}
$subdefs->set_subdef($group, $name, $class, $downloadable, $options);
} }
}
return new RedirectResponse('/admin/subdefs/' . $databox->get_sbas_id() . '/'); if ($delete_subdef) {
$delete_subef = explode('_', $delete_subdef);
$group = $delete_subef[0];
$name = $delete_subef[1];
$subdefs = $databox->get_subdef_structure();
$subdefs->delete_subdef($group, $name);
} elseif (count($add_subdef) === 3) {
$subdefs = $databox->get_subdef_structure();
$UnicodeProcessor = new \unicode();
$group = $add_subdef['group'];
$name = $UnicodeProcessor->remove_nonazAZ09($add_subdef['name'], false);
$class = $add_subdef['class'];
$subdefs->add_subdef($group, $name, $class);
} else {
$subdefs = $databox->get_subdef_structure();
$options = array();
foreach ($Parmsubdefs as $post_sub) {
$post_sub_ex = explode('_', $post_sub);
$group = $post_sub_ex[0];
$name = $post_sub_ex[1];
$class = $request->get($post_sub . '_class');
$downloadable = $request->get($post_sub . '_downloadable');
$defaults = array('path', 'baseurl', 'meta', 'mediatype');
foreach ($defaults as $def) {
$parm_loc = $request->get($post_sub . '_' . $def);
if ($def == 'meta' && ! $parm_loc) {
$parm_loc = "no";
}
$options[$def] = $parm_loc;
}
$mediatype = $request->get($post_sub . '_mediatype');
$media = $request->get($post_sub . '_' . $mediatype, array());
foreach ($media as $option => $value) {
if ($option == 'resolution' && $mediatype == 'image') {
$option = 'dpi';
}
$options[$option] = $value;
}
$subdefs->set_subdef($group, $name, $class, $downloadable, $options);
}
}
return new RedirectResponse('/admin/subdefs/' . $databox->get_sbas_id() . '/');
})->assert('sbas_id', '\d+'); })->assert('sbas_id', '\d+');
return $controllers; return $controllers;
} }
} }

View File

@@ -30,420 +30,384 @@ use Alchemy\Phrasea\Helper\User as UserHelper;
class Users implements ControllerProviderInterface class Users implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/rights/', function(Application $app) $controllers->post('/rights/', function(Application $app) {
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_users_rights());
}
);
$controllers->get('/rights/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_users_rights());
}
);
$controllers->post('/rights/reset/', function(Application $app, Request $request)
{
try
{
$core = $app['Core'];
$datas = array('error' => false);
$helper = new UserHelper\Edit($core, $request);
$helper->resetRights();
}
catch (\Exception $e)
{
$datas['error'] = true;
$datas['message'] = $e->getMessage();
}
return new Response(
$core->getSerializer()->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
}
);
$controllers->post('/delete/', function(Application $app)
{
$module = new UserHelper\Edit($app['Core'], $app['request']);
$module->delete_users();
return $app->redirect('/admin/users/search/');
}
);
$controllers->post('/rights/apply/', function(Application $app)
{
$datas = array('error' => true);
try
{
$rights = new UserHelper\Edit($app['Core'], $app['request']); $rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_rights();
if ($app['request']->get('template')) $template = 'admin/editusers.twig';
{ /* @var $twig \Twig_Environment */
$rights->apply_template(); $twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_users_rights());
}
);
$controllers->get('/rights/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_users_rights());
}
);
$controllers->post('/rights/reset/', function(Application $app, Request $request) {
try {
$core = $app['Core'];
$datas = array('error' => false);
$helper = new UserHelper\Edit($core, $request);
$helper->resetRights();
} catch (\Exception $e) {
$datas['error'] = true;
$datas['message'] = $e->getMessage();
} }
$rights->apply_infos(); return new Response(
$core->getSerializer()->serialize($datas, 'json')
$datas = array('error' => false); , 200
} , array('Content-Type' => 'application/json')
catch (\Exception $e)
{
$datas['message'] = $e->getMessage();
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
}
);
$controllers->post('/rights/quotas/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers_quotas.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_quotas());
}
);
$controllers->post('/rights/quotas/apply/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_quotas();
return;
}
);
$controllers->post('/rights/time/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers_timelimit.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_time());
}
);
$controllers->post('/rights/time/apply/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_time();
return;
}
);
$controllers->post('/rights/masks/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers_masks.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_masks());
}
);
$controllers->post('/rights/masks/apply/', function(Application $app)
{
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_masks();
return;
}
);
$controllers->match('/search/', function(Application $app)
{
$users = new UserHelper\Manage($app['Core'], $app['request']);
$template = 'admin/users.html';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $users->search());
}
);
$controllers->post('/search/export/', function() use ($app)
{
$request = $app['request'];
$users = new UserHelper\Manage($app['Core'], $app['request']);
$template = 'admin/users.html';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$userTable = array(
array(
'ID',
'Login',
'Last Name',
'First Name',
'E-Mail',
'Created',
'Updated',
'Address',
'City',
'Zip',
'Country',
'Phone',
'Fax',
'Job',
'Company',
'Position'
)
);
foreach ($users->export() as $user)
{
/* @var $user \User_Adapter */
$userTable[] = array(
$user->get_id(),
$user->get_login(),
$user->get_lastname(),
$user->get_firstname(),
$user->get_email(),
$user->get_creation_date()->format(DATE_ATOM),
$user->get_modification_date()->format(DATE_ATOM),
$user->get_address(),
$user->get_city(),
$user->get_zipcode(),
$user->get_country(),
$user->get_tel(),
$user->get_fax(),
$user->get_job(),
$user->get_company(),
$user->get_position()
); );
}
$CSVDatas = \format::arr_to_csv($userTable);
$response = new Response($CSVDatas, 200, array('Content-Type' => 'text/plain'));
$response->headers->set('Content-Disposition', 'attachment; filename=export.txt');
return $response;
} }
); );
$controllers->post('/apply_template/', function() use ($app) $controllers->post('/delete/', function(Application $app) {
{ $module = new UserHelper\Edit($app['Core'], $app['request']);
$users = new UserHelper\Edit($app['Core'], $app['request']); $module->delete_users();
$users->apply_template(); return $app->redirect('/admin/users/search/');
return new RedirectResponse('/admin/users/search/');
} }
); );
$controllers->get('/typeahead/search/', function(Application $app) use ($appbox) $controllers->post('/rights/apply/', function(Application $app) {
{ $datas = array('error' => true);
$request = $app['request'];
$user_query = new \User_Query($appbox); try {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_rights();
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); if ($app['request']->get('template')) {
$rights->apply_template();
}
$like_value = $request->get('term'); $rights->apply_infos();
$rights = $request->get('filter_rights') ? : array();
$have_right = $request->get('have_right') ? : array();
$have_not_right = $request->get('have_not_right') ? : array();
$on_base = $request->get('on_base') ? : array();
$datas = array('error' => false);
} catch (\Exception $e) {
$datas['message'] = $e->getMessage();
}
$elligible_users = $user_query $Serializer = $app['Core']['Serializer'];
->on_sbas_where_i_am($user->ACL(), $rights)
->like(\User_Query::LIKE_EMAIL, $like_value)
->like(\User_Query::LIKE_FIRSTNAME, $like_value)
->like(\User_Query::LIKE_LASTNAME, $like_value)
->like(\User_Query::LIKE_LOGIN, $like_value)
->like_match(\User_Query::LIKE_MATCH_OR)
->who_have_right($have_right)
->who_have_not_right($have_not_right)
->on_base_ids($on_base)
->execute()
->get_results();
$datas = array(); return new Response(
$Serializer->serialize($datas, 'json')
foreach ($elligible_users as $user) , 200
{ , array('Content-Type' => 'application/json')
$datas[] = array(
'email' => $user->get_email() ? : ''
, 'login' => $user->get_login() ? : ''
, 'name' => $user->get_display_name() ? : ''
, 'id' => $user->get_id()
); );
} }
);
$Serializer = $app['Core']['Serializer']; $controllers->post('/rights/quotas/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
return new Response( $template = 'admin/editusers_quotas.twig';
$Serializer->serialize($datas, 'json') /* @var $twig \Twig_Environment */
, 200 $twig = $app['Core']->getTwig();
, array('Content-type' => 'application/json')
); return $twig->render($template, $rights->get_quotas());
}
);
$controllers->post('/rights/quotas/apply/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_quotas();
return;
}
);
$controllers->post('/rights/time/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers_timelimit.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_time());
}
);
$controllers->post('/rights/time/apply/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_time();
return;
}
);
$controllers->post('/rights/masks/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$template = 'admin/editusers_masks.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $rights->get_masks());
}
);
$controllers->post('/rights/masks/apply/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_masks();
return;
}
);
$controllers->match('/search/', function(Application $app) {
$users = new UserHelper\Manage($app['Core'], $app['request']);
$template = 'admin/users.html';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return $twig->render($template, $users->search());
}
);
$controllers->post('/search/export/', function() use ($app) {
$request = $app['request'];
$users = new UserHelper\Manage($app['Core'], $app['request']);
$template = 'admin/users.html';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$userTable = array(
array(
'ID',
'Login',
'Last Name',
'First Name',
'E-Mail',
'Created',
'Updated',
'Address',
'City',
'Zip',
'Country',
'Phone',
'Fax',
'Job',
'Company',
'Position'
)
);
foreach ($users->export() as $user) {
/* @var $user \User_Adapter */
$userTable[] = array(
$user->get_id(),
$user->get_login(),
$user->get_lastname(),
$user->get_firstname(),
$user->get_email(),
$user->get_creation_date()->format(DATE_ATOM),
$user->get_modification_date()->format(DATE_ATOM),
$user->get_address(),
$user->get_city(),
$user->get_zipcode(),
$user->get_country(),
$user->get_tel(),
$user->get_fax(),
$user->get_job(),
$user->get_company(),
$user->get_position()
);
}
$CSVDatas = \format::arr_to_csv($userTable);
$response = new Response($CSVDatas, 200, array('Content-Type' => 'text/plain'));
$response->headers->set('Content-Disposition', 'attachment; filename=export.txt');
return $response;
}
);
$controllers->post('/apply_template/', function() use ($app) {
$users = new UserHelper\Edit($app['Core'], $app['request']);
$users->apply_template();
return new RedirectResponse('/admin/users/search/');
}
);
$controllers->get('/typeahead/search/', function(Application $app) use ($appbox) {
$request = $app['request'];
$user_query = new \User_Query($appbox);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$like_value = $request->get('term');
$rights = $request->get('filter_rights') ? : array();
$have_right = $request->get('have_right') ? : array();
$have_not_right = $request->get('have_not_right') ? : array();
$on_base = $request->get('on_base') ? : array();
$elligible_users = $user_query
->on_sbas_where_i_am($user->ACL(), $rights)
->like(\User_Query::LIKE_EMAIL, $like_value)
->like(\User_Query::LIKE_FIRSTNAME, $like_value)
->like(\User_Query::LIKE_LASTNAME, $like_value)
->like(\User_Query::LIKE_LOGIN, $like_value)
->like_match(\User_Query::LIKE_MATCH_OR)
->who_have_right($have_right)
->who_have_not_right($have_not_right)
->on_base_ids($on_base)
->execute()
->get_results();
$datas = array();
foreach ($elligible_users as $user) {
$datas[] = array(
'email' => $user->get_email() ? : ''
, 'login' => $user->get_login() ? : ''
, 'name' => $user->get_display_name() ? : ''
, 'id' => $user->get_id()
);
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-type' => 'application/json')
);
}); });
$controllers->post('/create/', function(Application $app) $controllers->post('/create/', function(Application $app) {
{
$datas = array('error' => false, 'message' => '', 'data' => null); $datas = array('error' => false, 'message' => '', 'data' => null);
try try {
{ $request = $app['request'];
$module = new UserHelper\Manage($app['Core'], $app['request']);
if ($request->get('template') == '1') {
$user = $module->create_template();
} else {
$user = $module->create_newuser();
}
if ( ! ($user instanceof \User_Adapter))
throw new \Exception('Unknown error');
$datas['data'] = $user->get_id();
} catch (\Exception $e) {
$datas['error'] = true;
$datas['message'] = $e->getMessage();
}
$Serializer = $app['Core']['Serializer'];
return new Response($Serializer->serialize($datas, 'json'), 200, array("Content-Type" => "application/json"));
}
);
$controllers->post('/export/csv/', function(Application $app) use ($appbox) {
$request = $app['request']; $request = $app['request'];
$module = new UserHelper\Manage($app['Core'], $app['request']); $user_query = new \User_Query($appbox, $app['Core']);
if ($request->get('template') == '1')
{
$user = $module->create_template();
}
else
{
$user = $module->create_newuser();
}
if (!($user instanceof \User_Adapter))
throw new \Exception('Unknown error');
$datas['data'] = $user->get_id(); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
} $like_value = $request->get('like_value');
catch (\Exception $e) $like_field = $request->get('like_field');
{ $on_base = $request->get('base_id') ? : null;
$datas['error'] = true; $on_sbas = $request->get('sbas_id') ? : null;
$datas['message'] = $e->getMessage();
}
$Serializer = $app['Core']['Serializer']; $elligible_users = $user_query->on_bases_where_i_am($user->ACL(), array('canadmin'))
->like($like_field, $like_value)
->on_base_ids($on_base)
->on_sbas_ids($on_sbas);
return new Response($Serializer->serialize($datas, 'json'), 200, array("Content-Type" => "application/json")); $offset = 0;
$geoname = new \geonames();
$buffer = array();
$buffer[] = array(
'ID'
, 'Login'
, _('admin::compte-utilisateur nom')
, _('admin::compte-utilisateur prenom')
, _('admin::compte-utilisateur email')
, 'CreationDate'
, 'ModificationDate'
, _('admin::compte-utilisateur adresse')
, _('admin::compte-utilisateur ville')
, _('admin::compte-utilisateur code postal')
, _('admin::compte-utilisateur pays')
, _('admin::compte-utilisateur telephone')
, _('admin::compte-utilisateur fax')
, _('admin::compte-utilisateur poste')
, _('admin::compte-utilisateur societe')
, _('admin::compte-utilisateur activite')
);
do {
$elligible_users->limit($offset, 20);
$offset += 20;
$results = $elligible_users->execute()->get_results();
foreach ($results as $user) {
$buffer[] = array(
$user->get_id()
, $user->get_login()
, $user->get_lastname()
, $user->get_firstname()
, $user->get_email()
, \phraseadate::format_mysql($user->get_creation_date())
, \phraseadate::format_mysql($user->get_modification_date())
, $user->get_address()
, $user->get_city()
, $user->get_zipcode()
, $geoname->get_country($user->get_geonameid())
, $user->get_tel()
, $user->get_fax()
, $user->get_job()
, $user->get_company()
, $user->get_position()
);
}
} while (count($results) > 0);
$out = \format::arr_to_csv($buffer);
$headers = array(
'Content-type' => 'text/csv'
, 'Content-Disposition' => 'attachment; filename=export.txt'
);
$response = new Response($out, 200, $headers);
$response->setCharset('UTF-8');
return $response;
} }
); );
$controllers->post('/export/csv/', function(Application $app) use ($appbox)
{
$request = $app['request'];
$user_query = new \User_Query($appbox, $app['Core']);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$like_value = $request->get('like_value');
$like_field = $request->get('like_field');
$on_base = $request->get('base_id') ? : null;
$on_sbas = $request->get('sbas_id') ? : null;
$elligible_users = $user_query->on_bases_where_i_am($user->ACL(), array('canadmin'))
->like($like_field, $like_value)
->on_base_ids($on_base)
->on_sbas_ids($on_sbas);
$offset = 0;
$geoname = new \geonames();
$buffer = array();
$buffer[] = array(
'ID'
, 'Login'
, _('admin::compte-utilisateur nom')
, _('admin::compte-utilisateur prenom')
, _('admin::compte-utilisateur email')
, 'CreationDate'
, 'ModificationDate'
, _('admin::compte-utilisateur adresse')
, _('admin::compte-utilisateur ville')
, _('admin::compte-utilisateur code postal')
, _('admin::compte-utilisateur pays')
, _('admin::compte-utilisateur telephone')
, _('admin::compte-utilisateur fax')
, _('admin::compte-utilisateur poste')
, _('admin::compte-utilisateur societe')
, _('admin::compte-utilisateur activite')
);
do
{
$elligible_users->limit($offset, 20);
$offset += 20;
$results = $elligible_users->execute()->get_results();
foreach ($results as $user)
{
$buffer[] = array(
$user->get_id()
, $user->get_login()
, $user->get_lastname()
, $user->get_firstname()
, $user->get_email()
, \phraseadate::format_mysql($user->get_creation_date())
, \phraseadate::format_mysql($user->get_modification_date())
, $user->get_address()
, $user->get_city()
, $user->get_zipcode()
, $geoname->get_country($user->get_geonameid())
, $user->get_tel()
, $user->get_fax()
, $user->get_job()
, $user->get_company()
, $user->get_position()
);
}
}
while (count($results) > 0);
$out = \format::arr_to_csv($buffer);
$headers = array(
'Content-type' => 'text/csv'
, 'Content-Disposition' => 'attachment; filename=export.txt'
);
$response = new Response($out, 200, $headers);
$response->setCharset('UTF-8');
return $response;
}
);
return $controllers;
}
return $controllers;
}
} }

View File

@@ -8,7 +8,9 @@
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Alchemy\Phrasea\Controller; namespace Alchemy\Phrasea\Controller;
/** /**
* *
* @package * @package

View File

@@ -31,538 +31,481 @@ use Alchemy\Phrasea\RouteProcessor\Basket as BasketRoute,
class Basket implements ControllerProviderInterface class Basket implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
/**
* This route is used to create a Basket
*
* @params name : title (mandatory)
* @params desc : description (optionnal)
* @params lst : Phraseanet serialized record list (optionnal)
*
* @accept JSON / YAML
*
*/
$controllers->post('/', function(Application $app)
{
$request = $app['request'];
/* @var $request \Symfony\Component\HttpFoundation\Request */
$em = $app['Core']->getEntityManager();
$user = $app['Core']->getAuthenticatedUser();
$Basket = new \Entities\Basket();
$Basket->setName($request->get('name', ''));
$Basket->setOwner($app['Core']->getAuthenticatedUser());
$Basket->setDescription($request->get('desc'));
$em->persist($Basket);
$n = 0;
foreach (explode(';', $request->get('lst')) as $sbas_rec)
{
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2)
continue;
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
if (!$user->ACL()->has_access_to_base($record->get_base_id())
&& !$user->ACL()->has_hd_grant($record)
&& !$user->ACL()->has_preview_grant($record))
{
continue;
}
if ($Basket->hasRecord($record))
continue;
$basket_element = new \Entities\BasketElement();
$basket_element->setRecord($record);
$basket_element->setBasket($Basket);
$em->persist($basket_element);
$Basket->addBasketElement($basket_element);
$n++;
}
$em->flush();
if ($request->getRequestFormat() == 'json')
{
$data = array(
'success' => true
, 'message' => _('Basket created')
, 'basket' => array(
'id' => $Basket->getId()
)
);
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse(sprintf('/%d/', $Basket->getId()));
}
});
/**
* This route is used to delete a basket
*
* @accept JSON / HTML
*
*/
$controllers->post('/{basket_id}/delete/', function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$em->remove($basket);
$em->flush();
$data = array(
'success' => true
, 'message' => _('Basket has been deleted')
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
* Removes a BasketElement
*/
$controllers->post(
'/{basket_id}/delete/{basket_element_id}/'
, function(Application $app, Request $request, $basket_id, $basket_element_id)
{
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
foreach ($basket->getElements() as $basket_element)
{
/* @var $basket_element \Entities\BasketElement */
if ($basket_element->getId() == $basket_element_id)
{
$em->remove($basket_element);
}
}
$em->flush();
$data = array(
'success' => true
, 'message' => _('Record removed from basket')
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+')->assert('basket_element_id', '\d+');
/**
* Update name and description of a basket
*
* @param name string mandatory
* @param description string optionnal
*
*/
$controllers->post('/{basket_id}/update/', function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$basket->setName($request->get('name', ''));
$basket->setDescription($request->get('description'));
$em->merge($basket);
$em->flush();
$data = array(
'success' => true
, 'message' => _('Basket has been updated')
, 'basket' => array('id' => $basket->getId())
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
* Get the form to update the Basket attributes (name and description)
*/
$controllers->get('/{basket_id}/update/', function(Application $app, $basket_id)
{
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'prod/Baskets/Update.html.twig'
, array('basket' => $basket)
)
);
})->assert('basket_id', '\d+');
/**
* Get the Basket reorder form
*/
$controllers->get(
'/{basket_id}/reorder/'
, function(Application $app, $basket_id)
{
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'prod/Baskets/Reorder.html.twig'
, array('basket' => $basket)
)
);
})->assert('basket_id', '\d+');
$controllers->post(
'/{basket_id}/reorder/'
, function(Application $app, $basket_id)
{
$ret = array('success' => false, 'message' => _('An error occured'));
try
{
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$order = $app['request']->get('element');
/* @var $basket \Entities\Basket */
foreach ($basket->getElements() as $basketElement)
{
if (isset($order[$basketElement->getId()]))
{
$basketElement->setOrd($order[$basketElement->getId()]);
$em->merge($basketElement);
}
}
$em->flush();
$ret = array('success' => true, 'message' => _('Basket updated'));
}
catch (\Exception $e)
{
}
$Serializer = $app['Core']['Serializer'];
return new Response($Serializer->serialize($ret, 'json'), 200, array('Content-type' => 'application/json'));
})->assert('basket_id', '\d+');
/**
* Toggle the status of a Basket
*
* @param acrhive : 0|1 (mandatory)
*
* @returns JSON / HTML
*/
$controllers->post('/{basket_id}/archive/', function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$archive_status = !!$request->get('archive');
$basket->setArchived($archive_status);
$em->merge($basket); /**
$em->flush(); * This route is used to create a Basket
*
* @params name : title (mandatory)
* @params desc : description (optionnal)
* @params lst : Phraseanet serialized record list (optionnal)
*
* @accept JSON / YAML
*
*/
$controllers->post('/', function(Application $app) {
$request = $app['request'];
if ($archive_status) /* @var $request \Symfony\Component\HttpFoundation\Request */
{
$message = _('Basket has been archived');
}
else
{
$message = _('Basket has been unarchived');
}
$data = array(
'success' => true
, 'archive' => $archive_status
, 'message' => $message
);
if ($request->getRequestFormat() == 'json') $em = $app['Core']->getEntityManager();
{
$datas = $app['Core']['Serializer']->serialize($data, 'json'); $user = $app['Core']->getAuthenticatedUser();
return new Response($datas, 200, array('Content-type' => 'application/json')); $Basket = new \Entities\Basket();
}
else
{
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/** $Basket->setName($request->get('name', ''));
* Add a BasketElement to a basket $Basket->setOwner($app['Core']->getAuthenticatedUser());
*/ $Basket->setDescription($request->get('desc'));
$controllers->post(
'/{basket_id}/addElements/'
, function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket') $em->persist($Basket);
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$user = $app['Core']->getAuthenticatedUser(); $n = 0;
/* @var $user \User_Adapter */
$n = 0; foreach (explode(';', $request->get('lst')) as $sbas_rec) {
$sbas_rec = explode('_', $sbas_rec);
foreach (explode(';', $request->get('lst')) as $sbas_rec) if (count($sbas_rec) !== 2)
{ continue;
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2) $record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
continue;
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]); if ( ! $user->ACL()->has_access_to_base($record->get_base_id())
&& ! $user->ACL()->has_hd_grant($record)
&& ! $user->ACL()->has_preview_grant($record)) {
continue;
}
if (!$user->ACL()->has_access_to_base($record->get_base_id()) if ($Basket->hasRecord($record))
&& !$user->ACL()->has_hd_grant($record) continue;
&& !$user->ACL()->has_preview_grant($record))
{ $basket_element = new \Entities\BasketElement();
continue; $basket_element->setRecord($record);
} $basket_element->setBasket($Basket);
if ($basket->hasRecord($record)) $em->persist($basket_element);
continue;
$Basket->addBasketElement($basket_element);
$n ++;
}
$em->flush();
if ($request->getRequestFormat() == 'json') {
$data = array(
'success' => true
, 'message' => _('Basket created')
, 'basket' => array(
'id' => $Basket->getId()
)
);
$datas = $app['Core']['Serializer']->serialize($data, 'json');
$basket_element = new \Entities\BasketElement(); return new Response($datas, 200, array('Content-type' => 'application/json'));
$basket_element->setRecord($record); } else {
$basket_element->setBasket($basket); return new RedirectResponse(sprintf('/%d/', $Basket->getId()));
}
$em->persist($basket_element); });
$basket->addBasketElement($basket_element); /**
* This route is used to delete a basket
*
* @accept JSON / HTML
*
*/
$controllers->post('/{basket_id}/delete/', function(Application $app, Request $request, $basket_id) {
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$em->remove($basket);
$em->flush();
$data = array(
'success' => true
, 'message' => _('Basket has been deleted')
);
if ($request->getRequestFormat() == 'json') {
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
* Removes a BasketElement
*/
$controllers->post(
'/{basket_id}/delete/{basket_element_id}/'
, function(Application $app, Request $request, $basket_id, $basket_element_id) {
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
if(null !== $validationSession = $basket->getValidation()) $basket = $em->getRepository('\Entities\Basket')
{ ->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$participants = $validationSession->getParticipants(); foreach ($basket->getElements() as $basket_element) {
/* @var $basket_element \Entities\BasketElement */
foreach($participants as $participant) if ($basket_element->getId() == $basket_element_id) {
{ $em->remove($basket_element);
$validationData = new \Entities\ValidationData(); }
$validationData->setParticipant($participant); }
$validationData->setBasketElement($basket_element);
$em->flush();
$em->persist($validationData);
} $data = array(
} 'success' => true
, 'message' => _('Record removed from basket')
$n++; );
}
if ($request->getRequestFormat() == 'json') {
$em->flush(); $datas = $app['Core']['Serializer']->serialize($data, 'json');
$data = array( return new Response($datas, 200, array('Content-type' => 'application/json'));
'success' => true } else {
, 'message' => sprintf(_('%d records added'), $n) return new RedirectResponse('/');
); }
})->assert('basket_id', '\d+')->assert('basket_element_id', '\d+');
if ($request->getRequestFormat() == 'json')
{ /**
* Update name and description of a basket
$datas = $app['Core']['Serializer']->serialize($data, 'json'); *
* @param name string mandatory
return new Response($datas, 200, array('Content-type' => 'application/json')); * @param description string optionnal
} *
else */
{ $controllers->post('/{basket_id}/update/', function(Application $app, Request $request, $basket_id) {
return new RedirectResponse('/'); $em = $app['Core']->getEntityManager();
}
})->assert('basket_id', '\d+'); $basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$basket->setName($request->get('name', ''));
$basket->setDescription($request->get('description'));
/**
* $em->merge($basket);
* Move Basket element from a basket to another $em->flush();
*
* @params elements Array : list of basket element id $data = array(
* 'success' => true
*/ , 'message' => _('Basket has been updated')
$controllers->post( , 'basket' => array('id' => $basket->getId())
'/{basket_id}/stealElements/' );
, function(Application $app, Request $request, $basket_id)
{ if ($request->getRequestFormat() == 'json') {
$em = $app['Core']->getEntityManager();
$datas = $app['Core']['Serializer']->serialize($data, 'json');
/* @var $em \Doctrine\ORM\EntityManager */
$basket = $em->getRepository('\Entities\Basket') return new Response($datas, 200, array('Content-type' => 'application/json'));
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true); } else {
return new RedirectResponse('/');
$user = $app['Core']->getAuthenticatedUser(); }
/* @var $user \User_Adapter */ })->assert('basket_id', '\d+');
$n = 0; /**
* Get the form to update the Basket attributes (name and description)
*/
$controllers->get('/{basket_id}/update/', function(Application $app, $basket_id) {
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'prod/Baskets/Update.html.twig'
, array('basket' => $basket)
)
);
})->assert('basket_id', '\d+');
/**
* Get the Basket reorder form
*/
$controllers->get(
'/{basket_id}/reorder/'
, function(Application $app, $basket_id) {
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'prod/Baskets/Reorder.html.twig'
, array('basket' => $basket)
)
);
})->assert('basket_id', '\d+');
foreach ($request->get('elements') as $bask_element_id)
{
try
{
$basket_element = $em->getRepository('\Entities\BasketElement')
->findUserElement($bask_element_id, $user);
}
catch (\Exception $e)
{
continue;
}
$basket_element->setBasket($basket);
$basket->addBasketElement($basket_element);
$n++;
}
$em->flush();
$data = array(
'success' => true
, 'message' => sprintf(_('%d records moved'), $n)
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
* Get basket creation form
*/
$controllers->get('/create/', function(Application $app)
{
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response($twig->render('prod/Baskets/Create.html.twig', array()));
});
/**
* Get a basket
*/
$controllers->get('/{basket_id}/', function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
if ($basket->getIsRead() === false)
{
$basket->setIsRead(true);
$em->flush();
}
if ($basket->getValidation())
{
if ($basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->getIsAware() === false)
{
$basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->setIsAware(true);
$em->flush();
}
}
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$params = array(
'basket' => $basket,
'ordre' => $request->get('order')
);
$html = $twig->render('prod/WorkZone/Basket.html.twig', $params);
return new Response($html);
})->assert('basket_id', '\d+');
return $controllers;
}
$controllers->post(
'/{basket_id}/reorder/'
, function(Application $app, $basket_id) {
$ret = array('success' => false, 'message' => _('An error occured'));
try {
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$order = $app['request']->get('element');
/* @var $basket \Entities\Basket */
foreach ($basket->getElements() as $basketElement) {
if (isset($order[$basketElement->getId()])) {
$basketElement->setOrd($order[$basketElement->getId()]);
$em->merge($basketElement);
}
}
$em->flush();
$ret = array('success' => true, 'message' => _('Basket updated'));
} catch (\Exception $e) {
}
$Serializer = $app['Core']['Serializer'];
return new Response($Serializer->serialize($ret, 'json'), 200, array('Content-type' => 'application/json'));
})->assert('basket_id', '\d+');
/**
* Toggle the status of a Basket
*
* @param acrhive : 0|1 (mandatory)
*
* @returns JSON / HTML
*/
$controllers->post('/{basket_id}/archive/', function(Application $app, Request $request, $basket_id) {
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$archive_status = ! ! $request->get('archive');
$basket->setArchived($archive_status);
$em->merge($basket);
$em->flush();
if ($archive_status) {
$message = _('Basket has been archived');
} else {
$message = _('Basket has been unarchived');
}
$data = array(
'success' => true
, 'archive' => $archive_status
, 'message' => $message
);
if ($request->getRequestFormat() == 'json') {
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
* Add a BasketElement to a basket
*/
$controllers->post(
'/{basket_id}/addElements/'
, function(Application $app, Request $request, $basket_id) {
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$user = $app['Core']->getAuthenticatedUser();
/* @var $user \User_Adapter */
$n = 0;
foreach (explode(';', $request->get('lst')) as $sbas_rec) {
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2)
continue;
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
if ( ! $user->ACL()->has_access_to_base($record->get_base_id())
&& ! $user->ACL()->has_hd_grant($record)
&& ! $user->ACL()->has_preview_grant($record)) {
continue;
}
if ($basket->hasRecord($record))
continue;
$basket_element = new \Entities\BasketElement();
$basket_element->setRecord($record);
$basket_element->setBasket($basket);
$em->persist($basket_element);
$basket->addBasketElement($basket_element);
if (null !== $validationSession = $basket->getValidation()) {
$participants = $validationSession->getParticipants();
foreach ($participants as $participant) {
$validationData = new \Entities\ValidationData();
$validationData->setParticipant($participant);
$validationData->setBasketElement($basket_element);
$em->persist($validationData);
}
}
$n ++;
}
$em->flush();
$data = array(
'success' => true
, 'message' => sprintf(_('%d records added'), $n)
);
if ($request->getRequestFormat() == 'json') {
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
*
* Move Basket element from a basket to another
*
* @params elements Array : list of basket element id
*
*/
$controllers->post(
'/{basket_id}/stealElements/'
, function(Application $app, Request $request, $basket_id) {
$em = $app['Core']->getEntityManager();
/* @var $em \Doctrine\ORM\EntityManager */
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$user = $app['Core']->getAuthenticatedUser();
/* @var $user \User_Adapter */
$n = 0;
foreach ($request->get('elements') as $bask_element_id) {
try {
$basket_element = $em->getRepository('\Entities\BasketElement')
->findUserElement($bask_element_id, $user);
} catch (\Exception $e) {
continue;
}
$basket_element->setBasket($basket);
$basket->addBasketElement($basket_element);
$n ++;
}
$em->flush();
$data = array(
'success' => true
, 'message' => sprintf(_('%d records moved'), $n)
);
if ($request->getRequestFormat() == 'json') {
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
/**
* Get basket creation form
*/
$controllers->get('/create/', function(Application $app) {
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response($twig->render('prod/Baskets/Create.html.twig', array()));
});
/**
* Get a basket
*/
$controllers->get('/{basket_id}/', function(Application $app, Request $request, $basket_id) {
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
if ($basket->getIsRead() === false) {
$basket->setIsRead(true);
$em->flush();
}
if ($basket->getValidation()) {
if ($basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->getIsAware() === false) {
$basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->setIsAware(true);
$em->flush();
}
}
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$params = array(
'basket' => $basket,
'ordre' => $request->get('order')
);
$html = $twig->render('prod/WorkZone/Basket.html.twig', $params);
return new Response($html);
})->assert('basket_id', '\d+');
return $controllers;
}
} }

View File

@@ -29,466 +29,419 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class Bridge implements ControllerProviderInterface class Bridge implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
$app['require_connection'] = $app->protect(function(\Bridge_Account $account) use ($app) $app['require_connection'] = $app->protect(function(\Bridge_Account $account) use ($app) {
{ $app['current_account'] = function() use ($account) {
$app['current_account'] = function() use ($account)
{
return $account; return $account;
}; };
if (!$account->get_api()->get_connector()->is_configured()) if ( ! $account->get_api()->get_connector()->is_configured())
throw new \Bridge_Exception_ApiConnectorNotConfigured("Bridge API Connector is not configured"); throw new \Bridge_Exception_ApiConnectorNotConfigured("Bridge API Connector is not configured");
if (!$account->get_api()->get_connector()->is_connected()) if ( ! $account->get_api()->get_connector()->is_connected())
throw new \Bridge_Exception_ApiConnectorNotConnected("Bridge API Connector is not connected"); throw new \Bridge_Exception_ApiConnectorNotConnected("Bridge API Connector is not connected");
return; return;
}); });
$controllers->post('/manager/' $controllers->post('/manager/'
, function(Application $app) use ($twig) , function(Application $app) use ($twig) {
{ $route = new RecordHelper\Bridge($app['Core'], $app['request']);
$route = new RecordHelper\Bridge($app['Core'], $app['request']);
$appbox = \appbox::get_instance($app['Core']);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$params = array(
'user_accounts' => \Bridge_Account::get_accounts_by_user($appbox, $user)
, 'available_apis' => \Bridge_Api::get_availables($appbox)
, 'route' => $route
, 'current_account_id' => ''
);
return new Response($twig->render('prod/actions/Bridge/index.twig', $params)
);
});
$controllers->get('/login/{api_name}/', function($api_name) use ($app, $twig)
{
$appbox = \appbox::get_instance($app['Core']);
$connector = \Bridge_Api::get_connector_by_name($appbox->get_registry(), $api_name);
return $app->redirect($connector->get_auth_url());
});
$controllers->get('/callback/{api_name}/', function($api_name) use ($app, $twig)
{
$error_message = '';
try
{
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$api = \Bridge_Api::get_by_api_name($appbox, $api_name);
$connector = $api->get_connector();
$response = $connector->connect();
$user_id = $connector->get_user_id();
try
{
$account = \Bridge_Account::load_account_from_distant_id($appbox, $api, $user, $user_id);
}
catch (\Bridge_Exception_AccountNotFound $e)
{
$account = \Bridge_Account::create($appbox, $api, $user, $user_id, $connector->get_user_name());
}
$settings = $account->get_settings();
if (isset($response['auth_token']))
$settings->set('auth_token', $response['auth_token']);
if (isset($response['refresh_token']))
$settings->set('refresh_token', $response['refresh_token']);
$connector->set_auth_settings($settings);
$connector->reconnect();
}
catch (\Exception $e)
{
$error_message = $e->getMessage();
}
$params = array('error_message' => $error_message);
return new Response($twig->render('prod/actions/Bridge/callback.twig', $params));
});
$controllers->get('/adapter/{account_id}/logout/'
, function($account_id) use ($app, $twig)
{
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$account->get_api()->get_connector()->disconnect();
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-elements/' . $account->get_api()->get_connector()->get_default_element_type() . '/');
})->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-records/'
, function($account_id) use ($app, $twig)
{
$page = max((int) $app['request']->get('page'), 0);
$quantity = 10;
$offset_start = max(($page - 1) * $quantity, 0);
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$elements = \Bridge_Element::get_elements_by_account($appbox, $account, $offset_start, $quantity);
$app['require_connection']($account);
$params = array(
'adapter_action' => 'load-records'
, 'account' => $account
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
return new Response($twig->render('prod/actions/Bridge/records_list.twig', $params));
})
->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-elements/{type}/'
, function($account_id, $type) use ($app, $twig)
{
$page = max((int) $app['request']->get('page'), 0);
$quantity = 5;
$offset_start = max(($page - 1) * $quantity, 0);
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$elements = $account->get_api()->list_elements($type, $offset_start, $quantity);
$params = array(
'action_type' => $type
, 'adapter_action' => 'load-elements'
, 'account' => $account
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
return new Response($twig->render('prod/actions/Bridge/element_list.twig', $params));
})
->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-containers/{type}/'
, function($account_id, $type) use ($app, $twig)
{
$page = max((int) $app['request']->get('page'), 0);
$quantity = 5;
$offset_start = max(($page - 1) * $quantity, 0);
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$elements = $account->get_api()->list_containers($type, $offset_start, $quantity);
$params = array(
'action_type' => $type
, 'adapter_action' => 'load-containers'
, 'account' => $account
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
return new Response($twig->render('prod/actions/Bridge/element_list.twig', $params));
})
->assert('account_id', '\d+');
$controllers->get('/action/{account_id}/{action}/{element_type}/'
, function($account_id, $action, $element_type) use ($app, $twig)
{
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$request = $app['request'];
$elements = $request->get('elements_list', array());
$elements = is_array($elements) ? $elements : explode(';', $elements);
$destination = $request->get('destination');
$route_params = array();
$class = $account->get_api()->get_connector()->get_object_class_from_type($element_type);
switch ($action)
{
case 'createcontainer':
break;
case 'modify':
if (count($elements) != 1)
{
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-elements/' . $element_type . '/?page=&error=' . _('Vous ne pouvez pas editer plusieurs elements simultanement'));
}
foreach ($elements as $element_id)
{
if ($class === \Bridge_Api_Interface::OBJECT_CLASS_ELEMENT)
{
$route_params = array('element' => $account->get_api()->get_element_from_id($element_id, $element_type));
}
if ($class === \Bridge_Api_Interface::OBJECT_CLASS_CONTAINER)
{
$route_params = array('element' => $account->get_api()->get_container_from_id($element_id, $element_type));
}
}
break;
case 'moveinto':
$route_params = array('containers' => $account->get_api()->list_containers($destination, 0, 0));
break;
case 'deleteelement':
break;
default:
throw new \Exception(_('Vous essayez de faire une action que je ne connais pas !'));
break;
}
$params = array(
'account' => $account
, 'destination' => $destination
, 'element_type' => $element_type
, 'action' => $action
, 'constraint_errors' => null
, 'adapter_action' => $action
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
$params = array_merge($params, $route_params);
$template = 'prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/' . $element_type . '_' . $action . ($destination ? '_' . $destination : '') . '.twig';
$html = $twig->render($template, $params);
return new Response($html);
})->assert('account_id', '\d+');
$controllers->post('/action/{account_id}/{action}/{element_type}/'
, function($account_id, $action, $element_type) use ($app, $twig)
{
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$request = $app['request'];
$elements = $request->get('elements_list', array());
$elements = is_array($elements) ? $elements : explode(';', $elements);
$destination = $request->get('destination');
$class = $account->get_api()->get_connector()->get_object_class_from_type($element_type);
$html = '';
switch ($action)
{
case 'modify':
if (count($elements) != 1)
{
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?elements_list=' . implode(';', $elements) . '&error=' . _('Vous ne pouvez pas editer plusieurs elements simultanement'));
}
try
{
foreach ($elements as $element_id)
{
$datas = $account->get_api()->get_connector()->get_update_datas($app['request']);
$errors = $account->get_api()->get_connector()->check_update_constraints($datas);
}
if (count($errors) > 0)
{
$params = array(
'element' => $account->get_api()->get_element_from_id($element_id, $element_type)
, 'account' => $account
, 'destination' => $destination
, 'element_type' => $element_type
, 'action' => $action
, 'elements' => $elements
, 'adapter_action' => $action
, 'error_message' => _('Request contains invalid datas')
, 'constraint_errors' => $errors
, 'notice_message' => $app['request']->get('notice')
);
$template = 'prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/' . $element_type . '_' . $action . ($destination ? '_' . $destination : '') . '.twig';
$html = $twig->render($template, $params);
return new Response($html);
}
foreach ($elements as $element_id)
{
$datas = $account->get_api()->get_connector()->get_update_datas($app['request']);
$account->get_api()->update_element($element_type, $element_id, $datas);
}
}
catch (\Exception $e)
{
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?elements_list[]=' . $element_id . '&error=' . get_class($e) . ' : ' . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-' . $class . 's/' . $element_type . '/?page=&update=success#anchor');
break;
case 'createcontainer':
try
{
$container_type = $request->get('f_container_type');
$account->get_api()->create_container($container_type, $app['request']);
}
catch (\Exception $e)
{
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?error=' . get_class($e) . ' : ' . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-' . $class . 's/' . $element_type . '/?page=&update=success#anchor');
break;
case 'moveinto':
try
{
$container_id = $request->get('container_id');
foreach ($elements as $element_id)
{
$account->get_api()->add_element_to_container($element_type, $element_id, $destination, $container_id);
}
}
catch (\Exception $e)
{
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?error=' . get_class($e) . ' : ' . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-containers/' . $destination . '/?page=&update=success#anchor');
break;
case 'deleteelement':
try
{
foreach ($elements as $element_id)
{
$account->get_api()->delete_object($element_type, $element_id);
}
}
catch (\Exception $e)
{
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?error=' . get_class($e) . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-' . $class . 's/' . $element_type . '/');
break;
default:
throw new \Exception('Unknown action');
break;
}
return new Response($html);
})->assert('account_id', '\d+');
$controllers->get('/upload/', function(Application $app) use ($twig)
{
$request = $app['request'];
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $request->get('account_id'));
$app['require_connection']($account);
$route = new RecordHelper\Bridge($app['Core'], $app['request']);
$route->grep_records($account->get_api()->acceptable_records());
$params = array(
'route' => $route
, 'account' => $account
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
, 'adapter_action' => 'upload'
);
$html = $twig->render(
'prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/upload.twig', $params
);
return new Response($html);
});
$controllers->post('/upload/'
, function(Application $app) use ($twig)
{
$errors = array();
$request = $app['request'];
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $request->get('account_id'));
$app['require_connection']($account);
$route = new RecordHelper\Bridge($app['Core'], $app['request']);
$route->grep_records($account->get_api()->acceptable_records());
$connector = $account->get_api()->get_connector();
/**
* check constraints
*/
foreach ($route->get_elements() as $record)
{
$datas = $connector->get_upload_datas($request, $record);
$errors = array_merge($errors, $connector->check_upload_constraints($datas, $record));
}
if (count($errors) > 0)
{
$params = array( $params = array(
'route' => $route 'user_accounts' => \Bridge_Account::get_accounts_by_user($appbox, $user)
, 'account' => $account , 'available_apis' => \Bridge_Api::get_availables($appbox)
, 'error_message' => _('Request contains invalid datas') , 'route' => $route
, 'constraint_errors' => $errors , 'current_account_id' => ''
);
return new Response($twig->render('prod/actions/Bridge/index.twig', $params)
);
});
$controllers->get('/login/{api_name}/', function($api_name) use ($app, $twig) {
$appbox = \appbox::get_instance($app['Core']);
$connector = \Bridge_Api::get_connector_by_name($appbox->get_registry(), $api_name);
return $app->redirect($connector->get_auth_url());
});
$controllers->get('/callback/{api_name}/', function($api_name) use ($app, $twig) {
$error_message = '';
try {
$appbox = \appbox::get_instance($app['Core']);
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$api = \Bridge_Api::get_by_api_name($appbox, $api_name);
$connector = $api->get_connector();
$response = $connector->connect();
$user_id = $connector->get_user_id();
try {
$account = \Bridge_Account::load_account_from_distant_id($appbox, $api, $user, $user_id);
} catch (\Bridge_Exception_AccountNotFound $e) {
$account = \Bridge_Account::create($appbox, $api, $user, $user_id, $connector->get_user_name());
}
$settings = $account->get_settings();
if (isset($response['auth_token']))
$settings->set('auth_token', $response['auth_token']);
if (isset($response['refresh_token']))
$settings->set('refresh_token', $response['refresh_token']);
$connector->set_auth_settings($settings);
$connector->reconnect();
} catch (\Exception $e) {
$error_message = $e->getMessage();
}
$params = array('error_message' => $error_message);
return new Response($twig->render('prod/actions/Bridge/callback.twig', $params));
});
$controllers->get('/adapter/{account_id}/logout/'
, function($account_id) use ($app, $twig) {
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$account->get_api()->get_connector()->disconnect();
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-elements/' . $account->get_api()->get_connector()->get_default_element_type() . '/');
})->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-records/'
, function($account_id) use ($app, $twig) {
$page = max((int) $app['request']->get('page'), 0);
$quantity = 10;
$offset_start = max(($page - 1) * $quantity, 0);
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$elements = \Bridge_Element::get_elements_by_account($appbox, $account, $offset_start, $quantity);
$app['require_connection']($account);
$params = array(
'adapter_action' => 'load-records'
, 'account' => $account
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
return new Response($twig->render('prod/actions/Bridge/records_list.twig', $params));
})
->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-elements/{type}/'
, function($account_id, $type) use ($app, $twig) {
$page = max((int) $app['request']->get('page'), 0);
$quantity = 5;
$offset_start = max(($page - 1) * $quantity, 0);
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$elements = $account->get_api()->list_elements($type, $offset_start, $quantity);
$params = array(
'action_type' => $type
, 'adapter_action' => 'load-elements'
, 'account' => $account
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
return new Response($twig->render('prod/actions/Bridge/element_list.twig', $params));
})
->assert('account_id', '\d+');
$controllers->get('/adapter/{account_id}/load-containers/{type}/'
, function($account_id, $type) use ($app, $twig) {
$page = max((int) $app['request']->get('page'), 0);
$quantity = 5;
$offset_start = max(($page - 1) * $quantity, 0);
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$elements = $account->get_api()->list_containers($type, $offset_start, $quantity);
$params = array(
'action_type' => $type
, 'adapter_action' => 'load-containers'
, 'account' => $account
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
return new Response($twig->render('prod/actions/Bridge/element_list.twig', $params));
})
->assert('account_id', '\d+');
$controllers->get('/action/{account_id}/{action}/{element_type}/'
, function($account_id, $action, $element_type) use ($app, $twig) {
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$request = $app['request'];
$elements = $request->get('elements_list', array());
$elements = is_array($elements) ? $elements : explode(';', $elements);
$destination = $request->get('destination');
$route_params = array();
$class = $account->get_api()->get_connector()->get_object_class_from_type($element_type);
switch ($action) {
case 'createcontainer':
break;
case 'modify':
if (count($elements) != 1) {
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-elements/' . $element_type . '/?page=&error=' . _('Vous ne pouvez pas editer plusieurs elements simultanement'));
}
foreach ($elements as $element_id) {
if ($class === \Bridge_Api_Interface::OBJECT_CLASS_ELEMENT) {
$route_params = array('element' => $account->get_api()->get_element_from_id($element_id, $element_type));
}
if ($class === \Bridge_Api_Interface::OBJECT_CLASS_CONTAINER) {
$route_params = array('element' => $account->get_api()->get_container_from_id($element_id, $element_type));
}
}
break;
case 'moveinto':
$route_params = array('containers' => $account->get_api()->list_containers($destination, 0, 0));
break;
case 'deleteelement':
break;
default:
throw new \Exception(_('Vous essayez de faire une action que je ne connais pas !'));
break;
}
$params = array(
'account' => $account
, 'destination' => $destination
, 'element_type' => $element_type
, 'action' => $action
, 'constraint_errors' => null
, 'adapter_action' => $action
, 'elements' => $elements
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice')
);
$params = array_merge($params, $route_params);
$template = 'prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/' . $element_type . '_' . $action . ($destination ? '_' . $destination : '') . '.twig';
$html = $twig->render($template, $params);
return new Response($html);
})->assert('account_id', '\d+');
$controllers->post('/action/{account_id}/{action}/{element_type}/'
, function($account_id, $action, $element_type) use ($app, $twig) {
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $account_id);
$app['require_connection']($account);
$request = $app['request'];
$elements = $request->get('elements_list', array());
$elements = is_array($elements) ? $elements : explode(';', $elements);
$destination = $request->get('destination');
$class = $account->get_api()->get_connector()->get_object_class_from_type($element_type);
$html = '';
switch ($action) {
case 'modify':
if (count($elements) != 1) {
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?elements_list=' . implode(';', $elements) . '&error=' . _('Vous ne pouvez pas editer plusieurs elements simultanement'));
}
try {
foreach ($elements as $element_id) {
$datas = $account->get_api()->get_connector()->get_update_datas($app['request']);
$errors = $account->get_api()->get_connector()->check_update_constraints($datas);
}
if (count($errors) > 0) {
$params = array(
'element' => $account->get_api()->get_element_from_id($element_id, $element_type)
, 'account' => $account
, 'destination' => $destination
, 'element_type' => $element_type
, 'action' => $action
, 'elements' => $elements
, 'adapter_action' => $action
, 'error_message' => _('Request contains invalid datas')
, 'constraint_errors' => $errors
, 'notice_message' => $app['request']->get('notice')
);
$template = 'prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/' . $element_type . '_' . $action . ($destination ? '_' . $destination : '') . '.twig';
$html = $twig->render($template, $params);
return new Response($html);
}
foreach ($elements as $element_id) {
$datas = $account->get_api()->get_connector()->get_update_datas($app['request']);
$account->get_api()->update_element($element_type, $element_id, $datas);
}
} catch (\Exception $e) {
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?elements_list[]=' . $element_id . '&error=' . get_class($e) . ' : ' . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-' . $class . 's/' . $element_type . '/?page=&update=success#anchor');
break;
case 'createcontainer':
try {
$container_type = $request->get('f_container_type');
$account->get_api()->create_container($container_type, $app['request']);
} catch (\Exception $e) {
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?error=' . get_class($e) . ' : ' . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-' . $class . 's/' . $element_type . '/?page=&update=success#anchor');
break;
case 'moveinto':
try {
$container_id = $request->get('container_id');
foreach ($elements as $element_id) {
$account->get_api()->add_element_to_container($element_type, $element_id, $destination, $container_id);
}
} catch (\Exception $e) {
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?error=' . get_class($e) . ' : ' . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-containers/' . $destination . '/?page=&update=success#anchor');
break;
case 'deleteelement':
try {
foreach ($elements as $element_id) {
$account->get_api()->delete_object($element_type, $element_id);
}
} catch (\Exception $e) {
return $app->redirect('/prod/bridge/action/' . $account_id . '/' . $action . '/' . $element_type . '/?error=' . get_class($e) . $e->getMessage());
}
return $app->redirect('/prod/bridge/adapter/' . $account_id . '/load-' . $class . 's/' . $element_type . '/');
break;
default:
throw new \Exception('Unknown action');
break;
}
return new Response($html);
})->assert('account_id', '\d+');
$controllers->get('/upload/', function(Application $app) use ($twig) {
$request = $app['request'];
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $request->get('account_id'));
$app['require_connection']($account);
$route = new RecordHelper\Bridge($app['Core'], $app['request']);
$route->grep_records($account->get_api()->acceptable_records());
$params = array(
'route' => $route
, 'account' => $account
, 'error_message' => $app['request']->get('error')
, 'notice_message' => $app['request']->get('notice') , 'notice_message' => $app['request']->get('notice')
, 'adapter_action' => 'upload' , 'adapter_action' => 'upload'
); );
$html = $twig->render('prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/upload.twig', $params); $html = $twig->render(
'prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/upload.twig', $params
);
return new Response($html); return new Response($html);
//return $app->redirect('/prod/bridge/upload/?lst='.$request->get('lst').'&account_id='.$request->get('account_id').'&errors=' . sprintf(_('%d elements en erreur. %s'), count($errors), $error_msg));
}
foreach ($route->get_elements() as $record)
{
$datas = $connector->get_upload_datas($request, $record);
$title = isset($datas["title"]) ? $datas["title"] : '';
$default_type = $connector->get_default_element_type();
\Bridge_Element::create($appbox, $account, $record, $title, \Bridge_Element::STATUS_PENDING, $default_type, $datas);
}
return $app->redirect('/prod/bridge/adapter/' . $account->get_id() . '/load-records/?notice=' . sprintf(_('%d elements en attente'), count($route->get_elements())));
}); });
return $controllers;
}
$controllers->post('/upload/'
, function(Application $app) use ($twig) {
$errors = array();
$request = $app['request'];
$appbox = \appbox::get_instance($app['Core']);
$account = \Bridge_Account::load_account($appbox, $request->get('account_id'));
$app['require_connection']($account);
$route = new RecordHelper\Bridge($app['Core'], $app['request']);
$route->grep_records($account->get_api()->acceptable_records());
$connector = $account->get_api()->get_connector();
/**
* check constraints
*/
foreach ($route->get_elements() as $record) {
$datas = $connector->get_upload_datas($request, $record);
$errors = array_merge($errors, $connector->check_upload_constraints($datas, $record));
}
if (count($errors) > 0) {
$params = array(
'route' => $route
, 'account' => $account
, 'error_message' => _('Request contains invalid datas')
, 'constraint_errors' => $errors
, 'notice_message' => $app['request']->get('notice')
, 'adapter_action' => 'upload'
);
$html = $twig->render('prod/actions/Bridge/' . $account->get_api()->get_connector()->get_name() . '/upload.twig', $params);
return new Response($html);
//return $app->redirect('/prod/bridge/upload/?lst='.$request->get('lst').'&account_id='.$request->get('account_id').'&errors=' . sprintf(_('%d elements en erreur. %s'), count($errors), $error_msg));
}
foreach ($route->get_elements() as $record) {
$datas = $connector->get_upload_datas($request, $record);
$title = isset($datas["title"]) ? $datas["title"] : '';
$default_type = $connector->get_default_element_type();
\Bridge_Element::create($appbox, $account, $record, $title, \Bridge_Element::STATUS_PENDING, $default_type, $datas);
}
return $app->redirect('/prod/bridge/adapter/' . $account->get_id() . '/load-records/?notice=' . sprintf(_('%d elements en attente'), count($route->get_elements())));
});
return $controllers;
}
} }

View File

@@ -27,85 +27,77 @@ use Symfony\Component\HttpFoundation\Request,
class Edit implements ControllerProviderInterface class Edit implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/', function(Application $app, Request $request) $controllers->post('/', function(Application $app, Request $request) {
{ $handler = new RecordHelper\Edit($app['Core'], $request);
$handler = new RecordHelper\Edit($app['Core'], $request);
$handler->propose_editing(); $handler->propose_editing();
$template = 'prod/actions/edit_default.twig'; $template = 'prod/actions/edit_default.twig';
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render($template, array('edit' => $handler, 'message' => '')); return $twig->render($template, array('edit' => $handler, 'message' => ''));
} }
); );
$controllers->get('/vocabulary/{vocabulary}/', function(Application $app, Request $request, $vocabulary) $controllers->get('/vocabulary/{vocabulary}/', function(Application $app, Request $request, $vocabulary) {
{ $datas = array('success' => false, 'message' => '', 'results' => array());
$datas = array('success' => false, 'message' => '', 'results' => array());
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
$sbas_id = (int) $request->get('sbas_id'); $sbas_id = (int) $request->get('sbas_id');
try try {
{ $VC = \Alchemy\Phrasea\Vocabulary\Controller::get($vocabulary);
$VC = \Alchemy\Phrasea\Vocabulary\Controller::get($vocabulary); $databox = \databox::get_instance($sbas_id);
$databox = \databox::get_instance($sbas_id); } catch (\Exception $e) {
} $datas['message'] = _('Vocabulary not found');
catch (\Exception $e)
{
$datas['message'] = _('Vocabulary not found');
$datas = $Serializer->serialize($datas, 'json'); $datas = $Serializer->serialize($datas, 'json');
return new response($datas, 200, array('Content-Type' => 'application/json')); return new response($datas, 200, array('Content-Type' => 'application/json'));
} }
$query = $request->get('query'); $query = $request->get('query');
$results = $VC->find($query, $app['Core']->getAuthenticatedUser(), $databox); $results = $VC->find($query, $app['Core']->getAuthenticatedUser(), $databox);
$list = array(); $list = array();
foreach ($results as $Term) foreach ($results as $Term) {
{ /* @var $Term \Alchemy\Phrasea\Vocabulary\Term */
/* @var $Term \Alchemy\Phrasea\Vocabulary\Term */ $list[] = array(
$list[] = array( 'id' => $Term->getId(),
'id' => $Term->getId(), 'context' => $Term->getContext(),
'context' => $Term->getContext(), 'value' => $Term->getValue(),
'value' => $Term->getValue(), );
); }
}
$datas['success'] = true; $datas['success'] = true;
$datas['results'] = $list; $datas['results'] = $list;
return new response($Serializer->serialize($datas, 'json'), 200, array('Content-Type' => 'application/json')); return new response($Serializer->serialize($datas, 'json'), 200, array('Content-Type' => 'application/json'));
} }
); );
$controllers->post('/apply/', function(Application $app, Request $request) $controllers->post('/apply/', function(Application $app, Request $request) {
{ $editing = new RecordHelper\Edit($app['Core'], $app['request']);
$editing = new RecordHelper\Edit($app['Core'], $app['request']); $editing->execute($request);
$editing->execute($request);
$template = 'prod/actions/edit_default.twig'; $template = 'prod/actions/edit_default.twig';
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render($template, array('edit' => $editing, 'message' => '')); return $twig->render($template, array('edit' => $editing, 'message' => ''));
} }
); );
return $controllers;
}
return $controllers;
}
} }

View File

@@ -29,196 +29,172 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class Feed implements ControllerProviderInterface class Feed implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
/** /**
* I got a selection of docs, which publications are available forthese docs ? * I got a selection of docs, which publications are available forthese docs ?
*/ */
$controllers->post('/requestavailable/', function(Application $app, Request $request) use ($appbox, $twig) $controllers->post('/requestavailable/', function(Application $app, Request $request) use ($appbox, $twig) {
{
$user = $app["Core"]->getAuthenticatedUser();
$feeds = \Feed_Collection::load_all($appbox, $user);
$publishing = new RecordHelper\Feed($app['Core'], $request);
$datas = $twig->render('prod/actions/publish/publish.html', array('publishing' => $publishing, 'feeds' => $feeds));
return new Response($datas);
});
/**
* I've selected a publication for my ocs, let's publish them
*/
$controllers->post('/entry/create/', function(Application $app, Request $request) use ($appbox, $twig)
{
try
{
$user = $app["Core"]->getAuthenticatedUser(); $user = $app["Core"]->getAuthenticatedUser();
$feed = new \Feed_Adapter($appbox, $request->get('feed_id')); $feeds = \Feed_Collection::load_all($appbox, $user);
$publisher = \Feed_Publisher_Adapter::getPublisher($appbox, $feed, $user); $publishing = new RecordHelper\Feed($app['Core'], $request);
$title = $request->get('title'); $datas = $twig->render('prod/actions/publish/publish.html', array('publishing' => $publishing, 'feeds' => $feeds));
$subtitle = $request->get('subtitle');
$author_name = $request->get('author_name');
$author_mail = $request->get('author_mail');
$entry = \Feed_Entry_Adapter::create($appbox, $feed, $publisher, $title, $subtitle, $author_name, $author_mail); return new Response($datas);
$publishing = new RecordHelper\Feed($app['Core'], $app['request']);
foreach ($publishing->get_elements() as $record)
{
$item = \Feed_Entry_Item::create($appbox, $entry, $record);
}
$datas = array('error' => false, 'message' => false);
}
catch (\Exception $e)
{
$datas = array('error' => true, 'message' => _('An error occured'), 'details' => $e->getMessage());
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
}); });
$controllers->get('/entry/{id}/edit/', function(Application $app, Request $request, $id) use ($appbox, $twig) /**
{ * I've selected a publication for my ocs, let's publish them
*/
$controllers->post('/entry/create/', function(Application $app, Request $request) use ($appbox, $twig) {
try {
$user = $app["Core"]->getAuthenticatedUser();
$feed = new \Feed_Adapter($appbox, $request->get('feed_id'));
$publisher = \Feed_Publisher_Adapter::getPublisher($appbox, $feed, $user);
$user = $app["Core"]->getAuthenticatedUser(); $title = $request->get('title');
$subtitle = $request->get('subtitle');
$author_name = $request->get('author_name');
$author_mail = $request->get('author_mail');
$entry = \Feed_Entry_Adapter::load_from_id($appbox, $id); $entry = \Feed_Entry_Adapter::create($appbox, $feed, $publisher, $title, $subtitle, $author_name, $author_mail);
if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id()) $publishing = new RecordHelper\Feed($app['Core'], $app['request']);
{
throw new \Exception_UnauthorizedAction();
}
$feeds = \Feed_Collection::load_all($appbox, $user); foreach ($publishing->get_elements() as $record) {
$item = \Feed_Entry_Item::create($appbox, $entry, $record);
}
$datas = array('error' => false, 'message' => false);
} catch (\Exception $e) {
$datas = array('error' => true, 'message' => _('An error occured'), 'details' => $e->getMessage());
}
$datas = $twig->render('prod/actions/publish/publish_edit.html', array('entry' => $entry, 'feeds' => $feeds)); $Serializer = $app['Core']['Serializer'];
return new Response($datas); return new Response(
})->assert('id', '\d+'); $Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
});
$controllers->post('/entry/{id}/update/', function(Application $app, Request $request, $id) use ($appbox, $twig) $controllers->get('/entry/{id}/edit/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
{
$datas = array('error' => true, 'message' => '', 'datas' => '');
try
{
$appbox->get_connection()->beginTransaction();
$user = $app["Core"]->getAuthenticatedUser(); $user = $app["Core"]->getAuthenticatedUser();
$entry = \Feed_Entry_Adapter::load_from_id($appbox, $id); $entry = \Feed_Entry_Adapter::load_from_id($appbox, $id);
if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id()) if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id()) {
{ throw new \Exception_UnauthorizedAction();
throw new \Exception_UnauthorizedAction();
} }
$title = $request->get('title'); $feeds = \Feed_Collection::load_all($appbox, $user);
$subtitle = $request->get('subtitle');
$author_name = $request->get('author_name');
$author_mail = $request->get('author_mail');
$entry->set_author_email($author_mail) $datas = $twig->render('prod/actions/publish/publish_edit.html', array('entry' => $entry, 'feeds' => $feeds));
return new Response($datas);
})->assert('id', '\d+');
$controllers->post('/entry/{id}/update/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
$datas = array('error' => true, 'message' => '', 'datas' => '');
try {
$appbox->get_connection()->beginTransaction();
$user = $app["Core"]->getAuthenticatedUser();
$entry = \Feed_Entry_Adapter::load_from_id($appbox, $id);
if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id()) {
throw new \Exception_UnauthorizedAction();
}
$title = $request->get('title');
$subtitle = $request->get('subtitle');
$author_name = $request->get('author_name');
$author_mail = $request->get('author_mail');
$entry->set_author_email($author_mail)
->set_author_name($author_name) ->set_author_name($author_name)
->set_title($title) ->set_title($title)
->set_subtitle($subtitle); ->set_subtitle($subtitle);
$items = explode(';', $request->get('sorted_lst')); $items = explode(';', $request->get('sorted_lst'));
foreach ($items as $item_sort) foreach ($items as $item_sort) {
{ $item_sort_datas = explode('_', $item_sort);
$item_sort_datas = explode('_', $item_sort); if (count($item_sort_datas) != 2) {
if (count($item_sort_datas) != 2) continue;
{ }
continue;
}
$item = new \Feed_Entry_Item($appbox, $entry, $item_sort_datas[0]); $item = new \Feed_Entry_Item($appbox, $entry, $item_sort_datas[0]);
$item->set_ord($item_sort_datas[1]); $item->set_ord($item_sort_datas[1]);
}
$appbox->get_connection()->commit();
$entry = $twig->render('prod/feeds/entry.html', array('entry' => $entry));
$datas = array('error' => false, 'message' => 'succes', 'datas' => $entry);
} catch (\Exception_Feed_EntryNotFound $e) {
$appbox->get_connection()->rollBack();
$datas['message'] = _('Feed entry not found');
} catch (\Exception $e) {
$appbox->get_connection()->rollBack();
$datas['message'] = $e->getMessage();
} }
$appbox->get_connection()->commit();
$entry = $twig->render('prod/feeds/entry.html', array('entry' => $entry)); $Serializer = $app['Core']['Serializer'];
$datas = array('error' => false, 'message' => 'succes', 'datas' => $entry); return new Response(
} $Serializer->serialize($datas, 'json')
catch (\Exception_Feed_EntryNotFound $e) , 200
{ , array('Content-Type' => 'application/json')
$appbox->get_connection()->rollBack(); );
$datas['message'] = _('Feed entry not found');
}
catch (\Exception $e)
{
$appbox->get_connection()->rollBack();
$datas['message'] = $e->getMessage();
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
})->assert('id', '\d+'); })->assert('id', '\d+');
$controllers->post('/entry/{id}/delete/', function(Application $app, Request $request, $id) use ($appbox, $twig) $controllers->post('/entry/{id}/delete/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
{ $datas = array('error' => true, 'message' => '');
$datas = array('error' => true, 'message' => ''); try {
try $appbox->get_connection()->beginTransaction();
{
$appbox->get_connection()->beginTransaction();
$user = $app["Core"]->getAuthenticatedUser(); $user = $app["Core"]->getAuthenticatedUser();
$entry = \Feed_Entry_Adapter::load_from_id($appbox, $id); $entry = \Feed_Entry_Adapter::load_from_id($appbox, $id);
if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id() if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id()
&& $entry->get_feed()->is_owner($user) === false) && $entry->get_feed()->is_owner($user) === false) {
{ throw new \Exception_UnauthorizedAction(_('Action Forbidden : You are not the publisher'));
throw new \Exception_UnauthorizedAction(_('Action Forbidden : You are not the publisher')); }
$entry->delete();
$appbox->get_connection()->commit();
$datas = array('error' => false, 'message' => 'succes');
} catch (\Exception_Feed_EntryNotFound $e) {
$appbox->get_connection()->rollBack();
$datas['message'] = _('Feed entry not found');
} catch (\Exception $e) {
$appbox->get_connection()->rollBack();
$datas['message'] = $e->getMessage();
} }
$entry->delete(); $Serializer = $app['Core']['Serializer'];
$appbox->get_connection()->commit(); return new Response(
$datas = array('error' => false, 'message' => 'succes'); $Serializer->serialize($datas, 'json')
} , 200
catch (\Exception_Feed_EntryNotFound $e) , array('Content-Type' => 'application/json')
{ );
$appbox->get_connection()->rollBack();
$datas['message'] = _('Feed entry not found');
}
catch (\Exception $e)
{
$appbox->get_connection()->rollBack();
$datas['message'] = $e->getMessage();
}
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
})->assert('id', '\d+'); })->assert('id', '\d+');
//$app->post('/entry/{id}/addelement/', function($id) use ($app, $appbox, $twig) //$app->post('/entry/{id}/addelement/', function($id) use ($app, $appbox, $twig)
@@ -240,95 +216,90 @@ class Feed implements ControllerProviderInterface
// //
// }); // });
$controllers->get('/', function(Application $app, Request $request) use ($appbox, $twig) $controllers->get('/', function(Application $app, Request $request) use ($appbox, $twig) {
{ $request = $app['request'];
$request = $app['request']; $page = (int) $request->get('page');
$page = (int) $request->get('page'); $page = $page > 0 ? $page : 1;
$page = $page > 0 ? $page : 1;
$user = $app["Core"]->getAuthenticatedUser(); $user = $app["Core"]->getAuthenticatedUser();
$feeds = \Feed_Collection::load_all($appbox, $user); $feeds = \Feed_Collection::load_all($appbox, $user);
$datas = $twig->render('prod/feeds/feeds.html' $datas = $twig->render('prod/feeds/feeds.html'
, array( , array(
'feeds' => $feeds 'feeds' => $feeds
, 'feed' => $feeds->get_aggregate() , 'feed' => $feeds->get_aggregate()
, 'page' => $page , 'page' => $page
) )
); );
return new Response($datas); return new Response($datas);
}); });
$controllers->get('/feed/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) $controllers->get('/feed/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
{ $page = (int) $request->get('page');
$page = (int) $request->get('page'); $page = $page > 0 ? $page : 1;
$page = $page > 0 ? $page : 1;
$user = $app["Core"]->getAuthenticatedUser(); $user = $app["Core"]->getAuthenticatedUser();
$feed = \Feed_Adapter::load_with_user($appbox, $user, $id); $feed = \Feed_Adapter::load_with_user($appbox, $user, $id);
$feeds = \Feed_Collection::load_all($appbox, $user); $feeds = \Feed_Collection::load_all($appbox, $user);
$datas = $twig->render('prod/feeds/feeds.html', array('feed' => $feed, 'feeds' => $feeds, 'page' => $page)); $datas = $twig->render('prod/feeds/feeds.html', array('feed' => $feed, 'feeds' => $feeds, 'page' => $page));
return new Response($datas); return new Response($datas);
})->assert('id', '\d+'); })->assert('id', '\d+');
$controllers->get('/subscribe/aggregated/', function(Application $app, Request $request) use ( $appbox, $twig) $controllers->get('/subscribe/aggregated/', function(Application $app, Request $request) use ( $appbox, $twig) {
{ $renew = ($request->get('renew') === 'true');
$renew = ($request->get('renew') === 'true');
$user = $app["Core"]->getAuthenticatedUser(); $user = $app["Core"]->getAuthenticatedUser();
$feeds = \Feed_Collection::load_all($appbox, $user); $feeds = \Feed_Collection::load_all($appbox, $user);
$registry = $appbox->get_registry(); $registry = $appbox->get_registry();
$output = array( $output = array(
'texte' => '<p>' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.') 'texte' => '<p>' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.')
. '</p><p>' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '</p> . '</p><p>' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '</p>
<div><input type="text" readonly="readonly" class="input_select_copy" value="' . $feeds->get_aggregate()->get_user_link($registry, $user, \Feed_Adapter::FORMAT_RSS, null, $renew)->get_href() . '"/></div>', <div><input type="text" readonly="readonly" class="input_select_copy" value="' . $feeds->get_aggregate()->get_user_link($registry, $user, \Feed_Adapter::FORMAT_RSS, null, $renew)->get_href() . '"/></div>',
'titre' => _('publications::votre rss personnel') 'titre' => _('publications::votre rss personnel')
); );
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize($output, 'json') $Serializer->serialize($output, 'json')
, 200 , 200
, array('Content-Type' => 'application/json') , array('Content-Type' => 'application/json')
); );
}); });
$controllers->get('/subscribe/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) $controllers->get('/subscribe/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
{ $renew = ($request->get('renew') === 'true');
$renew = ($request->get('renew') === 'true'); $user = $app["Core"]->getAuthenticatedUser();
$user = $app["Core"]->getAuthenticatedUser(); $feed = \Feed_Adapter::load_with_user($appbox, $user, $id);
$feed = \Feed_Adapter::load_with_user($appbox, $user, $id); $registry = $appbox->get_registry();
$registry = $appbox->get_registry();
$output = array( $output = array(
'texte' => '<p>' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.') 'texte' => '<p>' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.')
. '</p><p>' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '</p> . '</p><p>' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '</p>
<div><input type="text" style="width:100%" value="' . $feed->get_user_link($registry, $user, \Feed_Adapter::FORMAT_RSS, null, $renew)->get_href() . '"/></div>', <div><input type="text" style="width:100%" value="' . $feed->get_user_link($registry, $user, \Feed_Adapter::FORMAT_RSS, null, $renew)->get_href() . '"/></div>',
'titre' => _('publications::votre rss personnel') 'titre' => _('publications::votre rss personnel')
); );
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize($output, 'json') $Serializer->serialize($output, 'json')
, 200 , 200
, array('Content-Type' => 'application/json') , array('Content-Type' => 'application/json')
); );
})->assert('id', '\d+'); })->assert('id', '\d+');
return $controllers; return $controllers;
} }
} }

View File

@@ -29,85 +29,83 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class Language implements ControllerProviderInterface class Language implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controller = new ControllerCollection(); $controller = new ControllerCollection();
$controller->get("/", function(Application $app) $controller->get("/", function(Application $app) {
{ $registry = $app["Core"]->getRegistry();
$registry = $app["Core"]->getRegistry();
$out = array(); $out = array();
$out['thesaurusBasesChanged'] = _('prod::recherche: Attention : la liste des bases selectionnees pour la recherche a ete changee.'); $out['thesaurusBasesChanged'] = _('prod::recherche: Attention : la liste des bases selectionnees pour la recherche a ete changee.');
$out['confirmDel'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?'); $out['confirmDel'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?');
$out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique'); $out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique');
$out['serverName'] = $registry->get('GV_ServerName'); $out['serverName'] = $registry->get('GV_ServerName');
$out['serverTimeout'] = _('phraseanet::erreur: La connection au serveur Phraseanet semble etre indisponible'); $out['serverTimeout'] = _('phraseanet::erreur: La connection au serveur Phraseanet semble etre indisponible');
$out['serverDisconnected'] = _('phraseanet::erreur: Votre session est fermee, veuillez vous re-authentifier'); $out['serverDisconnected'] = _('phraseanet::erreur: Votre session est fermee, veuillez vous re-authentifier');
$out['hideMessage'] = _('phraseanet::Ne plus afficher ce message'); $out['hideMessage'] = _('phraseanet::Ne plus afficher ce message');
$out['confirmGroup'] = _('Supprimer egalement les documents rattaches a ces regroupements'); $out['confirmGroup'] = _('Supprimer egalement les documents rattaches a ces regroupements');
$out['confirmDelete'] = _('reponses:: Ces enregistrements vont etre definitivement supprimes et ne pourront etre recuperes. Etes vous sur ?'); $out['confirmDelete'] = _('reponses:: Ces enregistrements vont etre definitivement supprimes et ne pourront etre recuperes. Etes vous sur ?');
$out['cancel'] = _('boutton::annuler'); $out['cancel'] = _('boutton::annuler');
$out['deleteTitle'] = _('boutton::supprimer'); $out['deleteTitle'] = _('boutton::supprimer');
$out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\''); $out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\'');
$out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?'); $out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?');
$out['loading'] = _('phraseanet::chargement'); $out['loading'] = _('phraseanet::chargement');
$out['valider'] = _('boutton::valider'); $out['valider'] = _('boutton::valider');
$out['annuler'] = _('boutton::annuler'); $out['annuler'] = _('boutton::annuler');
$out['create'] = _('boutton::creer'); $out['create'] = _('boutton::creer');
$out['rechercher'] = _('boutton::rechercher'); $out['rechercher'] = _('boutton::rechercher');
$out['renewRss'] = _('boutton::renouveller'); $out['renewRss'] = _('boutton::renouveller');
$out['candeletesome'] = _('Vous n\'avez pas les droits pour supprimer certains documents'); $out['candeletesome'] = _('Vous n\'avez pas les droits pour supprimer certains documents');
$out['candeletedocuments'] = _('Vous n\'avez pas les droits pour supprimer ces documents'); $out['candeletedocuments'] = _('Vous n\'avez pas les droits pour supprimer ces documents');
$out['needTitle'] = _('Vous devez donner un titre'); $out['needTitle'] = _('Vous devez donner un titre');
$out['newPreset'] = _('Nouveau modele'); $out['newPreset'] = _('Nouveau modele');
$out['fermer'] = _('boutton::fermer'); $out['fermer'] = _('boutton::fermer');
$out['feed_require_fields'] = _('Vous n\'avez pas rempli tous les champ requis'); $out['feed_require_fields'] = _('Vous n\'avez pas rempli tous les champ requis');
$out['feed_require_feed'] = _('Vous n\'avez pas selectionne de fil de publication'); $out['feed_require_feed'] = _('Vous n\'avez pas selectionne de fil de publication');
$out['removeTitle'] = _('panier::Supression d\'un element d\'un reportage'); $out['removeTitle'] = _('panier::Supression d\'un element d\'un reportage');
$out['confirmRemoveReg'] = _('panier::Attention, vous etes sur le point de supprimer un element du reportage. Merci de confirmer votre action.'); $out['confirmRemoveReg'] = _('panier::Attention, vous etes sur le point de supprimer un element du reportage. Merci de confirmer votre action.');
$out['advsearch_title'] = _('phraseanet::recherche avancee'); $out['advsearch_title'] = _('phraseanet::recherche avancee');
$out['bask_rename'] = _('panier:: renommer le panier'); $out['bask_rename'] = _('panier:: renommer le panier');
$out['reg_wrong_sbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre'); $out['reg_wrong_sbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre');
$out['error'] = _('phraseanet:: Erreur'); $out['error'] = _('phraseanet:: Erreur');
$out['warningDenyCgus'] = _('cgus :: Attention, si vous refuser les CGUs de cette base, vous n\'y aures plus acces'); $out['warningDenyCgus'] = _('cgus :: Attention, si vous refuser les CGUs de cette base, vous n\'y aures plus acces');
$out['cgusRelog'] = _('cgus :: Vous devez vous reauthentifier pour que vos parametres soient pris en compte.'); $out['cgusRelog'] = _('cgus :: Vous devez vous reauthentifier pour que vos parametres soient pris en compte.');
$out['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes'); $out['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes');
$out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes'); $out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes');
$out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant'); $out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant');
$out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant'); $out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant');
$out['cantDeletePublicOne'] = _('panier:: vous ne pouvez pas supprimer un panier public'); $out['cantDeletePublicOne'] = _('panier:: vous ne pouvez pas supprimer un panier public');
$out['wrongsbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre'); $out['wrongsbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre');
$out['max_record_selected'] = _('Vous ne pouvez pas selectionner plus de 800 enregistrements'); $out['max_record_selected'] = _('Vous ne pouvez pas selectionner plus de 800 enregistrements');
$out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez'); $out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez');
$out['error_test_publi'] = _('Erreur : soit les parametres sont incorrects, soit le serveur distant ne repond pas'); $out['error_test_publi'] = _('Erreur : soit les parametres sont incorrects, soit le serveur distant ne repond pas');
$out['test_publi_ok'] = _('Les parametres sont corrects, le serveur distant est operationnel'); $out['test_publi_ok'] = _('Les parametres sont corrects, le serveur distant est operationnel');
$out['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, verifiez vos parametres'); $out['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, verifiez vos parametres');
$out['error_not_published'] = _('Aucune publication effectuee, verifiez vos parametres'); $out['error_not_published'] = _('Aucune publication effectuee, verifiez vos parametres');
$out['warning_delete_publi'] = _('Attention, en supprimant ce preregalge, vous ne pourrez plus modifier ou supprimer de publications prealablement effectues avec celui-ci'); $out['warning_delete_publi'] = _('Attention, en supprimant ce preregalge, vous ne pourrez plus modifier ou supprimer de publications prealablement effectues avec celui-ci');
$out['some_required_fields'] = _('edit::certains documents possedent des champs requis non remplis. Merci de les remplir pour valider votre editing'); $out['some_required_fields'] = _('edit::certains documents possedent des champs requis non remplis. Merci de les remplir pour valider votre editing');
$out['nodocselected'] = _('Aucun document selectionne'); $out['nodocselected'] = _('Aucun document selectionne');
$out['sureToRemoveList'] = _('Are you sure you want to delete this list ?'); $out['sureToRemoveList'] = _('Are you sure you want to delete this list ?');
$out['newListName'] = _('New list name ?'); $out['newListName'] = _('New list name ?');
$out['listNameCannotBeEmpty'] = _('List name can not be empty'); $out['listNameCannotBeEmpty'] = _('List name can not be empty');
$out['FeedBackName'] = _('Name'); $out['FeedBackName'] = _('Name');
$out['FeedBackMessage'] = _('Message'); $out['FeedBackMessage'] = _('Message');
$out['FeedBackDuration'] = _('Time for feedback (days)'); $out['FeedBackDuration'] = _('Time for feedback (days)');
$out['send'] = _('Send'); $out['send'] = _('Send');
$out['Recept'] = _('Accuse de reception'); $out['Recept'] = _('Accuse de reception');
$out['nFieldsChanged'] = _('%d fields have been updated'); $out['nFieldsChanged'] = _('%d fields have been updated');
$out['FeedBackNoUsersSelected'] = _('No users selected'); $out['FeedBackNoUsersSelected'] = _('No users selected');
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize($out, 'json') $Serializer->serialize($out, 'json')
, 200 , 200
, array('Content-Type' => 'application/json') , array('Content-Type' => 'application/json')
); );
}); });
return $controller; return $controller;
} }
} }

View File

@@ -27,39 +27,36 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class MoveCollection implements ControllerProviderInterface class MoveCollection implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/', function(Application $app, Request $request) $controllers->post('/', function(Application $app, Request $request) {
{ $request = $app['request'];
$request = $app['request']; $move = new RecordHelper\MoveCollection($app['Core'], $app['request']);
$move = new RecordHelper\MoveCollection($app['Core'], $app['request']); $move->propose();
$move->propose();
$template = 'prod/actions/collection_default.twig'; $template = 'prod/actions/collection_default.twig';
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render($template, array('action' => $move, 'message' => '')); return $twig->render($template, array('action' => $move, 'message' => ''));
} }
); );
$controllers->post('/apply/', function(Application $app) $controllers->post('/apply/', function(Application $app) {
{ $request = $app['request'];
$request = $app['request']; $move = new RecordHelper\MoveCollection($app['Core'], $app['request']);
$move = new RecordHelper\MoveCollection($app['Core'], $app['request']); $move->execute($request);
$move->execute($request); $template = 'prod/actions/collection_submit.twig';
$template = 'prod/actions/collection_submit.twig';
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render($template, array('action' => $move, 'message' => '')); return $twig->render($template, array('action' => $move, 'message' => ''));
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -25,30 +25,26 @@ use Symfony\Component\HttpFoundation\Request,
class MustacheLoader implements ControllerProviderInterface class MustacheLoader implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function(Application $app, Request $request) $controllers->get('/', function(Application $app, Request $request) {
{ $template_name = $request->get('template');
$template_name = $request->get('template');
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) if ( ! preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) {
{ throw new \Exception_BadRequest('Wrong template name : ' . $template_name);
throw new \Exception_BadRequest('Wrong template name : ' . $template_name); }
}
$template_path = realpath(__DIR__ . '/../../../../../templates/web/Mustache/Prod/' . $template_name . '.Mustache.html'); $template_path = realpath(__DIR__ . '/../../../../../templates/web/Mustache/Prod/' . $template_name . '.Mustache.html');
if (!file_exists($template_path)) if ( ! file_exists($template_path)) {
{ throw new \Exception_NotFound('Template does not exists : ' . $template_path);
throw new \Exception_NotFound('Template does not exists : ' . $template_path); }
}
return new \Symfony\Component\HttpFoundation\Response(file_get_contents($template_path)); return new \Symfony\Component\HttpFoundation\Response(file_get_contents($template_path));
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -27,47 +27,43 @@ use Symfony\Component\HttpFoundation\Response;
class Printer implements ControllerProviderInterface class Printer implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/', function(Application $app) $controllers->post('/', function(Application $app) {
{ $printer = new RecordHelper\Printer($app['Core'], $app['request']);
$printer = new RecordHelper\Printer($app['Core'], $app['request']);
$template = 'prod/actions/printer_default.html.twig'; $template = 'prod/actions/printer_default.html.twig';
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render($template, array('printer' => $printer, 'message' => '')); return $twig->render($template, array('printer' => $printer, 'message' => ''));
} }
); );
$controllers->post('/print.pdf', function(Application $app) $controllers->post('/print.pdf', function(Application $app) {
{ $printer = new RecordHelper\Printer($app['Core'], $app['request']);
$printer = new RecordHelper\Printer($app['Core'], $app['request']);
$request = $app['request']; $request = $app['request'];
$session = \Session_Handler::getInstance(\appbox::get_instance($app['Core'])); $session = \Session_Handler::getInstance(\appbox::get_instance($app['Core']));
$layout = $request->get('lay'); $layout = $request->get('lay');
foreach ($printer->get_elements() as $record) foreach ($printer->get_elements() as $record) {
{ $session->get_logger($record->get_databox())
$session->get_logger($record->get_databox())
->log($record, \Session_Logger::EVENT_PRINT, $layout, ''); ->log($record, \Session_Logger::EVENT_PRINT, $layout, '');
} }
$PDF = new PDFExport($printer->get_elements(), $layout); $PDF = new PDFExport($printer->get_elements(), $layout);
return new Response($PDF->render(), 200, array('Content-Type' => 'application/pdf')); return new Response($PDF->render(), 200, array('Content-Type' => 'application/pdf'));
} }
); );
return $controllers;
}
return $controllers;
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -27,228 +27,199 @@ use Symfony\Component\HttpFoundation\Response,
class Query implements ControllerProviderInterface class Query implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->match('/', function(Application $app, Request $request) $controllers->match('/', function(Application $app, Request $request) {
{
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$registry = $appbox->get_registry(); $registry = $appbox->get_registry();
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
$query = (string) $request->get('qry'); $query = (string) $request->get('qry');
$mod = $user->getPrefs('view'); $mod = $user->getPrefs('view');
$json = array(); $json = array();
$options = new \searchEngine_options(); $options = new \searchEngine_options();
$bas = is_array($request->get('bas')) ? $request->get('bas') : array_keys($user->ACL()->get_granted_base()); $bas = is_array($request->get('bas')) ? $request->get('bas') : array_keys($user->ACL()->get_granted_base());
/* @var $user \User_Adapter */ /* @var $user \User_Adapter */
if ($user->ACL()->has_right('modifyrecord')) if ($user->ACL()->has_right('modifyrecord')) {
{ $options->set_business_fields(array());
$options->set_business_fields(array());
$BF = array(); $BF = array();
foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) {
{ if (count($bas) === 0 || in_array($collection->get_base_id(), $bas)) {
if (count($bas) === 0 || in_array($collection->get_base_id(), $bas)) $BF[] = $collection->get_base_id();
{ }
$BF[] = $collection->get_base_id(); }
} $options->set_business_fields($BF);
} } else {
$options->set_business_fields($BF); $options->set_business_fields(array());
} }
else
{
$options->set_business_fields(array());
}
$status = is_array($request->get('status')) ? $request->get('status') : array(); $status = is_array($request->get('status')) ? $request->get('status') : array();
$fields = is_array($request->get('fields')) ? $request->get('fields') : array(); $fields = is_array($request->get('fields')) ? $request->get('fields') : array();
$options->set_fields($fields); $options->set_fields($fields);
$options->set_status($status); $options->set_status($status);
$options->set_bases($bas, $user->ACL()); $options->set_bases($bas, $user->ACL());
$options->set_search_type($request->get('search_type')); $options->set_search_type($request->get('search_type'));
$options->set_record_type($request->get('recordtype')); $options->set_record_type($request->get('recordtype'));
$options->set_min_date($request->get('datemin')); $options->set_min_date($request->get('datemin'));
$options->set_max_date($request->get('datemax')); $options->set_max_date($request->get('datemax'));
$options->set_date_fields(explode('|', $request->get('datefield'))); $options->set_date_fields(explode('|', $request->get('datefield')));
$options->set_sort($request->get('sort'), $request->get('ord', PHRASEA_ORDER_DESC)); $options->set_sort($request->get('sort'), $request->get('ord', PHRASEA_ORDER_DESC));
$options->set_use_stemming($request->get('stemme')); $options->set_use_stemming($request->get('stemme'));
$form = serialize($options); $form = serialize($options);
$perPage = (int) $user->getPrefs('images_per_page'); $perPage = (int) $user->getPrefs('images_per_page');
$search_engine = new \searchEngine_adapter($registry); $search_engine = new \searchEngine_adapter($registry);
$search_engine->set_options($options); $search_engine->set_options($options);
$page = (int) $request->get('pag'); $page = (int) $request->get('pag');
if ($page < 1) if ($page < 1) {
{ $search_engine->set_is_first_page(true);
$search_engine->set_is_first_page(true); $search_engine->reset_cache();
$search_engine->reset_cache(); $page = 1;
$page = 1; }
}
$result = $search_engine->query_per_page($query, $page, $perPage); $result = $search_engine->query_per_page($query, $page, $perPage);
$proposals = $search_engine->is_first_page() ? $result->get_propositions() : false; $proposals = $search_engine->is_first_page() ? $result->get_propositions() : false;
$npages = $result->get_total_pages(); $npages = $result->get_total_pages();
$page = $result->get_current_page(); $page = $result->get_current_page();
$string = ''; $string = '';
if ($npages > 1) if ($npages > 1) {
{
$d2top = ($npages - $page); $d2top = ($npages - $page);
$d2bottom = $page; $d2bottom = $page;
if (min($d2top, $d2bottom) < 4) if (min($d2top, $d2bottom) < 4) {
{ if ($d2bottom < 4) {
if ($d2bottom < 4) for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i ++ ) {
{ if ($i == $page)
for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i ++ ) $string .= '<input onkeypress="if(event.keyCode == 13 && !isNaN(parseInt(this.value)))gotopage(parseInt(this.value))" type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" />';
{ else
if ($i == $page) $string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
$string .= '<input onkeypress="if(event.keyCode == 13 && !isNaN(parseInt(this.value)))gotopage(parseInt(this.value))" type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" />'; }
else if ($npages > 4)
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>"; $string .= "<a onclick='gotopage(" . ($npages) . ");return false;'>&gt;&gt;</a>";
} }
if ($npages > 4) else {
$string .= "<a onclick='gotopage(" . ($npages) . ");return false;'>&gt;&gt;</a>"; $start = $npages - 4;
} if (($start) > 0)
else $string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
{ else
$start = $npages - 4; $start = 1;
if (($start) > 0) for ($i = ($start); $i <= $npages; $i ++ ) {
$string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>"; if ($i == $page)
else $string .= '<input onkeypress="if(event.keyCode == 13 && !isNaN(parseInt(this.value)))gotopage(parseInt(this.value))" type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" />';
$start = 1; else
for ($i = ($start); $i <= $npages; $i ++ ) $string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
{ }
if ($i == $page) }
$string .= '<input onkeypress="if(event.keyCode == 13 && !isNaN(parseInt(this.value)))gotopage(parseInt(this.value))" type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" />'; }
else else {
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>"; $string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
}
}
}
else
{
$string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
for ($i = ($page - 2); $i <= ($page + 2); $i ++ ) for ($i = ($page - 2); $i <= ($page + 2); $i ++ ) {
{ if ($i == $page)
if ($i == $page) $string .= '<input onkeypress="if(event.keyCode == 13 && !isNaN(parseInt(this.value)))gotopage(parseInt(this.value))" type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" />';
$string .= '<input onkeypress="if(event.keyCode == 13 && !isNaN(parseInt(this.value)))gotopage(parseInt(this.value))" type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" />'; else
else $string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>"; }
}
$string .= "<a onclick='gotopage(" . ($npages) . ");return false;'>&gt;&gt;</a>"; $string .= "<a onclick='gotopage(" . ($npages) . ");return false;'>&gt;&gt;</a>";
} }
} }
$string .= '<div style="display:none;"><div id="NEXT_PAGE"></div><div id="PREV_PAGE"></div></div>'; $string .= '<div style="display:none;"><div id="NEXT_PAGE"></div><div id="PREV_PAGE"></div></div>';
$explain = "<div id=\"explainResults\" class=\"myexplain\">"; $explain = "<div id=\"explainResults\" class=\"myexplain\">";
$explain .= "<img src=\"/skins/icons/answers.gif\" /><span><b>"; $explain .= "<img src=\"/skins/icons/answers.gif\" /><span><b>";
if ($result->get_count_total_results() != $result->get_count_available_results()) if ($result->get_count_total_results() != $result->get_count_available_results()) {
{ $explain .= sprintf(_('reponses:: %d Resultats rappatries sur un total de %d trouves'), $result->get_count_available_results(), $result->get_count_total_results());
$explain .= sprintf(_('reponses:: %d Resultats rappatries sur un total de %d trouves'), $result->get_count_available_results(), $result->get_count_total_results()); } else {
} $explain .= sprintf(_('reponses:: %d Resultats'), $result->get_count_total_results());
else }
{
$explain .= sprintf(_('reponses:: %d Resultats'), $result->get_count_total_results());
}
$explain .= " </b></span>"; $explain .= " </b></span>";
$explain .= '<br><div>' . $result->get_query_time() . ' s</div>dans index ' . $result->get_search_indexes(); $explain .= '<br><div>' . $result->get_query_time() . ' s</div>dans index ' . $result->get_search_indexes();
$explain .= "</div>"; $explain .= "</div>";
$infoResult = '<a href="#" class="infoDialog" infos="' . str_replace('"', '&quot;', $explain) . '">' . sprintf(_('reponses:: %d reponses'), $result->get_count_total_results()) . '</a> | ' . sprintf(_('reponses:: %s documents selectionnes'), '<span id="nbrecsel"></span>'); $infoResult = '<a href="#" class="infoDialog" infos="' . str_replace('"', '&quot;', $explain) . '">' . sprintf(_('reponses:: %d reponses'), $result->get_count_total_results()) . '</a> | ' . sprintf(_('reponses:: %s documents selectionnes'), '<span id="nbrecsel"></span>');
$json['infos'] = $infoResult; $json['infos'] = $infoResult;
$json['navigation'] = $string; $json['navigation'] = $string;
$prop = null; $prop = null;
if ($search_engine->is_first_page()) if ($search_engine->is_first_page()) {
{ $propals = $result->get_suggestions();
$propals = $result->get_suggestions(); if (count($propals) > 0) {
if (count($propals) > 0) foreach ($propals as $prop_array) {
{ if ($prop_array['value'] !== $query && $prop_array['hits'] > $result->get_count_total_results()) {
foreach ($propals as $prop_array) $prop = $prop_array['value'];
{ break;
if ($prop_array['value'] !== $query && $prop_array['hits'] > $result->get_count_total_results()) }
{ }
$prop = $prop_array['value']; }
break; }
}
}
}
}
$core = \bootstrap::getCore(); $core = \bootstrap::getCore();
$twig = $core->getTwig(); $twig = $core->getTwig();
if ($result->get_count_total_results() === 0) if ($result->get_count_total_results() === 0) {
{ $template = 'prod/results/help.twig';
$template = 'prod/results/help.twig'; } else {
} if ($mod == 'thumbs') {
else $template = 'prod/results/answergrid.html';
{ } else {
if ($mod == 'thumbs') $template = 'prod/results/answerlist.html';
{ }
$template = 'prod/results/answergrid.html'; }
}
else
{
$template = 'prod/results/answerlist.html';
}
}
$json['results'] = $twig->render($template, array( $json['results'] = $twig->render($template, array(
'results' => $result, 'results' => $result,
'GV_social_tools' => $registry->get('GV_social_tools'), 'GV_social_tools' => $registry->get('GV_social_tools'),
'highlight' => $search_engine->get_query(), 'highlight' => $search_engine->get_query(),
'searchEngine' => $search_engine, 'searchEngine' => $search_engine,
'suggestions' => $prop 'suggestions' => $prop
) )
); );
$json['query'] = $query; $json['query'] = $query;
$json['phrasea_props'] = $proposals; $json['phrasea_props'] = $proposals;
$json['total_answers'] = (int) $result->get_count_available_results(); $json['total_answers'] = (int) $result->get_count_available_results();
$json['next_page'] = ($page < $npages && $result->get_count_available_results() > 0) ? ($page + 1) : false; $json['next_page'] = ($page < $npages && $result->get_count_available_results() > 0) ? ($page + 1) : false;
$json['prev_page'] = ($page > 1 && $result->get_count_available_results() > 0) ? ($page - 1) : false; $json['prev_page'] = ($page > 1 && $result->get_count_available_results() > 0) ? ($page - 1) : false;
$json['form'] = $form; $json['form'] = $form;
$datas = $app['Core']['Serializer']->serialize($json, 'json'); $datas = $app['Core']['Serializer']->serialize($json, 'json');
return new Response($datas, 200, array('Content-Type' => 'application/json')); return new Response($datas, 200, array('Content-Type' => 'application/json'));
}); });
return $controllers;
}
return $controllers;
}
} }

View File

@@ -31,118 +31,108 @@ use Alchemy\Phrasea\Helper;
class Root implements ControllerProviderInterface class Root implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function(Application $app) $controllers->get('/', function(Application $app) {
{
\User_Adapter::updateClientInfos(1); \User_Adapter::updateClientInfos(1);
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$registry = $app['Core']->getRegistry(); $registry = $app['Core']->getRegistry();
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
$cssPath = $registry->get('GV_RootPath') . 'www/skins/prod/'; $cssPath = $registry->get('GV_RootPath') . 'www/skins/prod/';
$css = array(); $css = array();
$cssfile = false; $cssfile = false;
$finder = new Finder(); $finder = new Finder();
$iterator = $finder $iterator = $finder
->directories() ->directories()
->depth(0) ->depth(0)
->filter(function(\SplFileInfo $fileinfo) ->filter(function(\SplFileInfo $fileinfo) {
{ return ctype_xdigit($fileinfo->getBasename());
return ctype_xdigit($fileinfo->getBasename()); })
}) ->in($cssPath);
->in($cssPath);
foreach ($iterator as $dir) foreach ($iterator as $dir) {
{ $baseName = $dir->getBaseName();
$baseName = $dir->getBaseName(); $css[$baseName] = $baseName;
$css[$baseName] = $baseName;
}
$cssfile = $user->getPrefs('css');
if (!$cssfile && isset($css['000000']))
{
$cssfile = '000000';
}
$user_feeds = \Feed_Collection::load_all($appbox, $user);
$feeds = array_merge(array($user_feeds->get_aggregate()), $user_feeds->get_feeds());
$thjslist = "";
$queries_topics = '';
if ($registry->get('GV_client_render_topics') == 'popups')
{
$queries_topics = \queries::dropdown_topics();
}
elseif ($registry->get('GV_client_render_topics') == 'tree')
{
$queries_topics = \queries::tree_topics();
}
$sbas = $bas2sbas = array();
foreach ($appbox->get_databoxes() as $databox)
{
$sbas_id = $databox->get_sbas_id();
$sbas['s' + $sbas_id] = array(
'sbid' => $sbas_id,
'seeker' => null);
foreach ($databox->get_collections() as $coll)
{
$bas2sbas['b' . $coll->get_base_id()] = array(
'sbid' => $sbas_id,
'ckobj' => array('checked' => false),
'waschecked' => false
);
} }
}
/* @var $twig \Twig_Environment */ $cssfile = $user->getPrefs('css');
$twig = $app['Core']->getTwig();
$Serializer = $app['Core']['Serializer']; if ( ! $cssfile && isset($css['000000'])) {
$cssfile = '000000';
}
$out = $twig->render('prod/index.html.twig', array(
'module_name' => 'Production',
'WorkZone' => new Helper\WorkZone($app['Core'], $app['request']),
'module_prod' => new Helper\Prod($app['Core'], $app['request']),
'cssfile' => $cssfile,
'module' => 'prod',
'events' => \eventsmanager_broker::getInstance($appbox, $app['Core']),
'GV_defaultQuery_type' => $registry->get('GV_defaultQuery_type'),
'GV_multiAndReport' => $registry->get('GV_multiAndReport'),
'GV_thesaurus' => $registry->get('GV_thesaurus'),
'cgus_agreement' => \databox_cgu::askAgreement(),
'css' => $css,
'feeds' => $feeds,
'GV_google_api' => $registry->get('GV_google_api'),
'queries_topics' => $queries_topics,
'search_status' => \databox_status::getSearchStatus(),
'queries_history' => \queries::history(),
'thesau_js_list' => $thjslist,
'thesau_json_sbas' => $Serializer->serialize($sbas, 'json'),
'thesau_json_bas2sbas' => $Serializer->serialize($bas2sbas, 'json'),
'thesau_languages' => \User_Adapter::avLanguages(),
'GV_bitly_user' => $registry->get('GV_bitly_user'),
'GV_bitly_key' => $registry->get('GV_bitly_key')
));
return new Response($out); $user_feeds = \Feed_Collection::load_all($appbox, $user);
$feeds = array_merge(array($user_feeds->get_aggregate()), $user_feeds->get_feeds());
$thjslist = "";
$queries_topics = '';
if ($registry->get('GV_client_render_topics') == 'popups') {
$queries_topics = \queries::dropdown_topics();
} elseif ($registry->get('GV_client_render_topics') == 'tree') {
$queries_topics = \queries::tree_topics();
}
$sbas = $bas2sbas = array();
foreach ($appbox->get_databoxes() as $databox) {
$sbas_id = $databox->get_sbas_id();
$sbas['s' + $sbas_id] = array(
'sbid' => $sbas_id,
'seeker' => null);
foreach ($databox->get_collections() as $coll) {
$bas2sbas['b' . $coll->get_base_id()] = array(
'sbid' => $sbas_id,
'ckobj' => array('checked' => false),
'waschecked' => false
);
}
}
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$Serializer = $app['Core']['Serializer'];
$out = $twig->render('prod/index.html.twig', array(
'module_name' => 'Production',
'WorkZone' => new Helper\WorkZone($app['Core'], $app['request']),
'module_prod' => new Helper\Prod($app['Core'], $app['request']),
'cssfile' => $cssfile,
'module' => 'prod',
'events' => \eventsmanager_broker::getInstance($appbox, $app['Core']),
'GV_defaultQuery_type' => $registry->get('GV_defaultQuery_type'),
'GV_multiAndReport' => $registry->get('GV_multiAndReport'),
'GV_thesaurus' => $registry->get('GV_thesaurus'),
'cgus_agreement' => \databox_cgu::askAgreement(),
'css' => $css,
'feeds' => $feeds,
'GV_google_api' => $registry->get('GV_google_api'),
'queries_topics' => $queries_topics,
'search_status' => \databox_status::getSearchStatus(),
'queries_history' => \queries::history(),
'thesau_js_list' => $thjslist,
'thesau_json_sbas' => $Serializer->serialize($sbas, 'json'),
'thesau_json_bas2sbas' => $Serializer->serialize($bas2sbas, 'json'),
'thesau_languages' => \User_Adapter::avLanguages(),
'GV_bitly_user' => $registry->get('GV_bitly_user'),
'GV_bitly_key' => $registry->get('GV_bitly_key')
));
return new Response($out);
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -32,320 +32,284 @@ use Alchemy\Phrasea\RouteProcessor\Basket as BasketRoute,
class Story implements ControllerProviderInterface class Story implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/create/', function(Application $app) $controllers->get('/create/', function(Application $app) {
{ /* @var $twig \Twig_Environment */
/* @var $twig \Twig_Environment */ $twig = $app['Core']->getTwig();
$twig = $app['Core']->getTwig();
return new Response($twig->render('prod/Story/Create.html.twig', array())); return new Response($twig->render('prod/Story/Create.html.twig', array()));
}); });
$controllers->post('/', function(Application $app, Request $request) $controllers->post('/', function(Application $app, Request $request) {
{ /* @var $request \Symfony\Component\HttpFoundation\Request */
/* @var $request \Symfony\Component\HttpFoundation\Request */ $em = $app['Core']->getEntityManager();
$em = $app['Core']->getEntityManager();
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
$collection = \collection::get_from_base_id($request->get('base_id')); $collection = \collection::get_from_base_id($request->get('base_id'));
if (!$user->ACL()->has_right_on_base($collection->get_base_id(), 'canaddrecord')) if ( ! $user->ACL()->has_right_on_base($collection->get_base_id(), 'canaddrecord')) {
{ throw new \Exception_Forbidden('You can not create a story on this collection');
throw new \Exception_Forbidden('You can not create a story on this collection');
}
$system_file = new \system_file(
$app['Core']->getRegistry()
->get('GV_RootPath') . 'www/skins/icons/substitution/regroup_doc.png'
);
$Story = \record_adapter::create($collection, $system_file, false, true);
foreach (explode(';', $request->get('lst')) as $sbas_rec)
{
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2)
{
continue;
} }
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
if (!$user->ACL()->has_access_to_base($record->get_base_id()) $system_file = new \system_file(
&& !$user->ACL()->has_hd_grant($record) $app['Core']->getRegistry()
&& !$user->ACL()->has_preview_grant($record)) ->get('GV_RootPath') . 'www/skins/icons/substitution/regroup_doc.png'
{
continue;
}
if ($Story->hasChild($record))
continue;
$Story->appendChild($record);
}
$metadatas = array();
foreach ($collection->get_databox()->get_meta_structure() as $meta)
{
if ($meta->get_thumbtitle())
{
$value = $request->get('name');
}
else
{
continue;
}
$metadatas[] = array(
'meta_struct_id' => $meta->get_id()
, 'meta_id' => null
, 'value' => $value
); );
break; $Story = \record_adapter::create($collection, $system_file, false, true);
}
$Story->set_metadatas($metadatas)->rebuild_subdefs(); foreach (explode(';', $request->get('lst')) as $sbas_rec) {
$sbas_rec = explode('_', $sbas_rec);
$StoryWZ = new \Entities\StoryWZ(); if (count($sbas_rec) !== 2) {
$StoryWZ->setUser($user); continue;
$StoryWZ->setRecord($Story); }
$em->persist($StoryWZ); $record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
$em->flush(); if ( ! $user->ACL()->has_access_to_base($record->get_base_id())
&& ! $user->ACL()->has_hd_grant($record)
&& ! $user->ACL()->has_preview_grant($record)) {
continue;
}
if ($Story->hasChild($record))
continue;
$Story->appendChild($record);
}
$metadatas = array();
foreach ($collection->get_databox()->get_meta_structure() as $meta) {
if ($meta->get_thumbtitle()) {
$value = $request->get('name');
} else {
continue;
}
$metadatas[] = array(
'meta_struct_id' => $meta->get_id()
, 'meta_id' => null
, 'value' => $value
);
break;
}
$Story->set_metadatas($metadatas)->rebuild_subdefs();
$StoryWZ = new \Entities\StoryWZ();
$StoryWZ->setUser($user);
$StoryWZ->setRecord($Story);
$em->persist($StoryWZ);
$em->flush();
if ($request->getRequestFormat() == 'json') {
$data = array(
'success' => true
, 'message' => _('Story created')
, 'WorkZone' => $StoryWZ->getId()
, 'story' => array(
'sbas_id' => $Story->get_sbas_id(),
'record_id' => $Story->get_record_id(),
)
);
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse(sprintf('/%d/', $StoryWZ->getId()));
}
});
$controllers->get('/{sbas_id}/{record_id}/', function(Application $app, $sbas_id, $record_id) {
$Story = new \record_adapter($sbas_id, $record_id);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$html = $twig->render('prod/WorkZone/Story.html.twig', array('Story' => $Story));
return new Response($html);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post(
'/{sbas_id}/{record_id}/addElements/'
, function(Application $app, Request $request, $sbas_id, $record_id) {
$Story = new \record_adapter($sbas_id, $record_id);
$user = $app['Core']->getAuthenticatedUser();
if ( ! $user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord'))
throw new \Exception_Forbidden('You can not add document to this Story');
/* @var $user \User_Adapter */
$n = 0;
foreach (explode(';', $request->get('lst')) as $sbas_rec) {
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2)
continue;
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
if ( ! $user->ACL()->has_access_to_base($record->get_base_id())
&& ! $user->ACL()->has_hd_grant($record)
&& ! $user->ACL()->has_preview_grant($record)) {
continue;
}
if ($Story->hasChild($record))
continue;
$Story->appendChild($record);
$n ++;
}
if ($request->getRequestFormat() == 'json')
{
$data = array( $data = array(
'success' => true 'success' => true
, 'message' => _('Story created') , 'message' => sprintf(_('%d records added'), $n)
, 'WorkZone' => $StoryWZ->getId()
, 'story' => array(
'sbas_id' => $Story->get_sbas_id(),
'record_id' => $Story->get_record_id(),
)
); );
$datas = $app['Core']['Serializer']->serialize($data, 'json'); if ($request->getRequestFormat() == 'json') {
return new Response($datas, 200, array('Content-type' => 'application/json')); $datas = $app['Core']['Serializer']->serialize($data, 'json');
}
else
{
return new RedirectResponse(sprintf('/%d/', $StoryWZ->getId()));
}
});
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
$controllers->get('/{sbas_id}/{record_id}/', function(Application $app, $sbas_id, $record_id) return new RedirectResponse('/');
{
$Story = new \record_adapter($sbas_id, $record_id);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$html = $twig->render('prod/WorkZone/Story.html.twig', array('Story' => $Story));
return new Response($html);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post(
'/{sbas_id}/{record_id}/addElements/'
, function(Application $app, Request $request, $sbas_id, $record_id)
{
$Story = new \record_adapter($sbas_id, $record_id);
$user = $app['Core']->getAuthenticatedUser();
if (!$user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord'))
throw new \Exception_Forbidden('You can not add document to this Story');
/* @var $user \User_Adapter */
$n = 0;
foreach (explode(';', $request->get('lst')) as $sbas_rec)
{
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2)
continue;
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
if (!$user->ACL()->has_access_to_base($record->get_base_id())
&& !$user->ACL()->has_hd_grant($record)
&& !$user->ACL()->has_preview_grant($record))
{
continue;
} }
if ($Story->hasChild($record))
continue;
$Story->appendChild($record);
$n++;
}
$data = array(
'success' => true
, 'message' => sprintf(_('%d records added'), $n)
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse('/');
}
})->assert('sbas_id', '\d+')->assert('record_id', '\d+'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post( $controllers->post(
'/{sbas_id}/{record_id}/delete/{child_sbas_id}/{child_record_id}/' '/{sbas_id}/{record_id}/delete/{child_sbas_id}/{child_record_id}/'
, function(Application $app, Request $request, $sbas_id, $record_id, $child_sbas_id, $child_record_id) , function(Application $app, Request $request, $sbas_id, $record_id, $child_sbas_id, $child_record_id) {
{ $Story = new \record_adapter($sbas_id, $record_id);
$Story = new \record_adapter($sbas_id, $record_id);
$record = new \record_adapter($child_sbas_id, $child_record_id); $record = new \record_adapter($child_sbas_id, $child_record_id);
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
if (!$user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) if ( ! $user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord'))
throw new \Exception_Forbidden('You can not add document to this Story'); throw new \Exception_Forbidden('You can not add document to this Story');
/* @var $user \User_Adapter */ /* @var $user \User_Adapter */
$Story->removeChild($record); $Story->removeChild($record);
$data = array( $data = array(
'success' => true 'success' => true
, 'message' => _('Record removed from story') , 'message' => _('Record removed from story')
); );
if ($request->getRequestFormat() == 'json') if ($request->getRequestFormat() == 'json') {
{
$datas = $app['Core']['Serializer']->serialize($data, 'json'); $datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json')); return new Response($datas, 200, array('Content-type' => 'application/json'));
} } else {
else
{
return new RedirectResponse('/'); return new RedirectResponse('/');
} }
}) })
->assert('sbas_id', '\d+') ->assert('sbas_id', '\d+')
->assert('record_id', '\d+') ->assert('record_id', '\d+')
->assert('child_sbas_id', '\d+') ->assert('child_sbas_id', '\d+')
->assert('child_record_id', '\d+'); ->assert('child_record_id', '\d+');
/** /**
* Get the Basket reorder form * Get the Basket reorder form
*/ */
$controllers->get( $controllers->get(
'/{sbas_id}/{record_id}/reorder/' '/{sbas_id}/{record_id}/reorder/'
, function(Application $app, $sbas_id, $record_id) , function(Application $app, $sbas_id, $record_id) {
{ /* @var $em \Doctrine\ORM\EntityManager */
/* @var $em \Doctrine\ORM\EntityManager */ $em = $app['Core']->getEntityManager();
$em = $app['Core']->getEntityManager();
$story = new \record_adapter($sbas_id, $record_id); $story = new \record_adapter($sbas_id, $record_id);
if (!$story->is_grouping()) if ( ! $story->is_grouping()) {
{
throw new \Exception('This is not a story'); throw new \Exception('This is not a story');
} }
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return new Response( return new Response(
$twig->render( $twig->render(
'prod/Story/Reorder.html.twig' 'prod/Story/Reorder.html.twig'
, array('story' => $story) , array('story' => $story)
) )
); );
}) })
->assert('sbas_id', '\d+') ->assert('sbas_id', '\d+')
->assert('record_id', '\d+'); ->assert('record_id', '\d+');
$controllers->post( $controllers->post(
'/{sbas_id}/{record_id}/reorder/' '/{sbas_id}/{record_id}/reorder/'
, function(Application $app, $sbas_id, $record_id) , function(Application $app, $sbas_id, $record_id) {
{ $ret = array('success' => false, 'message' => _('An error occured'));
$ret = array('success' => false, 'message' => _('An error occured')); try {
try
{
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
/* @var $user \User_Adapter */ /* @var $user \User_Adapter */
$story = new \record_adapter($sbas_id, $record_id); $story = new \record_adapter($sbas_id, $record_id);
if (!$story->is_grouping()) if ( ! $story->is_grouping()) {
{ throw new \Exception('This is not a story');
throw new \Exception('This is not a story');
} }
if (!$user->ACL()->has_right_on_base($story->get_base_id(), 'canmodifrecord')) if ( ! $user->ACL()->has_right_on_base($story->get_base_id(), 'canmodifrecord')) {
{ throw new ControllerException(_('You can not edit this story'));
throw new ControllerException(_('You can not edit this story'));
} }
$sql = 'UPDATE regroup SET ord = :ord $sql = 'UPDATE regroup SET ord = :ord
WHERE rid_parent = :parent_id AND rid_child = :children_id'; WHERE rid_parent = :parent_id AND rid_child = :children_id';
$stmt = $story->get_databox()->get_connection()->prepare($sql); $stmt = $story->get_databox()->get_connection()->prepare($sql);
foreach ($app['request']->get('element') as $record_id => $ord) foreach ($app['request']->get('element') as $record_id => $ord) {
{ $params = array(
$params = array( ':ord' => $ord,
':ord' => $ord, ':parent_id' => $story->get_record_id(),
':parent_id' => $story->get_record_id(), ':children_id' => $record_id
':children_id' => $record_id );
); $stmt->execute($params);
$stmt->execute($params);
} }
$stmt->closeCursor(); $stmt->closeCursor();
$ret = array('success' => true, 'message' => _('Story updated')); $ret = array('success' => true, 'message' => _('Story updated'));
} } catch (ControllerException $e) {
catch (ControllerException $e)
{
$ret = array('success' => false, 'message' => $e->getMessage()); $ret = array('success' => false, 'message' => $e->getMessage());
} } catch (\Exception $e) {
catch (\Exception $e)
{
} }
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response($Serializer->serialize($ret, 'json'), 200, array('Content-type' => 'application/json')); return new Response($Serializer->serialize($ret, 'json'), 200, array('Content-type' => 'application/json'));
}) })
->assert('sbas_id', '\d+') ->assert('sbas_id', '\d+')
->assert('record_id', '\d+'); ->assert('record_id', '\d+');
return $controllers; return $controllers;
} }
} }

View File

@@ -29,42 +29,37 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class TOU implements ControllerProviderInterface class TOU implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/deny/{sbas_id}/', function(Application $app, Request $request, $sbas_id) $controllers->post('/deny/{sbas_id}/', function(Application $app, Request $request, $sbas_id) {
{ $ret = array('success' => false, 'message' => '');
$ret = array('success' => false, 'message' => '');
try try {
{ $user = $app['Core']->getAuthenticatedUser();
$user = $app['Core']->getAuthenticatedUser(); $session = \Session_Handler::getInstance(\appbox::get_instance($app['Core']));
$session = \Session_Handler::getInstance(\appbox::get_instance($app['Core']));
$databox = \databox::get_instance((int) $sbas_id); $databox = \databox::get_instance((int) $sbas_id);
$user->ACL()->revoke_access_from_bases( $user->ACL()->revoke_access_from_bases(
$user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) $user->ACL()->get_granted_base(array(), array($databox->get_sbas_id()))
); );
$user->ACL()->revoke_unused_sbas_rights(); $user->ACL()->revoke_unused_sbas_rights();
$session->logout(); $session->logout();
$ret = array('success' => true, 'message' => ''); $ret = array('success' => true, 'message' => '');
} } catch (\Exception $e) {
catch (\Exception $e)
{
} }
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
$datas = $Serializer->serialize($ret, 'json'); $datas = $Serializer->serialize($ret, 'json');
return new Response($datas, 200, array('Content-Type' => 'application/json')); return new Response($datas, 200, array('Content-Type' => 'application/json'));
}); });
return $controllers;
}
return $controllers;
}
} }

View File

@@ -36,287 +36,243 @@ class Tools implements ControllerProviderInterface
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function(Application $app, Request $request) $controllers->get('/', function(Application $app, Request $request) {
{ $helper = new Helper\Record\Tools($app['Core'], $request);
$helper = new Helper\Record\Tools($app['Core'], $request);
$selection = $helper->get_elements(); $selection = $helper->get_elements();
$binary = $app['Core']->getRegistry()->get('GV_exiftool'); $binary = $app['Core']->getRegistry()->get('GV_exiftool');
$metadatas = false; $metadatas = false;
$record = null; $record = null;
$metadatasFirst = $metadatasSecond = array(); $metadatasFirst = $metadatasSecond = array();
if (count($selection) == 1 && ! empty($binary)) if (count($selection) == 1 && ! empty($binary)) {
{ try {
try $record = reset($selection);
{ $file = $record->get_subdef('document')->get_pathfile();
$record = reset($selection); $cmd = $binary . ' -h ' . escapeshellarg($file);
$file = $record->get_subdef('document')->get_pathfile();
$cmd = $binary . ' -h ' . escapeshellarg($file);
$out = ""; $out = "";
exec($cmd, $out); exec($cmd, $out);
foreach ($out as $liout) foreach ($out as $liout) {
{ if (strpos($liout, '<tr><td>Directory') === false)
if (strpos($liout, '<tr><td>Directory') === false) $metadatasFirst[] = $liout;
$metadatasFirst[] = $liout; }
} $out = "";
$out = ""; $cmd = $binary . ' -X -n -fast ' . escapeshellarg($file) . '';
$cmd = $binary . ' -X -n -fast ' . escapeshellarg($file) . ''; exec($cmd, $out);
exec($cmd, $out); foreach ($out as $liout) {
foreach ($out as $liout) $metadatasSecond[] = htmlentities($liout);
{ }
$metadatasSecond[] = htmlentities($liout); $metadatas = true;
} } catch (\Exception $e) {
$metadatas = true;
}
catch (\Exception $e)
{
} }
} }
$template = 'prod/actions/Tools/index.html.twig'; $template = 'prod/actions/Tools/index.html.twig';
$var = array( $var = array(
'helper' => $helper, 'helper' => $helper,
'selection' => $selection, 'selection' => $selection,
'record' => $record, 'record' => $record,
'metadatas' => $metadatas, 'metadatas' => $metadatas,
'metadatasFirst' => $metadatasFirst, 'metadatasFirst' => $metadatasFirst,
'metadatasSecond' => $metadatasSecond 'metadatasSecond' => $metadatasSecond
); );
return new Response($app['Core']->getTwig()->render($template, $var)); return new Response($app['Core']->getTwig()->render($template, $var));
}); });
$controllers->post('/rotate/', function(Application $app, Request $request) $controllers->post('/rotate/', function(Application $app, Request $request) {
{ $return = array('success' => false, 'errorMessage' => '');
$return = array('success' => false, 'errorMessage' => '');
$helper = new Helper\Record\Tools($app['Core'], $request); $helper = new Helper\Record\Tools($app['Core'], $request);
$rotation = in_array($request->get('rotation'), array('-90', '90', '180')) ? $request->get('rotation', 90) : 90; $rotation = in_array($request->get('rotation'), array('-90', '90', '180')) ? $request->get('rotation', 90) : 90;
$selection = $helper->get_elements(); $selection = $helper->get_elements();
foreach ($selection as $record) foreach ($selection as $record) {
{ try {
try $record->rotate_subdefs($rotation);
{ $return['success'] = true;
$record->rotate_subdefs($rotation); } catch (\Exception $e) {
$return['success'] = true; $return['errorMessage'] = $e->getMessage();
} }
catch (\Exception $e) }
{
$return['errorMessage'] = $e->getMessage();
}
}
$json = $app['Core']->getSerializer()->serialize($return, 'json'); $json = $app['Core']->getSerializer()->serialize($return, 'json');
return new Response($json, 200, array('content-type' => 'application/json')); return new Response($json, 200, array('content-type' => 'application/json'));
}); });
$controllers->post('/image/', function(Application $app, Request $request) $controllers->post('/image/', function(Application $app, Request $request) {
{ $return = array('success' => true);
$return = array('success' => true);
$helper = new Helper\Record\Tools($app['Core'], $request); $helper = new Helper\Record\Tools($app['Core'], $request);
$selection = $helper->get_elements(); $selection = $helper->get_elements();
if ($request->get('ForceThumbSubstit') == '1') if ($request->get('ForceThumbSubstit') == '1') {
{ foreach ($selection as $record) {
foreach ($selection as $record) try {
{ $record->rebuild_subdefs();
try } catch (\Exception $e) {
{ $return['success'] = false;
$record->rebuild_subdefs(); $return['message'] = _('an error occured');
} }
catch (\Exception $e) }
{ }
$return['success'] = false;
$return['message'] = _('an error occured');
}
}
}
$json = $app['Core']->getSerializer()->serialize($return, 'json'); $json = $app['Core']->getSerializer()->serialize($return, 'json');
return new Response($json, 200, array('content-type' => 'application/json')); return new Response($json, 200, array('content-type' => 'application/json'));
}); });
$controllers->post('/hddoc/', function(Application $app, Request $request) $controllers->post('/hddoc/', function(Application $app, Request $request) {
{ $success = false;
$success = false; $errorMessage = "";
$errorMessage = ""; $fileName = null;
$fileName = null;
if ($file = $request->files->get('newHD')) if ($file = $request->files->get('newHD')) {
{ $fileName = $file->getClientOriginalName();
$fileName = $file->getClientOriginalName(); $size = $file->getClientSize();
$size = $file->getClientSize();
if ($size && $fileName && $file->isValid()) if ($size && $fileName && $file->isValid()) {
{
try try {
{ $record = new \record_adapter(
$record = new \record_adapter( $request->get('sbas_id')
$request->get('sbas_id') , $request->get('record_id')
, $request->get('record_id') );
);
$record->substitute_subdef( $record->substitute_subdef(
'document' 'document'
, new \system_file($file->getPathname()) , new \system_file($file->getPathname())
); );
if ((int) $request->get('ccfilename') === 1) if ((int) $request->get('ccfilename') === 1) {
{ $record->set_original_name($fileName);
$record->set_original_name($fileName); }
}
$success = true; $success = true;
} } catch (\Exception $e) {
catch (\Exception $e) $errorMessage = $e->getMessage();
{ }
$errorMessage = $e->getMessage(); } else {
} $errorMessage = _('file is not valid');
} }
else }
{
$errorMessage = _('file is not valid');
}
}
$template = 'prod/actions/Tools/iframeUpload.html.twig'; $template = 'prod/actions/Tools/iframeUpload.html.twig';
$var = array( $var = array(
'success' => $success
, 'fileName' => $fileName
, 'errorMessage' => $errorMessage
);
return new Response($app['Core']->getTwig()->render($template, $var));
/**
*
*/
});
$controllers->post('/chgthumb/', function(Application $app, Request $request)
{
$success = false;
$errorMessage = "";
if ($file = $request->files->get('newThumb'))
{
$size = $file->getClientSize();
$fileName = $file->getClientOriginalName();
if ($size && $fileName && $file->isValid())
{
try
{
$rootPath = $app['Core']->getRegistry()->get('GV_RootPath');
$tmpFile = $rootPath . 'tmp/' . $fileName;
rename($file->getPathname(), $tmpFile);
$record = new \record_adapter(
$request->get('sbas_id')
, $request->get('record_id')
);
$record->substitute_subdef(
'thumbnail'
, new \system_file($tmpFile)
);
$success = true;
}
catch (\Exception $e)
{
$errorMessage = $e->getMessage();
}
}
else
{
$errorMessage = _('file is not valid');
}
$template = 'prod/actions/Tools/iframeUpload.html.twig';
$var = array(
'success' => $success 'success' => $success
, 'fileName' => $fileName , 'fileName' => $fileName
, 'errorMessage' => $errorMessage , 'errorMessage' => $errorMessage
); );
return new Response($app['Core']->getTwig()->render($template, $var)); return new Response($app['Core']->getTwig()->render($template, $var));
}
});
$controllers->post('/thumb-extractor/confirm-box/', function(Application $app, Request $request) /**
{ *
$return = array('error' => false, 'datas' => ''); */
$template = 'prod/actions/Tools/confirm.html.twig'; });
try $controllers->post('/chgthumb/', function(Application $app, Request $request) {
{ $success = false;
$record = new \record_adapter($request->get('sbas_id'), $request->get('record_id')); $errorMessage = "";
$var = array(
'video_title' => $record->get_title()
, 'image' => $request->get('image', '')
);
$return['datas'] = $app['Core']->getTwig()->render($template, $var);
}
catch (\Exception $e)
{
$return['datas'] = _('an error occured');
$return['error'] = true;
}
$json = $app['Core']->getSerializer()->serialize($return, 'json'); if ($file = $request->files->get('newThumb')) {
return new Response($json, 201, array('content-type' => 'application/json')); $size = $file->getClientSize();
}); $fileName = $file->getClientOriginalName();
$controllers->post('/thumb-extractor/apply/', function(Application $app, Request $request) if ($size && $fileName && $file->isValid()) {
{ try {
$return = array('success' => false, 'message' => ''); $rootPath = $app['Core']->getRegistry()->get('GV_RootPath');
$tmpFile = $rootPath . 'tmp/' . $fileName;
rename($file->getPathname(), $tmpFile);
try $record = new \record_adapter(
{ $request->get('sbas_id')
$record = new \record_adapter($request->get('sbas_id'), $request->get('record_id')); , $request->get('record_id')
);
$dataUri = DataURI\Parser::parse($request->get('image', '')); $record->substitute_subdef(
'thumbnail'
, new \system_file($tmpFile)
);
$path = $app['Core']->getRegistry()->get('GV_RootPath') . 'tmp'; $success = true;
} catch (\Exception $e) {
$errorMessage = $e->getMessage();
}
} else {
$errorMessage = _('file is not valid');
}
$name = sprintf('extractor_thumb_%s', $record->get_serialize_key()); $template = 'prod/actions/Tools/iframeUpload.html.twig';
$var = array(
'success' => $success
, 'fileName' => $fileName
, 'errorMessage' => $errorMessage
);
$fileName = sprintf('%s/%s.png', $path, $name); return new Response($app['Core']->getTwig()->render($template, $var));
}
});
file_put_contents($fileName, $dataUri->getData()); $controllers->post('/thumb-extractor/confirm-box/', function(Application $app, Request $request) {
$return = array('error' => false, 'datas' => '');
$template = 'prod/actions/Tools/confirm.html.twig';
$record->substitute_subdef('thumbnail', new \system_file($fileName)); try {
$record = new \record_adapter($request->get('sbas_id'), $request->get('record_id'));
$var = array(
'video_title' => $record->get_title()
, 'image' => $request->get('image', '')
);
$return['datas'] = $app['Core']->getTwig()->render($template, $var);
} catch (\Exception $e) {
$return['datas'] = _('an error occured');
$return['error'] = true;
}
$return['success'] = true; $json = $app['Core']->getSerializer()->serialize($return, 'json');
}
catch (\Exception $e)
{
$return['message'] = $e->getMessage();
}
$json = $app['Core']->getSerializer()->serialize($return, 'json'); return new Response($json, 201, array('content-type' => 'application/json'));
});
return new Response($json, 201, array('content-type' => 'application/json')); $controllers->post('/thumb-extractor/apply/', function(Application $app, Request $request) {
}); $return = array('success' => false, 'message' => '');
try {
$record = new \record_adapter($request->get('sbas_id'), $request->get('record_id'));
$dataUri = DataURI\Parser::parse($request->get('image', ''));
$path = $app['Core']->getRegistry()->get('GV_RootPath') . 'tmp';
$name = sprintf('extractor_thumb_%s', $record->get_serialize_key());
$fileName = sprintf('%s/%s.png', $path, $name);
file_put_contents($fileName, $dataUri->getData());
$record->substitute_subdef('thumbnail', new \system_file($fileName));
$return['success'] = true;
} catch (\Exception $e) {
$return['message'] = $e->getMessage();
}
$json = $app['Core']->getSerializer()->serialize($return, 'json');
return new Response($json, 201, array('content-type' => 'application/json'));
});
return $controllers; return $controllers;
} }
} }

View File

@@ -29,178 +29,166 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class Tooltip implements ControllerProviderInterface class Tooltip implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$app['appbox'] = \appbox::get_instance($app['Core']); $app['appbox'] = \appbox::get_instance($app['Core']);
$controllers->post('/basket/{basket_id}/' $controllers->post('/basket/{basket_id}/'
, function(Application $app, $basket_id) , function(Application $app, $basket_id) {
{ $em = $app['Core']->getEntityManager();
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket') $basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false); ->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render('prod/Tooltip/Basket.html.twig', array('basket' => $basket)); return $twig->render('prod/Tooltip/Basket.html.twig', array('basket' => $basket));
})->assert('basket_id', '\d+'); })->assert('basket_id', '\d+');
$controllers->post('/Story/{sbas_id}/{record_id}/' $controllers->post('/Story/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $record_id) , function(Application $app, $sbas_id, $record_id) {
{ $Story = new \record_adapter($sbas_id, $record_id);
$Story = new \record_adapter($sbas_id, $record_id);
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return $twig->render('prod/Tooltip/Story.html.twig', array('Story' => $Story)); return $twig->render('prod/Tooltip/Story.html.twig', array('Story' => $Story));
})->assert('sbas_id', '\d+')->assert('record_id', '\d+'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post('/user/{usr_id}/' $controllers->post('/user/{usr_id}/'
, function(Application $app, $usr_id) , function(Application $app, $usr_id) {
{ $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
$user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return new Response($twig->render( return new Response($twig->render(
'prod/Tooltip/User.html.twig' 'prod/Tooltip/User.html.twig'
, array('user' => $user) , array('user' => $user)
) )
); );
})->assert('usr_id', '\d+'); })->assert('usr_id', '\d+');
$controllers->post('/preview/{sbas_id}/{record_id}/' $controllers->post('/preview/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $record_id) , function(Application $app, $sbas_id, $record_id) {
{ $record = new \record_adapter($sbas_id, $record_id);
$record = new \record_adapter($sbas_id, $record_id);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response($twig->render(
'common/preview.html'
, array(
'record' => $record
, 'not_wrapped' => true
)
)
);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post('/caption/{sbas_id}/{record_id}/{view}/'
, function(Application $app, $sbas_id, $record_id, $view)
{
$number = (int) $app['request']->get('number');
$record = new \record_adapter($sbas_id, $record_id, $number);
$search_engine = null;
if($view == 'answer')
{
if (($search_engine_options = unserialize($app['request']->get('options_serial'))) !== false)
{
$search_engine = new \searchEngine_adapter($app['appbox']->get_registry());
$search_engine->set_options($search_engine_options);
}
}
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return new Response( return new Response($twig->render(
$twig->render( 'common/preview.html'
'common/caption.html' , array(
, array( 'record' => $record
'record' => $record , 'not_wrapped' => true
, 'view' => $view )
, 'highlight' => $app['request']->get('query') )
, 'searchEngine' => $search_engine );
)
)
);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post('/tc_datas/{sbas_id}/{record_id}/' $controllers->post('/caption/{sbas_id}/{record_id}/{view}/'
, function(Application $app, $sbas_id, $record_id) , function(Application $app, $sbas_id, $record_id, $view) {
{ $number = (int) $app['request']->get('number');
$record = new \record_adapter($sbas_id, $record_id); $record = new \record_adapter($sbas_id, $record_id, $number);
$document = $record->get_subdef('document');
/* @var $twig \Twig_Environment */ $search_engine = null;
$twig = $app['Core']->getTwig();
return new Response( if ($view == 'answer') {
$twig->render( if (($search_engine_options = unserialize($app['request']->get('options_serial'))) !== false) {
'common/technical_datas.twig' $search_engine = new \searchEngine_adapter($app['appbox']->get_registry());
, array('record' => $record, 'document' => $document) $search_engine->set_options($search_engine_options);
) }
); }
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'common/caption.html'
, array(
'record' => $record
, 'view' => $view
, 'highlight' => $app['request']->get('query')
, 'searchEngine' => $search_engine
)
)
);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post('/metas/FieldInfos/{sbas_id}/{field_id}/' $controllers->post('/tc_datas/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $field_id) , function(Application $app, $sbas_id, $record_id) {
{ $record = new \record_adapter($sbas_id, $record_id);
$databox = \databox::get_instance((int) $sbas_id); $document = $record->get_subdef('document');
$field = \databox_field::get_instance($databox, $field_id);
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return new Response( return new Response(
$twig->render( $twig->render(
'common/databox_field.twig' 'common/technical_datas.twig'
, array('field' => $field) , array('record' => $record, 'document' => $document)
) )
); );
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post('/metas/FieldInfos/{sbas_id}/{field_id}/'
, function(Application $app, $sbas_id, $field_id) {
$databox = \databox::get_instance((int) $sbas_id);
$field = \databox_field::get_instance($databox, $field_id);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'common/databox_field.twig'
, array('field' => $field)
)
);
})->assert('sbas_id', '\d+')->assert('field_id', '\d+'); })->assert('sbas_id', '\d+')->assert('field_id', '\d+');
$controllers->post('/DCESInfos/{sbas_id}/{field_id}/' $controllers->post('/DCESInfos/{sbas_id}/{field_id}/'
, function(Application $app, $sbas_id, $field_id) , function(Application $app, $sbas_id, $field_id) {
{ $databox = \databox::get_instance((int) $sbas_id);
$databox = \databox::get_instance((int) $sbas_id); $field = \databox_field::get_instance($databox, $field_id);
$field = \databox_field::get_instance($databox, $field_id);
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return new Response( return new Response(
$twig->render( $twig->render(
'common/databox_field_DCES.twig' 'common/databox_field_DCES.twig'
, array('field' => $field) , array('field' => $field)
) )
); );
})->assert('sbas_id', '\d+')->assert('field_id', '\d+'); })->assert('sbas_id', '\d+')->assert('field_id', '\d+');
$controllers->post('/metas/restrictionsInfos/{sbas_id}/{field_id}/' $controllers->post('/metas/restrictionsInfos/{sbas_id}/{field_id}/'
, function(Application $app, $sbas_id, $field_id) , function(Application $app, $sbas_id, $field_id) {
{ $databox = \databox::get_instance((int) $sbas_id);
$databox = \databox::get_instance((int) $sbas_id); $field = \databox_field::get_instance($databox, $field_id);
$field = \databox_field::get_instance($databox, $field_id);
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
return new Response( return new Response(
$twig->render( $twig->render(
'common/databox_field_restrictions.twig' 'common/databox_field_restrictions.twig'
, array('field' => $field) , array('field' => $field)
) )
); );
})->assert('sbas_id', '\d+')->assert('field_id', '\d+'); })->assert('sbas_id', '\d+')->assert('field_id', '\d+');
return $controllers; return $controllers;
} }
} }

View File

@@ -31,39 +31,34 @@ use Alchemy\Phrasea\RouteProcessor\Basket as BasketRoute,
class UserPreferences implements ControllerProviderInterface class UserPreferences implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->post('/save/', function(Application $app, Request $request) $controllers->post('/save/', function(Application $app, Request $request) {
{ $ret = array('success' => false, 'message' => _('Error while saving preference'));
$ret = array('success' => false, 'message' => _('Error while saving preference'));
try try {
{ $user = $app['Core']->getAuthenticatedUser();
$user = $app['Core']->getAuthenticatedUser();
$ret = $user->setPrefs($request->get('prop'), $request->get('value')); $ret = $user->setPrefs($request->get('prop'), $request->get('value'));
if ($ret == $request->get('value')) if ($ret == $request->get('value'))
$output = "1"; $output = "1";
else else
$output = "0"; $output = "0";
$ret = array('success' => true, 'message' => _('Preference saved !')); $ret = array('success' => true, 'message' => _('Preference saved !'));
} } catch (\Exception $e) {
catch (\Exception $e)
{
} }
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
$datas = $Serializer->serialize($ret, 'json'); $datas = $Serializer->serialize($ret, 'json');
return new Response($datas, 200, array('Content-Type' => 'application/json')); return new Response($datas, 200, array('Content-Type' => 'application/json'));
}); });
return $controllers;
}
return $controllers;
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -31,242 +31,217 @@ use Alchemy\Phrasea\RouteProcessor\WorkZone as RouteWorkZone,
class WorkZone implements ControllerProviderInterface class WorkZone implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function(Application $app) $controllers->get('/', function(Application $app) {
{ $params = array(
$params = array( 'WorkZone' => new Helper\WorkZone($app['Core'], $app['request'])
'WorkZone' => new Helper\WorkZone($app['Core'], $app['request']) , 'selected_type' => $app['request']->get('type')
, 'selected_type' => $app['request']->get('type') , 'selected_id' => $app['request']->get('id')
, 'selected_id' => $app['request']->get('id') , 'srt' => $app['request']->get('sort')
, 'srt' => $app['request']->get('sort') );
);
return new Response($app['Core']->getTwig()->render('prod/WorkZone/WorkZone.html.twig', $params)); return new Response($app['Core']->getTwig()->render('prod/WorkZone/WorkZone.html.twig', $params));
}); });
$controllers->get('/Browse/', function(Application $app) $controllers->get('/Browse/', function(Application $app) {
{ $date_obj = new \DateTime();
$date_obj = new \DateTime();
$params = array( $params = array(
'CurrentYear' => $date_obj->format('Y') 'CurrentYear' => $date_obj->format('Y')
); );
return new Response( return new Response(
$app['Core']->getTwig()->render('prod/WorkZone/Browser/Browser.html.twig' $app['Core']->getTwig()->render('prod/WorkZone/Browser/Browser.html.twig'
, $params , $params
) )
); );
}); });
$controllers->get('/Browse/Search/', function(Application $app) $controllers->get('/Browse/Search/', function(Application $app) {
{
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
$request = $app['request']; $request = $app['request'];
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
/* @var $em \Doctrine\ORM\EntityManager */ /* @var $em \Doctrine\ORM\EntityManager */
$BasketRepo = $em->getRepository('\Entities\Basket'); $BasketRepo = $em->getRepository('\Entities\Basket');
$Page = (int) $request->get('Page', 0); $Page = (int) $request->get('Page', 0);
$PerPage = 10; $PerPage = 10;
$offsetStart = max(($Page - 1) * $PerPage, 0); $offsetStart = max(($Page - 1) * $PerPage, 0);
$Baskets = $BasketRepo->findWorkzoneBasket( $Baskets = $BasketRepo->findWorkzoneBasket(
$user $user
, $request->get('Query') , $request->get('Query')
, $request->get('Year') , $request->get('Year')
, $request->get('Type') , $request->get('Type')
, $offsetStart , $offsetStart
, $PerPage , $PerPage
); );
$page = floor($offsetStart / $PerPage) + 1; $page = floor($offsetStart / $PerPage) + 1;
$maxPage = floor(count($Baskets) / $PerPage) + 1; $maxPage = floor(count($Baskets) / $PerPage) + 1;
$params = array( $params = array(
'Baskets' => $Baskets 'Baskets' => $Baskets
, 'Page' => $page , 'Page' => $page
, 'MaxPage' => $maxPage , 'MaxPage' => $maxPage
, 'Total' => count($Baskets) , 'Total' => count($Baskets)
, 'Query' => $request->get('Query') , 'Query' => $request->get('Query')
, 'Year' => $request->get('Year') , 'Year' => $request->get('Year')
, 'Type' => $request->get('Type') , 'Type' => $request->get('Type')
); );
return new Response($app['Core']->getTwig()->render('prod/WorkZone/Browser/Results.html.twig', $params)); return new Response($app['Core']->getTwig()->render('prod/WorkZone/Browser/Results.html.twig', $params));
}); });
$controllers->get('/Browse/Basket/{basket_id}/', function(Application $app, Request $request, $basket_id) $controllers->get('/Browse/Basket/{basket_id}/', function(Application $app, Request $request, $basket_id) {
{
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket') $basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false); ->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
$params = array( $params = array(
'Basket' => $basket 'Basket' => $basket
); );
return new Response($app['Core']->getTwig()->render('prod/WorkZone/Browser/Basket.html.twig', $params)); return new Response($app['Core']->getTwig()->render('prod/WorkZone/Browser/Basket.html.twig', $params));
})->assert('basket_id', '\d+'); })->assert('basket_id', '\d+');
$controllers->post( $controllers->post(
'/attachStories/' '/attachStories/'
, function(Application $app, Request $request) , function(Application $app, Request $request) {
{ if ( ! $request->get('stories'))
if (!$request->get('stories')) throw new \Exception_BadRequest();
throw new \Exception_BadRequest();
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
/* @var $em \Doctrine\ORM\EntityManager */ /* @var $em \Doctrine\ORM\EntityManager */
$StoryWZRepo = $em->getRepository('\Entities\StoryWZ'); $StoryWZRepo = $em->getRepository('\Entities\StoryWZ');
$alreadyFixed = $done = 0; $alreadyFixed = $done = 0;
$stories = $request->get('stories', array()); $stories = $request->get('stories', array());
foreach ($stories as $element) foreach ($stories as $element) {
{ $element = explode('_', $element);
$element = explode('_', $element); $Story = new \record_adapter($element[0], $element[1]);
$Story = new \record_adapter($element[0], $element[1]);
if (!$Story->is_grouping()) if ( ! $Story->is_grouping())
throw new \Exception('You can only attach stories'); throw new \Exception('You can only attach stories');
if (!$user->ACL()->has_access_to_base($Story->get_base_id())) if ( ! $user->ACL()->has_access_to_base($Story->get_base_id()))
throw new \Exception_Forbidden('You do not have access to this Story'); throw new \Exception_Forbidden('You do not have access to this Story');
if ($StoryWZRepo->findUserStory($user, $Story)) if ($StoryWZRepo->findUserStory($user, $Story)) {
{ $alreadyFixed ++;
$alreadyFixed++; continue;
continue; }
}
$StoryWZ = new \Entities\StoryWZ(); $StoryWZ = new \Entities\StoryWZ();
$StoryWZ->setUser($user); $StoryWZ->setUser($user);
$StoryWZ->setRecord($Story); $StoryWZ->setRecord($Story);
$em->persist($StoryWZ); $em->persist($StoryWZ);
$done++; $done ++;
} }
$em->flush(); $em->flush();
if ($alreadyFixed === 0) if ($alreadyFixed === 0) {
{ if ($done <= 1) {
if ($done <= 1) $message = sprintf(
{ _('%d Story attached to the WorkZone')
$message = sprintf( , $done
_('%d Story attached to the WorkZone') );
, $done } else {
); $message = sprintf(
} _('%d Stories attached to the WorkZone')
else , $done
{ );
$message = sprintf( }
_('%d Stories attached to the WorkZone') } else {
, $done if ($done <= 1) {
); $message = sprintf(
} _('%1$d Story attached to the WorkZone, %2$d already attached')
} , $done
else , $alreadyFixed
{ );
if ($done <= 1) } else {
{ $message = sprintf(
$message = sprintf( _('%1$d Stories attached to the WorkZone, %2$d already attached')
_('%1$d Story attached to the WorkZone, %2$d already attached') , $done
, $done , $alreadyFixed
, $alreadyFixed );
); }
} }
else
{
$message = sprintf(
_('%1$d Stories attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
}
}
$data = array( $data = array(
'success' => true 'success' => true
, 'message' => $message , 'message' => $message
); );
if ($request->getRequestFormat() == 'json') if ($request->getRequestFormat() == 'json') {
{
$datas = $app['Core']['Serializer']->serialize($data, 'json'); $datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json')); return new Response($datas, 200, array('Content-type' => 'application/json'));
} } else {
else return new RedirectResponse('/{sbas_id}/{record_id}/');
{ }
return new RedirectResponse('/{sbas_id}/{record_id}/'); });
}
});
$controllers->post( $controllers->post(
'/detachStory/{sbas_id}/{record_id}/' '/detachStory/{sbas_id}/{record_id}/'
, function(Application $app, Request $request, $sbas_id, $record_id) , function(Application $app, Request $request, $sbas_id, $record_id) {
{ $Story = new \record_adapter($sbas_id, $record_id);
$Story = new \record_adapter($sbas_id, $record_id);
$user = $app['Core']->getAuthenticatedUser(); $user = $app['Core']->getAuthenticatedUser();
$em = $app['Core']->getEntityManager(); $em = $app['Core']->getEntityManager();
$repository = $em->getRepository('\Entities\StoryWZ'); $repository = $em->getRepository('\Entities\StoryWZ');
/* @var $repository \Repositories\StoryWZRepository */ /* @var $repository \Repositories\StoryWZRepository */
$StoryWZ = $repository->findUserStory($user, $Story); $StoryWZ = $repository->findUserStory($user, $Story);
if (!$StoryWZ) if ( ! $StoryWZ) {
{ throw new \Exception_NotFound('Story not found');
throw new \Exception_NotFound('Story not found'); }
} $em->remove($StoryWZ);
$em->remove($StoryWZ);
$em->flush(); $em->flush();
$data = array( $data = array(
'success' => true 'success' => true
, 'message' => _('Story detached from the WorkZone') , 'message' => _('Story detached from the WorkZone')
); );
if ($request->getRequestFormat() == 'json') if ($request->getRequestFormat() == 'json') {
{ $datas = $app['Core']['Serializer']->serialize($data, 'json');
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json')); return new Response($datas, 200, array('Content-type' => 'application/json'));
} } else {
else return new RedirectResponse('/');
{ }
return new RedirectResponse('/'); })->assert('sbas_id', '\d+')->assert('record_id', '\d+');
}
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
return $controllers; return $controllers;
} }
} }

View File

@@ -25,163 +25,143 @@ use Silex\ControllerCollection;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com * @link www.phraseanet.com
*/ */
class RSSFeeds implements ControllerProviderInterface class RSSFeeds implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$display_feed = function($feed, $format, $page, $user = null) $display_feed = function($feed, $format, $page, $user = null) {
{ $total = $feed->get_count_total_entries();
$total = $feed->get_count_total_entries(); $perPage = 5;
$perPage = 5; $entries = $feed->get_entries((($page - 1) * $perPage), $perPage);
$entries = $feed->get_entries((($page - 1) * $perPage), $perPage);
$registry = \registry::get_instance(); $registry = \registry::get_instance();
if ($format == \Feed_Adapter::FORMAT_RSS) if ($format == \Feed_Adapter::FORMAT_RSS) {
{ $content = new \Feed_XML_RSS();
$content = new \Feed_XML_RSS(); }
}
if ($format == \Feed_Adapter::FORMAT_ATOM) if ($format == \Feed_Adapter::FORMAT_ATOM) {
{ $content = new \Feed_XML_Atom();
$content = new \Feed_XML_Atom(); }
}
if($format == \Feed_Adapter::FORMAT_COOLIRIS) if ($format == \Feed_Adapter::FORMAT_COOLIRIS) {
{ $content = new \Feed_XML_Cooliris();
$content = new \Feed_XML_Cooliris(); }
}
if ($user instanceof \User_Adapter) if ($user instanceof \User_Adapter)
$link = $feed->get_user_link($registry, $user, $format, $page); $link = $feed->get_user_link($registry, $user, $format, $page);
else else
$link = $feed->get_homepage_link($registry, $format, $page); $link = $feed->get_homepage_link($registry, $format, $page);
$content->set_updated_on(new \DateTime()); $content->set_updated_on(new \DateTime());
$content->set_title($feed->get_title()); $content->set_title($feed->get_title());
$content->set_subtitle($feed->get_subtitle()); $content->set_subtitle($feed->get_subtitle());
$content->set_generator('Phraseanet'); $content->set_generator('Phraseanet');
$content->set_link($link); $content->set_link($link);
if ($user instanceof \User_Adapter) if ($user instanceof \User_Adapter) {
{ if ($page > 1)
if ($page > 1) $content->set_previous_page($feed->get_user_link($registry, $user, $format, ($page - 1)));
$content->set_previous_page($feed->get_user_link($registry, $user, $format, ($page - 1))); if ($total > ($page * $perPage))
if ($total > ($page * $perPage)) $content->set_next_page($feed->get_user_link($registry, $user, $format, ($page + 1)));
$content->set_next_page($feed->get_user_link($registry, $user, $format, ($page + 1))); }
} else {
else if ($page > 1)
{ $content->set_previous_page($feed->get_homepage_link($registry, $format, ($page - 1)));
if ($page > 1) if ($total > ($page * $perPage))
$content->set_previous_page($feed->get_homepage_link($registry, $format, ($page - 1))); $content->set_next_page($feed->get_homepage_link($registry, $format, ($page + 1)));
if ($total > ($page * $perPage)) }
$content->set_next_page($feed->get_homepage_link($registry, $format, ($page + 1))); foreach ($entries->get_entries() as $entry)
} $content->set_item($entry);
foreach ($entries->get_entries() as $entry)
$content->set_item($entry);
$render = $content->render(); $render = $content->render();
$response = new Response($render, 200, array('Content-Type' => $content->get_mimetype())); $response = new Response($render, 200, array('Content-Type' => $content->get_mimetype()));
$response->setCharset('UTF-8'); $response->setCharset('UTF-8');
return $response; return $response;
}; };
$controllers->get('/feed/{id}/{format}/', function($id, $format) use ($app, $appbox, $display_feed) $controllers->get('/feed/{id}/{format}/', function($id, $format) use ($app, $appbox, $display_feed) {
{ $feed = new \Feed_Adapter($appbox, $id);
$feed = new \Feed_Adapter($appbox, $id);
if (!$feed->is_public()) if ( ! $feed->is_public()) {
{ return new Response('Forbidden', 403);
return new Response('Forbidden', 403); }
}
$request = $app['request']; $request = $app['request'];
$page = (int) $request->get('page'); $page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page; $page = $page < 1 ? 1 : $page;
return $display_feed($feed, $format, $page); return $display_feed($feed, $format, $page);
})->assert('id', '\d+')->assert('format', '(rss|atom)'); })->assert('id', '\d+')->assert('format', '(rss|atom)');
$controllers->get('/userfeed/{token}/{id}/{format}/', function($token, $id, $format) use ($app, $appbox, $display_feed) $controllers->get('/userfeed/{token}/{id}/{format}/', function($token, $id, $format) use ($app, $appbox, $display_feed) {
{ try {
try $token = new \Feed_Token($appbox, $token, $id);
{ $feed = $token->get_feed();
$token = new \Feed_Token($appbox, $token, $id); } catch (\Exception_FeedNotFound $e) {
$feed = $token->get_feed(); return new Response('Not Found', 404);
} }
catch (\Exception_FeedNotFound $e) $request = $app['request'];
{
return new Response('Not Found', 404);
}
$request = $app['request'];
$page = (int) $request->get('page'); $page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page; $page = $page < 1 ? 1 : $page;
return $display_feed($feed, $format, $page, $token->get_user()); return $display_feed($feed, $format, $page, $token->get_user());
})->assert('id', '\d+')->assert('format', '(rss|atom)'); })->assert('id', '\d+')->assert('format', '(rss|atom)');
$controllers->get('/userfeed/aggregated/{token}/{format}/', function($token, $format) use ($app, $appbox, $display_feed) $controllers->get('/userfeed/aggregated/{token}/{format}/', function($token, $format) use ($app, $appbox, $display_feed) {
{ try {
try $token = new \Feed_TokenAggregate($appbox, $token);
{ $feed = $token->get_feed();
$token = new \Feed_TokenAggregate($appbox, $token); } catch (\Exception_FeedNotFound $e) {
$feed = $token->get_feed(); return new Response('', 404);
} }
catch (\Exception_FeedNotFound $e)
{
return new Response('', 404);
}
$request = $app['request']; $request = $app['request'];
$page = (int) $request->get('page'); $page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page; $page = $page < 1 ? 1 : $page;
return $display_feed($feed, $format, $page, $token->get_user()); return $display_feed($feed, $format, $page, $token->get_user());
})->assert('format', '(rss|atom)'); })->assert('format', '(rss|atom)');
$controllers->get('/aggregated/{format}/', function($format) use ($app, $appbox, $display_feed) $controllers->get('/aggregated/{format}/', function($format) use ($app, $appbox, $display_feed) {
{ $feeds = \Feed_Collection::load_public_feeds($appbox);
$feeds = \Feed_Collection::load_public_feeds($appbox); $feed = $feeds->get_aggregate();
$feed = $feeds->get_aggregate();
$request = $app['request']; $request = $app['request'];
$page = (int) $request->get('page'); $page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page; $page = $page < 1 ? 1 : $page;
return $display_feed($feed, $format, $page); return $display_feed($feed, $format, $page);
})->assert('format', '(rss|atom)'); })->assert('format', '(rss|atom)');
$controllers->get('/cooliris/', function() use ($app, $appbox, $display_feed) { $controllers->get('/cooliris/', function() use ($app, $appbox, $display_feed) {
$feeds = \Feed_Collection::load_public_feeds($appbox); $feeds = \Feed_Collection::load_public_feeds($appbox);
$feed = $feeds->get_aggregate(); $feed = $feeds->get_aggregate();
$request = $app['request']; $request = $app['request'];
$page = (int) $request->get('page'); $page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page; $page = $page < 1 ? 1 : $page;
return $display_feed($feed, \Feed_Adapter::FORMAT_COOLIRIS , $page); return $display_feed($feed, \Feed_Adapter::FORMAT_COOLIRIS, $page);
}); });
return $controllers;
}
return $controllers;
}
} }

View File

@@ -28,329 +28,297 @@ use Silex\ControllerCollection;
class Installer implements ControllerProviderInterface class Installer implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function() use ($app) $controllers->get('/', function() use ($app) {
{ $request = $app['request'];
$request = $app['request'];
$php_constraint = \setup::check_php_version(); $php_constraint = \setup::check_php_version();
$writability_constraints = \setup::check_writability(new \Setup_Registry()); $writability_constraints = \setup::check_writability(new \Setup_Registry());
$extension_constraints = \setup::check_php_extension(); $extension_constraints = \setup::check_php_extension();
$opcode_constraints = \setup::check_cache_opcode(); $opcode_constraints = \setup::check_cache_opcode();
$php_conf_constraints = \setup::check_php_configuration(); $php_conf_constraints = \setup::check_php_configuration();
$locales_constraints = \setup::check_system_locales(); $locales_constraints = \setup::check_system_locales();
$constraints_coll = array( $constraints_coll = array(
'php_constraint' => $php_constraint 'php_constraint' => $php_constraint
, 'writability_constraints' => $writability_constraints , 'writability_constraints' => $writability_constraints
, 'extension_constraints' => $extension_constraints , 'extension_constraints' => $extension_constraints
, 'opcode_constraints' => $opcode_constraints , 'opcode_constraints' => $opcode_constraints
, 'php_conf_constraints' => $php_conf_constraints , 'php_conf_constraints' => $php_conf_constraints
, 'locales_constraints' => $locales_constraints , 'locales_constraints' => $locales_constraints
); );
$redirect = true; $redirect = true;
foreach ($constraints_coll as $key => $constraints) foreach ($constraints_coll as $key => $constraints) {
{ $unset = true;
$unset = true; foreach ($constraints as $constraint) {
foreach ($constraints as $constraint) if ( ! $constraint->is_ok() && $constraint->is_blocker())
{ $redirect = $unset = false;
if (!$constraint->is_ok() && $constraint->is_blocker()) }
$redirect = $unset = false; if ($unset === true) {
unset($constraints_coll[$key]);
}
} }
if ($unset === true)
{ if ($redirect) {
unset($constraints_coll[$key]); return $app->redirect('/setup/installer/step2/');
} }
}
if ($redirect)
{
return $app->redirect('/setup/installer/step2/');
}
$ld_path = array(__DIR__ . '/../../../../../templates/web'); $ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new \Twig_Loader_Filesystem($ld_path); $loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new \Twig_Environment($loader); $twig = new \Twig_Environment($loader);
$html = $twig->render( $html = $twig->render(
'/setup/index.html.twig' '/setup/index.html.twig'
, array_merge($constraints_coll, array( , array_merge($constraints_coll, array(
'locale' => \Session_Handler::get_locale() 'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['Core']::getAvailableLanguages() , 'available_locales' => $app['Core']::getAvailableLanguages()
, 'version_number' => $app['Core']['Version']->getNumber() , 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName() , 'version_name' => $app['Core']['Version']->getName()
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/' , 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
)) ))
); );
return new Response($html); return new Response($html);
}); });
$controllers->get('/step2/', function() use ($app) $controllers->get('/step2/', function() use ($app) {
{ \phrasea::use_i18n(\Session_Handler::get_locale());
\phrasea::use_i18n(\Session_Handler::get_locale());
$ld_path = array(__DIR__ . '/../../../../../templates/web'); $ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new \Twig_Loader_Filesystem($ld_path); $loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new \Twig_Environment($loader); $twig = new \Twig_Environment($loader);
$twig->addExtension(new \Twig_Extensions_Extension_I18n()); $twig->addExtension(new \Twig_Extensions_Extension_I18n());
$request = $app['request']; $request = $app['request'];
$warnings = array(); $warnings = array();
$php_constraint = \setup::check_php_version(); $php_constraint = \setup::check_php_version();
$writability_constraints = \setup::check_writability(new \Setup_Registry()); $writability_constraints = \setup::check_writability(new \Setup_Registry());
$extension_constraints = \setup::check_php_extension(); $extension_constraints = \setup::check_php_extension();
$opcode_constraints = \setup::check_cache_opcode(); $opcode_constraints = \setup::check_cache_opcode();
$php_conf_constraints = \setup::check_php_configuration(); $php_conf_constraints = \setup::check_php_configuration();
$locales_constraints = \setup::check_system_locales(); $locales_constraints = \setup::check_system_locales();
$constraints_coll = array( $constraints_coll = array(
'php_constraint' => $php_constraint 'php_constraint' => $php_constraint
, 'writability_constraints' => $writability_constraints , 'writability_constraints' => $writability_constraints
, 'extension_constraints' => $extension_constraints , 'extension_constraints' => $extension_constraints
, 'opcode_constraints' => $opcode_constraints , 'opcode_constraints' => $opcode_constraints
, 'php_conf_constraints' => $php_conf_constraints , 'php_conf_constraints' => $php_conf_constraints
, 'locales_constraints' => $locales_constraints , 'locales_constraints' => $locales_constraints
); );
foreach ($constraints_coll as $key => $constraints) foreach ($constraints_coll as $key => $constraints) {
{ $unset = true;
$unset = true; foreach ($constraints as $constraint) {
foreach ($constraints as $constraint) if ( ! $constraint->is_ok() && ! $constraint->is_blocker()) {
{ $warnings[] = $constraint->get_message();
if (!$constraint->is_ok() && !$constraint->is_blocker()) }
{ }
$warnings[] = $constraint->get_message();
}
} }
}
if ($request->getScheme() == 'http') if ($request->getScheme() == 'http') {
{ $warnings[] = _('It is not recommended to install Phraseanet without HTTPS support');
$warnings[] = _('It is not recommended to install Phraseanet without HTTPS support'); }
}
$html = $twig->render( $html = $twig->render(
'/setup/step2.html.twig' '/setup/step2.html.twig'
, array( , array(
'locale' => \Session_Handler::get_locale() 'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['Core']::getAvailableLanguages() , 'available_locales' => $app['Core']::getAvailableLanguages()
, 'available_templates' => \appbox::list_databox_templates() , 'available_templates' => \appbox::list_databox_templates()
, 'version_number' => $app['Core']['Version']->getNumber() , 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName() , 'version_name' => $app['Core']['Version']->getName()
, 'warnings' => $warnings , 'warnings' => $warnings
, 'error' => $request->get('error') , 'error' => $request->get('error')
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/' , 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
, 'discovered_binaries' => \setup::discover_binaries() , 'discovered_binaries' => \setup::discover_binaries()
, 'rootpath' => dirname(dirname(dirname(dirname(__DIR__)))) . '/' , 'rootpath' => dirname(dirname(dirname(dirname(__DIR__)))) . '/'
) )
); );
return new Response($html); return new Response($html);
}); });
$controllers->post('/install/', function() use ($app) $controllers->post('/install/', function() use ($app) {
{ set_time_limit(360);
set_time_limit(360); \phrasea::use_i18n(\Session_Handler::get_locale());
\phrasea::use_i18n(\Session_Handler::get_locale()); $request = $app['request'];
$request = $app['request'];
$servername = $request->getScheme() . '://' . $request->getHttpHost() . '/'; $servername = $request->getScheme() . '://' . $request->getHttpHost() . '/';
$setupRegistry = new \Setup_Registry();
$setupRegistry->set('GV_ServerName', $servername, \registry::TYPE_STRING);
$conn = $connbas = null;
$hostname = $request->get('ab_hostname');
$port = $request->get('ab_port');
$user_ab = $request->get('ab_user');
$password = $request->get('ab_password');
$appbox_name = $request->get('ab_name');
$databox_name = $request->get('db_name');
try
{
$conn = new \connection_pdo('appbox', $hostname, $port, $user_ab, $password, $appbox_name, array(), $setupRegistry);
}
catch (\Exception $e)
{
return $app->redirect('/setup/installer/step2/?error=' . _('Appbox is unreachable'));
}
try
{
if ($databox_name)
{
$connbas = new \connection_pdo('databox', $hostname, $port, $user_ab, $password, $databox_name, array(), $setupRegistry);
}
}
catch (\Exception $e)
{
return $app->redirect('/setup/installer/step2/?error=' . _('Databox is unreachable'));
}
\setup::rollback($conn, $connbas);
try
{
$setupRegistry = new \Setup_Registry(); $setupRegistry = new \Setup_Registry();
$setupRegistry->set('GV_ServerName', $servername, \registry::TYPE_STRING); $setupRegistry->set('GV_ServerName', $servername, \registry::TYPE_STRING);
$appbox = \appbox::create($app['Core'], $setupRegistry, $conn, $appbox_name, true); $conn = $connbas = null;
$configuration = \Alchemy\Phrasea\Core\Configuration::build(); $hostname = $request->get('ab_hostname');
$port = $request->get('ab_port');
$user_ab = $request->get('ab_user');
$password = $request->get('ab_password');
if ($configuration->isInstalled()) $appbox_name = $request->get('ab_name');
{ $databox_name = $request->get('db_name');
$serviceName = $configuration->getOrm();
$confService = $configuration->getService($serviceName);
$ormService = \Alchemy\Phrasea\Core\Service\Builder::create( try {
$app['Core'] $conn = new \connection_pdo('appbox', $hostname, $port, $user_ab, $password, $appbox_name, array(), $setupRegistry);
, $confService } catch (\Exception $e) {
); return $app->redirect('/setup/installer/step2/?error=' . _('Appbox is unreachable'));
if ($ormService->getType() === 'doctrine')
{
/* @var $em \Doctrine\ORM\EntityManager */
$em = $ormService->getDriver();
$metadatas = $em->getMetadataFactory()->getAllMetadata();
if (!empty($metadatas))
{
// Create SchemaTool
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
// Create schema
$tool->dropSchema($metadatas);
$tool->createSchema($metadatas);
}
}
} }
$registry = \registry::get_instance(); try {
\setup::create_global_values($registry); if ($databox_name) {
$connbas = new \connection_pdo('databox', $hostname, $port, $user_ab, $password, $databox_name, array(), $setupRegistry);
$appbox->set_registry($registry);
$registry->set('GV_base_datapath_noweb', \p4string::addEndSlash($request->get('datapath_noweb')), \registry::TYPE_STRING);
$registry->set('GV_base_datapath_web', \p4string::addEndSlash($request->get('datapath_web')), \registry::TYPE_STRING);
$registry->set('GV_base_dataurl', \p4string::addEndSlash($request->get('mount_point_web')), \registry::TYPE_STRING);
$registry->set('GV_ServerName', $servername, \registry::TYPE_STRING);
$registry->set('GV_cli', $request->get('binary_php'), \registry::TYPE_STRING);
$registry->set('GV_imagick', $request->get('binary_convert'), \registry::TYPE_STRING);
$registry->set('GV_pathcomposite', $request->get('binary_composite'), \registry::TYPE_STRING);
$registry->set('GV_exiftool', $request->get('binary_exiftool'), \registry::TYPE_STRING);
$registry->set('GV_swf_extract', $request->get('binary_swfextract'), \registry::TYPE_STRING);
$registry->set('GV_pdf2swf', $request->get('binary_pdf2swf'), \registry::TYPE_STRING);
$registry->set('GV_swf_render', $request->get('binary_swfrender'), \registry::TYPE_STRING);
$registry->set('GV_unoconv', $request->get('binary_unoconv'), \registry::TYPE_STRING);
$registry->set('GV_ffmpeg', $request->get('binary_ffmpeg'), \registry::TYPE_STRING);
$registry->set('GV_mp4box', $request->get('binary_MP4Box'), \registry::TYPE_STRING);
$registry->set('GV_mplayer', $request->get('binary_mplayer'), \registry::TYPE_STRING);
$registry->set('GV_pdftotext', $request->get('binary_xpdf'), \registry::TYPE_STRING);
$user = \User_Adapter::create($appbox, $request->get('email'), $request->get('password'), $request->get('email'), true);
\phrasea::start($app['Core']);
$auth = new \Session_Authentication_None($user);
$appbox->get_session()->authenticate($auth);
if (!\p4string::hasAccent($databox_name))
{
if ($databox_name)
{
$template = new \system_file(__DIR__ . '/../../../../conf.d/data_templates/' . $request->get('db_template') . '.xml');
$databox = \databox::create($appbox, $connbas, $template, $registry);
$user->ACL()
->give_access_to_sbas(array($databox->get_sbas_id()))
->update_rights_to_sbas(
$databox->get_sbas_id(), array(
'bas_manage' => 1, 'bas_modify_struct' => 1,
'bas_modif_th' => 1, 'bas_chupub' => 1
)
);
$a = \collection::create($databox, $appbox, 'test', $user);
$user->ACL()->give_access_to_base(array($a->get_base_id()));
$user->ACL()->update_rights_to_base($a->get_base_id(), array(
'canpush' => 1, 'cancmd' => 1
, 'canputinalbum' => 1, 'candwnldhd' => 1, 'candwnldpreview' => 1, 'canadmin' => 1
, 'actif' => 1, 'canreport' => 1, 'canaddrecord' => 1, 'canmodifrecord' => 1
, 'candeleterecord' => 1, 'chgstatus' => 1, 'imgtools' => 1, 'manage' => 1
, 'modify_struct' => 1, 'nowatermark' => 1
)
);
$tasks = $request->get('create_task', array());
foreach ($tasks as $task)
{
switch ($task)
{
case 'cindexer';
case 'subdef';
case 'writemeta';
$class_name = sprintf('task_period_%s', $task);
if ($task === 'cindexer')
{
$credentials = $databox->get_connection()->get_credentials();
$host = $credentials['hostname'];
$port = $credentials['port'];
$user_ab = $credentials['user'];
$password = $credentials['password'];
$settings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tasksettings>\n<binpath>"
. str_replace('/phraseanet_indexer', '', $request->get('binary_phraseanet_indexer'))
. "</binpath><host>" . $host . "</host><port>"
. $port . "</port><base>"
. $appbox_name . "</base><user>"
. $user_ab . "</user><password>"
. $password . "</password><socket>25200</socket>"
. "<use_sbas>1</use_sbas><nolog>0</nolog><clng></clng>"
. "<winsvc_run>0</winsvc_run><charset>utf8</charset></tasksettings>";
}
else
{
$settings = null;
}
\task_abstract::create($appbox, $class_name, $settings);
break;
default:
break;
}
} }
} } catch (\Exception $e) {
return $app->redirect('/setup/installer/step2/?error=' . _('Databox is unreachable'));
} }
$redirection = '/admin/?section=taskmanager&notice=install_success';
return $app->redirect($redirection);
}
catch (\Exception $e)
{
\setup::rollback($conn, $connbas); \setup::rollback($conn, $connbas);
}
return $app->redirect('/setup/installer/step2/?error=' . sprintf(_('an error occured : %s'), $e->getMessage())); try {
$setupRegistry = new \Setup_Registry();
$setupRegistry->set('GV_ServerName', $servername, \registry::TYPE_STRING);
$appbox = \appbox::create($app['Core'], $setupRegistry, $conn, $appbox_name, true);
$configuration = \Alchemy\Phrasea\Core\Configuration::build();
if ($configuration->isInstalled()) {
$serviceName = $configuration->getOrm();
$confService = $configuration->getService($serviceName);
$ormService = \Alchemy\Phrasea\Core\Service\Builder::create(
$app['Core']
, $confService
);
if ($ormService->getType() === 'doctrine') {
/* @var $em \Doctrine\ORM\EntityManager */
$em = $ormService->getDriver();
$metadatas = $em->getMetadataFactory()->getAllMetadata();
if ( ! empty($metadatas)) {
// Create SchemaTool
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
// Create schema
$tool->dropSchema($metadatas);
$tool->createSchema($metadatas);
}
}
}
$registry = \registry::get_instance();
\setup::create_global_values($registry);
$appbox->set_registry($registry);
$registry->set('GV_base_datapath_noweb', \p4string::addEndSlash($request->get('datapath_noweb')), \registry::TYPE_STRING);
$registry->set('GV_base_datapath_web', \p4string::addEndSlash($request->get('datapath_web')), \registry::TYPE_STRING);
$registry->set('GV_base_dataurl', \p4string::addEndSlash($request->get('mount_point_web')), \registry::TYPE_STRING);
$registry->set('GV_ServerName', $servername, \registry::TYPE_STRING);
$registry->set('GV_cli', $request->get('binary_php'), \registry::TYPE_STRING);
$registry->set('GV_imagick', $request->get('binary_convert'), \registry::TYPE_STRING);
$registry->set('GV_pathcomposite', $request->get('binary_composite'), \registry::TYPE_STRING);
$registry->set('GV_exiftool', $request->get('binary_exiftool'), \registry::TYPE_STRING);
$registry->set('GV_swf_extract', $request->get('binary_swfextract'), \registry::TYPE_STRING);
$registry->set('GV_pdf2swf', $request->get('binary_pdf2swf'), \registry::TYPE_STRING);
$registry->set('GV_swf_render', $request->get('binary_swfrender'), \registry::TYPE_STRING);
$registry->set('GV_unoconv', $request->get('binary_unoconv'), \registry::TYPE_STRING);
$registry->set('GV_ffmpeg', $request->get('binary_ffmpeg'), \registry::TYPE_STRING);
$registry->set('GV_mp4box', $request->get('binary_MP4Box'), \registry::TYPE_STRING);
$registry->set('GV_mplayer', $request->get('binary_mplayer'), \registry::TYPE_STRING);
$registry->set('GV_pdftotext', $request->get('binary_xpdf'), \registry::TYPE_STRING);
$user = \User_Adapter::create($appbox, $request->get('email'), $request->get('password'), $request->get('email'), true);
\phrasea::start($app['Core']);
$auth = new \Session_Authentication_None($user);
$appbox->get_session()->authenticate($auth);
if ( ! \p4string::hasAccent($databox_name)) {
if ($databox_name) {
$template = new \system_file(__DIR__ . '/../../../../conf.d/data_templates/' . $request->get('db_template') . '.xml');
$databox = \databox::create($appbox, $connbas, $template, $registry);
$user->ACL()
->give_access_to_sbas(array($databox->get_sbas_id()))
->update_rights_to_sbas(
$databox->get_sbas_id(), array(
'bas_manage' => 1, 'bas_modify_struct' => 1,
'bas_modif_th' => 1, 'bas_chupub' => 1
)
);
$a = \collection::create($databox, $appbox, 'test', $user);
$user->ACL()->give_access_to_base(array($a->get_base_id()));
$user->ACL()->update_rights_to_base($a->get_base_id(), array(
'canpush' => 1, 'cancmd' => 1
, 'canputinalbum' => 1, 'candwnldhd' => 1, 'candwnldpreview' => 1, 'canadmin' => 1
, 'actif' => 1, 'canreport' => 1, 'canaddrecord' => 1, 'canmodifrecord' => 1
, 'candeleterecord' => 1, 'chgstatus' => 1, 'imgtools' => 1, 'manage' => 1
, 'modify_struct' => 1, 'nowatermark' => 1
)
);
$tasks = $request->get('create_task', array());
foreach ($tasks as $task) {
switch ($task) {
case 'cindexer';
case 'subdef';
case 'writemeta';
$class_name = sprintf('task_period_%s', $task);
if ($task === 'cindexer') {
$credentials = $databox->get_connection()->get_credentials();
$host = $credentials['hostname'];
$port = $credentials['port'];
$user_ab = $credentials['user'];
$password = $credentials['password'];
$settings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tasksettings>\n<binpath>"
. str_replace('/phraseanet_indexer', '', $request->get('binary_phraseanet_indexer'))
. "</binpath><host>" . $host . "</host><port>"
. $port . "</port><base>"
. $appbox_name . "</base><user>"
. $user_ab . "</user><password>"
. $password . "</password><socket>25200</socket>"
. "<use_sbas>1</use_sbas><nolog>0</nolog><clng></clng>"
. "<winsvc_run>0</winsvc_run><charset>utf8</charset></tasksettings>";
} else {
$settings = null;
}
\task_abstract::create($appbox, $class_name, $settings);
break;
default:
break;
}
}
}
}
$redirection = '/admin/?section=taskmanager&notice=install_success';
return $app->redirect($redirection);
} catch (\Exception $e) {
\setup::rollback($conn, $connbas);
}
return $app->redirect('/setup/installer/step2/?error=' . sprintf(_('an error occured : %s'), $e->getMessage()));
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -28,64 +28,60 @@ use Silex\ControllerCollection;
class Upgrader implements ControllerProviderInterface class Upgrader implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/', function() use ($app) $controllers->get('/', function() use ($app) {
{ require_once __DIR__ . '/../../../../bootstrap.php';
require_once __DIR__ . '/../../../../bootstrap.php'; $upgrade_status = \Setup_Upgrade::get_status();
$upgrade_status = \Setup_Upgrade::get_status();
/* @var $twig \Twig_Environment */ /* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig(); $twig = $app['Core']->getTwig();
$html = $twig->render( $html = $twig->render(
'/setup/upgrader.html.twig' '/setup/upgrader.html.twig'
, array( , array(
'locale' => \Session_Handler::get_locale() 'locale' => \Session_Handler::get_locale()
, 'upgrade_status' => $upgrade_status , 'upgrade_status' => $upgrade_status
, 'available_locales' => $app['Core']::getAvailableLanguages() , 'available_locales' => $app['Core']::getAvailableLanguages()
, 'bad_users' => \User_Adapter::get_wrong_email_users(\appbox::get_instance($app['Core'])) , 'bad_users' => \User_Adapter::get_wrong_email_users(\appbox::get_instance($app['Core']))
, 'version_number' => $app['Core']['Version']->getNumber() , 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName() , 'version_name' => $app['Core']['Version']->getName()
) )
); );
ini_set('display_errors', 'on'); ini_set('display_errors', 'on');
return new Response($html); return new Response($html);
}); });
$controllers->get('/status/', function() use ($app) $controllers->get('/status/', function() use ($app) {
{ require_once __DIR__ . '/../../../../bootstrap.php';
require_once __DIR__ . '/../../../../bootstrap.php';
$datas = \Setup_Upgrade::get_status(); $datas = \Setup_Upgrade::get_status();
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize($datas, 'json') $Serializer->serialize($datas, 'json')
, 200 , 200
, array('Content-Type: application/json') , array('Content-Type: application/json')
); );
}); });
$controllers->post('/execute/', function() use ($app) $controllers->post('/execute/', function() use ($app) {
{ require_once __DIR__ . '/../../../../bootstrap.php';
require_once __DIR__ . '/../../../../bootstrap.php'; set_time_limit(0);
set_time_limit(0); session_write_close();
session_write_close(); ignore_user_abort(true);
ignore_user_abort(true);
$appbox = \appbox::get_instance($app['Core']); $appbox = \appbox::get_instance($app['Core']);
$upgrader = new \Setup_Upgrade($appbox); $upgrader = new \Setup_Upgrade($appbox);
$appbox->forceUpgrade($upgrader); $appbox->forceUpgrade($upgrader);
return new \Symfony\Component\HttpFoundation\RedirectResponse('/'); return new \Symfony\Component\HttpFoundation\RedirectResponse('/');
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -28,86 +28,74 @@ use Silex\ControllerCollection;
class ConnectionTest implements ControllerProviderInterface class ConnectionTest implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/mysql/', function() use ($app) $controllers->get('/mysql/', function() use ($app) {
{ require_once __DIR__ . '/../../../../classes/connection/pdo.class.php';
require_once __DIR__ . '/../../../../classes/connection/pdo.class.php';
$request = $app['request']; $request = $app['request'];
$hostname = $request->get('hostname', '127.0.0.1'); $hostname = $request->get('hostname', '127.0.0.1');
$port = (int) $request->get('port', 3306); $port = (int) $request->get('port', 3306);
$user = $request->get('user'); $user = $request->get('user');
$password = $request->get('password'); $password = $request->get('password');
$dbname = $request->get('dbname'); $dbname = $request->get('dbname');
$connection_ok = $db_ok = $is_databox = $is_appbox = $empty = false; $connection_ok = $db_ok = $is_databox = $is_appbox = $empty = false;
try try {
{ $conn = new \connection_pdo('test', $hostname, $port, $user, $password);
$conn = new \connection_pdo('test', $hostname, $port, $user, $password); $connection_ok = true;
$connection_ok = true; } catch (\Exception $e) {
}
catch (\Exception $e)
{
}
if ($dbname && $connection_ok === true)
{
try
{
$conn = new \connection_pdo('test', $hostname, $port, $user, $password, $dbname);
$db_ok = true;
$sql = "SHOW TABLE STATUS";
$stmt = $conn->prepare($sql);
$stmt->execute();
$empty = $stmt->rowCount() === 0;
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row)
{
if ($row["Name"] === 'sitepreff')
{
$is_appbox = true;
}
if ($row["Name"] === 'pref')
{
$is_databox = true;
}
}
}
catch (\Exception $e)
{
} }
}
$Serializer = $app['Core']['Serializer']; if ($dbname && $connection_ok === true) {
try {
$conn = new \connection_pdo('test', $hostname, $port, $user, $password, $dbname);
$db_ok = true;
$datas = array( $sql = "SHOW TABLE STATUS";
'connection' => $connection_ok $stmt = $conn->prepare($sql);
, 'database' => $db_ok $stmt->execute();
, 'is_empty' => $empty
, 'is_appbox' => $is_appbox
, 'is_databox' => $is_databox
);
return new Response( $empty = $stmt->rowCount() === 0;
$Serializer->serialize($datas, 'json')
, 200 $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
, array('content-type' => 'application/json') $stmt->closeCursor();
);
foreach ($rs as $row) {
if ($row["Name"] === 'sitepreff') {
$is_appbox = true;
}
if ($row["Name"] === 'pref') {
$is_databox = true;
}
}
} catch (\Exception $e) {
}
}
$Serializer = $app['Core']['Serializer'];
$datas = array(
'connection' => $connection_ok
, 'database' => $db_ok
, 'is_empty' => $empty
, 'is_appbox' => $is_appbox
, 'is_databox' => $is_databox
);
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('content-type' => 'application/json')
);
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -28,53 +28,50 @@ use Silex\ControllerCollection;
class PathFileTest implements ControllerProviderInterface class PathFileTest implements ControllerProviderInterface
{ {
public function connect(Application $app) public function connect(Application $app)
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->get('/path/', function() use ($app) $controllers->get('/path/', function() use ($app) {
{ $path = $app['request']->get('path');
$path = $app['request']->get('path');
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize( $Serializer->serialize(
array( array(
'exists' => file_exists($path) 'exists' => file_exists($path)
, 'file' => is_file($path) , 'file' => is_file($path)
, 'dir' => is_dir($path) , 'dir' => is_dir($path)
, 'readable' => is_readable($path) , 'readable' => is_readable($path)
, 'writeable' => is_writable($path) , 'writeable' => is_writable($path)
, 'executable' => is_executable($path) , 'executable' => is_executable($path)
) )
, 'json' , 'json'
) )
, 200 , 200
, array('content-type' => 'application/json') , array('content-type' => 'application/json')
); );
}); });
$controllers->get('/url/', function() use ($app) $controllers->get('/url/', function() use ($app) {
{ $url = $app['request']->get('url');
$url = $app['request']->get('url');
$Serializer = $app['Core']['Serializer']; $Serializer = $app['Core']['Serializer'];
return new Response( return new Response(
$Serializer->serialize( $Serializer->serialize(
array( array(
'code' => \http_query::getHttpCodeFromUrl($url) 'code' => \http_query::getHttpCodeFromUrl($url)
) )
, 'json' , 'json'
) )
, 200 , 200
, array('content-type' => 'application/json') , array('content-type' => 'application/json')
); );
}); });
return $controllers; return $controllers;
} }
} }

View File

@@ -37,15 +37,13 @@ require_once __DIR__ . '/Core/Configuration/ApplicationSpecification.php';
*/ */
class Core extends \Pimple class Core extends \Pimple
{ {
protected static $availableLanguages = array( protected static $availableLanguages = array(
'ar_SA' => 'العربية' 'ar_SA' => 'العربية'
, 'de_DE' => 'Deutsch' , 'de_DE' => 'Deutsch'
, 'en_GB' => 'English' , 'en_GB' => 'English'
, 'es_ES' => 'Español' , 'es_ES' => 'Español'
, 'fr_FR' => 'Français' , 'fr_FR' => 'Français'
); );
protected static $autoloader_initialized = false; protected static $autoloader_initialized = false;
/** /**
@@ -70,109 +68,94 @@ class Core extends \Pimple
/** /**
* Set version * Set version
*/ */
$this['Version'] = $this->share(function() $this['Version'] = $this->share(function() {
{ return new Core\Version();
return new Core\Version(); });
});
if ($this->configuration->isInstalled()) if ($this->configuration->isInstalled()) {
{ $this['Registry'] = $this->share(function() use ($core) {
$this['Registry'] = $this->share(function() use ($core) return \registry::get_instance($core);
{ });
return \registry::get_instance($core);
});
\phrasea::start($this); \phrasea::start($this);
} } else {
else
{
$this['Registry'] = $this->share(function() $this['Registry'] = $this->share(function() {
{ return new \Setup_Registry();
return new \Setup_Registry(); });
});
} }
$this['CacheService'] = $this->share(function() use ($core) $this['CacheService'] = $this->share(function() use ($core) {
{ if ( ! file_exists(__DIR__ . '/../../../tmp/cache_registry.yml')) {
if ( ! file_exists(__DIR__ . '/../../../tmp/cache_registry.yml')) touch(__DIR__ . '/../../../tmp/cache_registry.yml');
{ }
touch(__DIR__ . '/../../../tmp/cache_registry.yml');
}
$file = new \SplFileObject(__DIR__ . '/../../../tmp/cache_registry.yml'); $file = new \SplFileObject(__DIR__ . '/../../../tmp/cache_registry.yml');
return new \Alchemy\Phrasea\Cache\Manager($core, $file); return new \Alchemy\Phrasea\Cache\Manager($core, $file);
}); });
/** /**
* Set Entity Manager using configuration * Set Entity Manager using configuration
*/ */
$this['EM'] = $this->share(function() use ($core) $this['EM'] = $this->share(function() use ($core) {
{ $serviceName = $core->getConfiguration()->getOrm();
$serviceName = $core->getConfiguration()->getOrm(); $configuration = $core->getConfiguration()->getService($serviceName);
$configuration = $core->getConfiguration()->getService($serviceName);
$Service = Core\Service\Builder::create($core, $configuration); $Service = Core\Service\Builder::create($core, $configuration);
return $Service->getDriver(); return $Service->getDriver();
}); });
$this['Cache'] = $this->share(function() use ($core) $this['Cache'] = $this->share(function() use ($core) {
{ $serviceName = $core->getConfiguration()->getCache();
$serviceName = $core->getConfiguration()->getCache();
return $core['CacheService']->get('MainCache', $serviceName)->getDriver(); return $core['CacheService']->get('MainCache', $serviceName)->getDriver();
}); });
$this['OpcodeCache'] = $this->share(function() use ($core) $this['OpcodeCache'] = $this->share(function() use ($core) {
{ $serviceName = $core->getConfiguration()->getOpcodeCache();
$serviceName = $core->getConfiguration()->getOpcodeCache();
return $core['CacheService']->get('OpcodeCache', $serviceName)->getDriver(); return $core['CacheService']->get('OpcodeCache', $serviceName)->getDriver();
}); });
$this["Twig"] = $this->share(function() use ($core) $this["Twig"] = $this->share(function() use ($core) {
{ $serviceName = $core->getConfiguration()->getTemplating();
$serviceName = $core->getConfiguration()->getTemplating(); $configuration = $core->getConfiguration()->getService($serviceName);
$configuration = $core->getConfiguration()->getService($serviceName);
$Service = Core\Service\Builder::create($core, $configuration); $Service = Core\Service\Builder::create($core, $configuration);
return $Service->getDriver(); return $Service->getDriver();
}); });
$this['Serializer'] = $this->share(function() $this['Serializer'] = $this->share(function() {
{ $encoders = array(
$encoders = array( 'json' => new Serializer\Encoder\JsonEncoder()
'json' => new Serializer\Encoder\JsonEncoder() );
);
return new Serializer\Serializer(array(), $encoders); return new Serializer\Serializer(array(), $encoders);
}); });
$this['monolog'] = $this->share(function () use ($core) $this['monolog'] = $this->share(function () use ($core) {
{ $logger = new \Monolog\Logger('Logger');
$logger = new \Monolog\Logger('Logger');
$logger->pushHandler(new \Monolog\Handler\NullHandler()); $logger->pushHandler(new \Monolog\Handler\NullHandler());
return $logger; return $logger;
}); });
$this['media-alchemyst'] = $this->share(function () use ($core) $this['media-alchemyst'] = $this->share(function () use ($core) {
{ $conf = $core->getConfiguration()->has('media-alchemyst') ? $core->getConfiguration()->get('media-alchemyst') : new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag(array());
$conf = $core->getConfiguration()->has('media-alchemyst') ? $core->getConfiguration()->get('media-alchemyst') : new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag(array());
$drivers = new \MediaAlchemyst\DriversContainer($conf, $core['monolog']); $drivers = new \MediaAlchemyst\DriversContainer($conf, $core['monolog']);
return new \MediaAlchemyst\Alchemyst($drivers); return new \MediaAlchemyst\Alchemyst($drivers);
}); });
self::initPHPConf(); self::initPHPConf();
@@ -199,15 +182,11 @@ class Core extends \Pimple
*/ */
private function init() private function init()
{ {
if ($this->configuration->isInstalled()) if ($this->configuration->isInstalled()) {
{ if ($this->configuration->isDisplayingErrors()) {
if ($this->configuration->isDisplayingErrors())
{
ini_set('display_errors', 'on'); ini_set('display_errors', 'on');
error_reporting(E_ALL); error_reporting(E_ALL);
} } else {
else
{
ini_set('display_errors', 'off'); ini_set('display_errors', 'off');
} }
} }
@@ -292,11 +271,10 @@ class Core extends \Pimple
*/ */
public function getAuthenticatedUser() public function getAuthenticatedUser()
{ {
$appbox = \appbox::get_instance($this); $appbox = \appbox::get_instance($this);
$session = \Session_Handler::getInstance($appbox); $session = \Session_Handler::getInstance($appbox);
if ($session->get_usr_id()) if ($session->get_usr_id()) {
{
return \User_Adapter::getInstance($session->get_usr_id(), $appbox); return \User_Adapter::getInstance($session->get_usr_id(), $appbox);
} }
@@ -325,7 +303,6 @@ class Core extends \Pimple
return; return;
} }
protected $request; protected $request;
protected function getRequest() protected function getRequest()
@@ -368,12 +345,9 @@ class Core extends \Pimple
ini_set('error_log', $php_log); ini_set('error_log', $php_log);
if ($this->getRegistry()->get('GV_log_errors')) if ($this->getRegistry()->get('GV_log_errors')) {
{
ini_set('log_errors', 'on'); ini_set('log_errors', 'on');
} } else {
else
{
ini_set('log_errors', 'off'); ini_set('log_errors', 'off');
} }
@@ -397,13 +371,12 @@ class Core extends \Pimple
protected function detectLanguage() protected function detectLanguage()
{ {
$this->getRequest()->setDefaultLocale( $this->getRequest()->setDefaultLocale(
$this->getRegistry()->get('GV_default_lng', 'en_GB') $this->getRegistry()->get('GV_default_lng', 'en_GB')
); );
$cookies = $this->getRequest()->cookies; $cookies = $this->getRequest()->cookies;
if (isset(static::$availableLanguages[$cookies->get('locale')])) if (isset(static::$availableLanguages[$cookies->get('locale')])) {
{
$this->getRequest()->setLocale($cookies->get('locale')); $this->getRequest()->setLocale($cookies->get('locale'));
} }
@@ -418,42 +391,33 @@ class Core extends \Pimple
*/ */
public static function initAutoloads($cacheAutoload = false) public static function initAutoloads($cacheAutoload = false)
{ {
if (static::$autoloader_initialized) if (static::$autoloader_initialized) {
{
return; return;
} }
require_once __DIR__ . '/Loader/Autoloader.php'; require_once __DIR__ . '/Loader/Autoloader.php';
if ($cacheAutoload === true) if ($cacheAutoload === true) {
{ try {
try
{
require_once __DIR__ . '/Loader/CacheAutoloader.php'; require_once __DIR__ . '/Loader/CacheAutoloader.php';
$prefix = 'class_'; $prefix = 'class_';
$namespace = md5(__DIR__); $namespace = md5(__DIR__);
$loader = new Loader\CacheAutoloader($prefix, $namespace); $loader = new Loader\CacheAutoloader($prefix, $namespace);
} } catch (\Exception $e) {
catch (\Exception $e)
{
//no op code cache available //no op code cache available
$loader = new Loader\Autoloader(); $loader = new Loader\Autoloader();
} }
} } else {
else
{
$loader = new Loader\Autoloader(); $loader = new Loader\Autoloader();
} }
$getComposerNamespaces = function() $getComposerNamespaces = function() {
{ return require realpath(__DIR__ . '/../../../vendor/.composer/autoload_namespaces.php');
return require realpath(__DIR__ . '/../../../vendor/.composer/autoload_namespaces.php'); };
};
foreach ($getComposerNamespaces() as $prefix => $path) foreach ($getComposerNamespaces() as $prefix => $path) {
{
if (substr($prefix, -1) === '_') if (substr($prefix, -1) === '_')
$loader->registerPrefix($prefix, $path); $loader->registerPrefix($prefix, $path);
else else
@@ -461,18 +425,18 @@ class Core extends \Pimple
} }
$loader->registerNamespaces(array( $loader->registerNamespaces(array(
'Entities' => realpath(__DIR__ . '/../../Doctrine/'), 'Entities' => realpath(__DIR__ . '/../../Doctrine/'),
'Repositories' => realpath(__DIR__ . '/../../Doctrine/'), 'Repositories' => realpath(__DIR__ . '/../../Doctrine/'),
'Proxies' => realpath(__DIR__ . '/../../Doctrine/'), 'Proxies' => realpath(__DIR__ . '/../../Doctrine/'),
'Doctrine\\Logger' => realpath(__DIR__ . '/../../'), 'Doctrine\\Logger' => realpath(__DIR__ . '/../../'),
'Types' => realpath(__DIR__ . "/../../Doctrine"), 'Types' => realpath(__DIR__ . "/../../Doctrine"),
'PhraseaFixture' => realpath(__DIR__ . "/../../conf.d"), 'PhraseaFixture' => realpath(__DIR__ . "/../../conf.d"),
)); ));
$loader->register(); $loader->register();
set_include_path( set_include_path(
get_include_path() . PATH_SEPARATOR . realpath(__DIR__ . '/../../../vendor/alchemy/gdata') get_include_path() . PATH_SEPARATOR . realpath(__DIR__ . '/../../../vendor/alchemy/gdata')
); );
static::$autoloader_initialized = true; static::$autoloader_initialized = true;
@@ -488,8 +452,7 @@ class Core extends \Pimple
{ {
ini_set('output_buffering', '4096'); ini_set('output_buffering', '4096');
if ((int) ini_get('memory_limit') < 2048) if ((int) ini_get('memory_limit') < 2048) {
{
ini_set('memory_limit', '2048M'); ini_set('memory_limit', '2048M');
} }
@@ -514,5 +477,4 @@ class Core extends \Pimple
{ {
return $this->configuration->getEnvironnement(); return $this->configuration->getEnvironnement();
} }
} }

View File

@@ -23,7 +23,6 @@ use Alchemy\Phrasea\Core\Configuration\ApplicationSpecification;
*/ */
class Configuration class Configuration
{ {
/** /**
* The finale configuration values as an array * The finale configuration values as an array
* @var ParameterBag\ParameterBag * @var ParameterBag\ParameterBag
@@ -45,8 +44,7 @@ class Configuration
*/ */
public static function build($specifications = null, $environment = null) public static function build($specifications = null, $environment = null)
{ {
if ( ! $specifications) if ( ! $specifications) {
{
$specifications = new Configuration\ApplicationSpecification(); $specifications = new Configuration\ApplicationSpecification();
} }
@@ -63,13 +61,10 @@ class Configuration
{ {
$this->specifications = $specifications; $this->specifications = $specifications;
if ($specifications->isSetup()) if ($specifications->isSetup()) {
{
$configurations = $this->specifications->getConfigurations(); $configurations = $this->specifications->getConfigurations();
$environment = $environment ? : $configurations[self::KEYWORD_ENV]; $environment = $environment ? : $configurations[self::KEYWORD_ENV];
} } else {
else
{
$environment = null; $environment = null;
} }
@@ -82,26 +77,24 @@ class Configuration
{ {
$this->initialize(); $this->initialize();
$retrieve_old_credentials = function(\SplFileObject $connexionInc) $retrieve_old_credentials = function(\SplFileObject $connexionInc) {
{ require $connexionInc->getPathname();
require $connexionInc->getPathname();
return array( return array(
'hostname' => $hostname, 'hostname' => $hostname,
'port' => $port, 'port' => $port,
'user' => $user, 'user' => $user,
'password' => $password, 'password' => $password,
'dbname' => $dbname, 'dbname' => $dbname,
); );
}; };
$credentials = $retrieve_old_credentials($connexionInc); $credentials = $retrieve_old_credentials($connexionInc);
$connexions = $this->getConnexions(); $connexions = $this->getConnexions();
foreach ($credentials as $key => $value) foreach ($credentials as $key => $value) {
{ $key = $key == 'hostname' ? 'host' : $key;
$key = $key == 'hostname' ? 'host' : $key;
$connexions['main_connexion'][$key] = (string) $value; $connexions['main_connexion'][$key] = (string) $value;
} }
@@ -110,21 +103,18 @@ class Configuration
$configs = $this->getConfigurations(); $configs = $this->getConfigurations();
$retrieve_old_parameters = function(\SplFileObject $configInc) $retrieve_old_parameters = function(\SplFileObject $configInc) {
{ require $configInc->getPathname();
require $configInc->getPathname();
return array( return array(
'servername' => $servername 'servername' => $servername
); );
}; };
$old_parameters = $retrieve_old_parameters($configInc); $old_parameters = $retrieve_old_parameters($configInc);
foreach ($configs as $env => $conf) foreach ($configs as $env => $conf) {
{ if ( ! is_array($configs[$env]) || ! array_key_exists('phraseanet', $configs[$env])) {
if ( ! is_array($configs[$env]) || ! array_key_exists('phraseanet', $configs[$env]))
{
continue; continue;
} }
@@ -168,19 +158,15 @@ class Configuration
{ {
$this->environment = $environment; $this->environment = $environment;
if ($this->specifications->isSetup()) if ($this->specifications->isSetup()) {
{
$configurations = $this->specifications->getConfigurations(); $configurations = $this->specifications->getConfigurations();
if ( ! isset($configurations[$this->environment])) if ( ! isset($configurations[$this->environment])) {
{
throw new \Exception('Requested environnment is not available'); throw new \Exception('Requested environnment is not available');
} }
$this->configuration = new ParameterBag($configurations[$this->environment]); $this->configuration = new ParameterBag($configurations[$this->environment]);
} } else {
else
{
$this->configuration = new ParameterBag(array()); $this->configuration = new ParameterBag(array());
} }
@@ -196,12 +182,9 @@ class Configuration
{ {
$phraseanet = $this->getPhraseanet(); $phraseanet = $this->getPhraseanet();
try try {
{
$debug = ! ! $phraseanet->get('debug'); $debug = ! ! $phraseanet->get('debug');
} } catch (\Exception $e) {
catch (\Exception $e)
{
$debug = false; $debug = false;
} }
@@ -217,12 +200,9 @@ class Configuration
{ {
$phraseanet = $this->getPhraseanet(); $phraseanet = $this->getPhraseanet();
try try {
{
$maintained = ! ! $phraseanet->get('maintenance'); $maintained = ! ! $phraseanet->get('maintenance');
} } catch (\Exception $e) {
catch (\Exception $e)
{
$maintained = false; $maintained = false;
} }
@@ -238,12 +218,9 @@ class Configuration
{ {
$phraseanet = $this->getPhraseanet(); $phraseanet = $this->getPhraseanet();
try try {
{
$displayErrors = ! ! $phraseanet->get('display_errors'); $displayErrors = ! ! $phraseanet->get('display_errors');
} } catch (\Exception $e) {
catch (\Exception $e)
{
$displayErrors = false; $displayErrors = false;
} }
@@ -306,7 +283,6 @@ class Configuration
{ {
return $this->specifications->getConnexions(); return $this->specifications->getConnexions();
} }
const KEYWORD_ENV = 'environment'; const KEYWORD_ENV = 'environment';
public function getSelectedEnvironnment() public function getSelectedEnvironnment()
@@ -323,8 +299,7 @@ class Configuration
{ {
$connexions = $this->getConnexions(); $connexions = $this->getConnexions();
if ( ! isset($connexions[$name])) if ( ! isset($connexions[$name])) {
{
throw new \Exception(sprintf('Unknown connexion name %s', $name)); throw new \Exception(sprintf('Unknown connexion name %s', $name));
} }
@@ -367,26 +342,21 @@ class Configuration
*/ */
public function getService($name) public function getService($name)
{ {
$scopes = explode('\\', $name); $scopes = explode('\\', $name);
$services = new ParameterBag($this->getServices()); $services = new ParameterBag($this->getServices());
$service = null; $service = null;
while ($scopes) while ($scopes) {
{
$scope = array_shift($scopes); $scope = array_shift($scopes);
try try {
{ $service = new ParameterBag($services->get($scope));
$service = new ParameterBag($services->get($scope));
$services = $service; $services = $service;
} } catch (\Exception $e) {
catch (\Exception $e)
{
throw new \Exception(sprintf('Unknow service name %s', $name)); throw new \Exception(sprintf('Unknow service name %s', $name));
} }
} }
return $service; return $service;
} }
} }

View File

@@ -20,149 +20,142 @@ namespace Alchemy\Phrasea\Core\Configuration;
*/ */
class ApplicationSpecification implements Specification class ApplicationSpecification implements Specification
{ {
protected $parser;
protected $parser; public function __construct()
public function __construct()
{
$this->parser = new \Symfony\Component\Yaml\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 setServices($services)
{
return file_put_contents(
$this->getServicesPathFile(), $this->parser->dump($services, 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 getServices()
{
return $this->parser->parse(
file_get_contents($this->getServicesPathFile())
);
}
protected function getConfigurationsFile()
{
return new \SplFileObject($this->getConfigurationsPathFile());
}
protected function getConnexionsFile()
{
return new \SplFileObject($this->getConnexionsPathFile());
}
protected function getServicesFile()
{
return new \SplFileObject($this->getServicesPathFile());
}
public function delete()
{
$files = array(
$this->getConnexionsPathFile(),
$this->getConfigurationsPathFile(),
$this->getServicesPathFile()
);
foreach ($files as $file)
{ {
if (file_exists($file)) $this->parser = new \Symfony\Component\Yaml\Yaml();
unlink($file);
}
}
public function initialize()
{
$this->delete();
copy(
$this->getRealRootPath() . "/config/connexions.sample.yml"
, $this->getConnexionsPathFile()
);
copy(
$this->getRealRootPath() . "/config/services.sample.yml"
, $this->getServicesPathFile()
);
copy(
$this->getRealRootPath() . "/config/config.sample.yml"
, $this->getConfigurationsPathFile()
);
if (function_exists('chmod'))
{
chmod($this->getConnexionsPathFile(), 0700);
chmod($this->getConfigurationsPathFile(), 0700);
chmod($this->getServicesPathFile(), 0700);
}
}
public function isSetup()
{
try
{
$this->getConfigurationsFile();
$this->getConnexionsFile();
$this->getServicesFile();
return true;
}
catch (\Exception $e)
{
} }
return false; public function setConfigurations($configurations)
} {
return file_put_contents(
$this->getConfigurationsPathFile(), $this->parser->dump($configurations, 7)
);
}
protected function getConfigurationsPathFile() public function setConnexions($connexions)
{ {
return $this->getRealRootPath() . '/config/config.yml'; return file_put_contents(
} $this->getConnexionsPathFile(), $this->parser->dump($connexions, 7)
);
}
protected function getConnexionsPathFile() public function setServices($services)
{ {
return $this->getRealRootPath() . '/config/connexions.yml'; return file_put_contents(
} $this->getServicesPathFile(), $this->parser->dump($services, 7)
);
}
protected function getServicesPathFile() public function getConfigurations()
{ {
return $this->getRealRootPath() . '/config/services.yml'; return $this->parser->parse(
} file_get_contents($this->getConfigurationsPathFile())
);
}
protected function getRealRootPath() public function getConnexions()
{ {
return realpath(__DIR__ . '/../../../../../'); return $this->parser->parse(
} file_get_contents($this->getConnexionsPathFile())
);
}
public function getServices()
{
return $this->parser->parse(
file_get_contents($this->getServicesPathFile())
);
}
protected function getConfigurationsFile()
{
return new \SplFileObject($this->getConfigurationsPathFile());
}
protected function getConnexionsFile()
{
return new \SplFileObject($this->getConnexionsPathFile());
}
protected function getServicesFile()
{
return new \SplFileObject($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() . "/config/connexions.sample.yml"
, $this->getConnexionsPathFile()
);
copy(
$this->getRealRootPath() . "/config/services.sample.yml"
, $this->getServicesPathFile()
);
copy(
$this->getRealRootPath() . "/config/config.sample.yml"
, $this->getConfigurationsPathFile()
);
if (function_exists('chmod')) {
chmod($this->getConnexionsPathFile(), 0700);
chmod($this->getConfigurationsPathFile(), 0700);
chmod($this->getServicesPathFile(), 0700);
}
}
public function isSetup()
{
try {
$this->getConfigurationsFile();
$this->getConnexionsFile();
$this->getServicesFile();
return true;
} catch (\Exception $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 getRealRootPath()
{
return realpath(__DIR__ . '/../../../../../');
}
} }

View File

@@ -21,22 +21,21 @@ namespace Alchemy\Phrasea\Core\Configuration;
interface Specification interface Specification
{ {
public function setConfigurations($configurations); public function setConfigurations($configurations);
public function setConnexions($connexions); public function setConnexions($connexions);
public function setServices($services); public function setServices($services);
public function getConfigurations(); public function getConfigurations();
public function getConnexions(); public function getConnexions();
public function getServices(); public function getServices();
public function initialize(); public function initialize();
public function delete(); public function delete();
public function isSetup();
public function isSetup();
} }

View File

@@ -23,25 +23,20 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag,
class Builder class Builder
{ {
public static function create(Core $core, ParameterBag $configuration) public static function create(Core $core, ParameterBag $configuration)
{
$classname = __NAMESPACE__ . '\\' . $configuration->get("type");
if (!class_exists($classname))
{ {
throw new Exception\ServiceNotFound(sprintf('Service %s not found', $classname)); $classname = __NAMESPACE__ . '\\' . $configuration->get("type");
}
try if ( ! class_exists($classname)) {
{ throw new Exception\ServiceNotFound(sprintf('Service %s not found', $classname));
$options = $configuration->get("options"); }
}
catch (\Exception $e)
{
$options = array();
}
return new $classname($core, $options); try {
} $options = $configuration->get("options");
} catch (\Exception $e) {
$options = array();
}
return new $classname($core, $options);
}
} }

View File

@@ -25,31 +25,26 @@ use Alchemy\Phrasea\Core,
*/ */
class ApcCache extends ServiceAbstract class ApcCache extends ServiceAbstract
{ {
protected $cache;
protected $cache; public function getDriver()
public function getDriver()
{
if (!extension_loaded('apc'))
{ {
throw new \Exception('The APC cache requires the APC extension.'); 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;
} }
if (!$this->cache) public function getType()
{ {
$this->cache = new CacheDriver\ApcCache(); return 'apc';
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
} }
return $this->cache;
}
public function getType()
{
return 'apc';
}
} }

View File

@@ -26,25 +26,22 @@ use Alchemy\Phrasea\Core,
*/ */
class ArrayCache extends ServiceAbstract class ArrayCache extends ServiceAbstract
{ {
protected $cache;
protected $cache; public function getDriver()
public function getDriver()
{
if (!$this->cache)
{ {
$this->cache = new CacheDriver\ArrayCache(); if ( ! $this->cache) {
$this->cache = new CacheDriver\ArrayCache();
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); $this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
}
return $this->cache;
} }
return $this->cache; public function getType()
} {
return 'array';
public function getType() }
{
return 'array';
}
} }

View File

@@ -25,70 +25,63 @@ use Alchemy\Phrasea\Core,
*/ */
class MemcacheCache extends ServiceAbstract class MemcacheCache extends ServiceAbstract
{ {
const DEFAULT_HOST = "localhost";
const DEFAULT_PORT = "11211";
const DEFAULT_HOST = "localhost"; protected $cache;
const DEFAULT_PORT = "11211"; protected $host;
protected $port;
protected $cache; protected function init()
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.'); $options = $this->getOptions();
$this->host = isset($options["host"]) ? $options["host"] : self::DEFAULT_HOST;
$this->port = isset($options["port"]) ? $options["port"] : self::DEFAULT_PORT;
} }
if (!$this->cache) public function getDriver()
{ {
$memcache = new \Memcache(); if ( ! extension_loaded('memcache')) {
throw new \Exception('The Memcache cache requires the Memcache extension.');
}
$memcache->addServer($this->host, $this->port); if ( ! $this->cache) {
$memcache = new \Memcache();
$key = sprintf("%s:%s", $this->host, $this->port); $memcache->addServer($this->host, $this->port);
$stats = @$memcache->getExtendedStats(); $key = sprintf("%s:%s", $this->host, $this->port);
if (isset($stats[$key])) $stats = @$memcache->getExtendedStats();
{
$this->cache = new CacheDriver\MemcacheCache();
$this->cache->setMemcache($memcache);
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../'))); if (isset($stats[$key])) {
} $this->cache = new CacheDriver\MemcacheCache();
else $this->cache->setMemcache($memcache);
{
throw new \Exception(sprintf("Memcache instance with host '%s' and port '%s' is not reachable", $this->host, $this->port)); $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;
} }
return $this->cache; public function getType()
} {
return 'memcache';
}
public function getType() public function getHost()
{ {
return 'memcache'; return $this->host;
} }
public function getHost()
{
return $this->host;
}
public function getPort()
{
return $this->port;
}
public function getPort()
{
return $this->port;
}
} }

View File

@@ -25,74 +25,65 @@ use Alchemy\Phrasea\Core,
*/ */
class RedisCache extends ServiceAbstract class RedisCache extends ServiceAbstract
{ {
const DEFAULT_HOST = "localhost";
const DEFAULT_PORT = "6379";
const DEFAULT_HOST = "localhost"; protected $cache;
const DEFAULT_PORT = "6379"; protected $host;
protected $port;
protected $cache; protected function init()
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.'); $options = $this->getOptions();
$this->host = isset($options["host"]) ? $options["host"] : self::DEFAULT_HOST;
$this->port = isset($options["port"]) ? $options["port"] : self::DEFAULT_PORT;
} }
/**
if (!$this->cache) *
* @return Cache\ApcCache
*/
public function getDriver()
{ {
$redis = new \Redis(); if ( ! extension_loaded('redis')) {
throw new \Exception('The Redis cache requires the Redis extension.');
}
if (!$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY))
{
$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
}
if ($redis->connect($this->host, $this->port)) if ( ! $this->cache) {
{ $redis = new \Redis();
$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));
}
if ( ! $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY)) {
$redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
}
if ($redis->connect($this->host, $this->port)) {
$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;
} }
return $this->cache; public function getType()
} {
return 'redis';
}
public function getType() public function getHost()
{ {
return 'redis'; return $this->host;
} }
public function getHost()
{
return $this->host;
}
public function getPort()
{
return $this->port;
}
public function getPort()
{
return $this->port;
}
} }

View File

@@ -25,29 +25,25 @@ use Alchemy\Phrasea\Core,
*/ */
class XcacheCache extends ServiceAbstract class XcacheCache extends ServiceAbstract
{ {
protected $cache;
protected $cache; public function getDriver()
public function getDriver()
{
if (!extension_loaded('xcache'))
{ {
throw new \Exception('The XCache cache requires the XCache extension.'); 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;
} }
if (!$this->cache) public function getType()
{ {
$this->cache = new CacheDriver\XcacheCache(); return 'xcache';
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
} }
return $this->cache;
}
public function getType()
{
return 'xcache';
}
} }

View File

@@ -26,38 +26,34 @@ use Doctrine\Logger\MonologSQLLogger;
*/ */
class Monolog extends ParentLog class Monolog extends ParentLog
{ {
const JSON_OUTPUT = 'json';
const YAML_OUTPUT = 'yaml';
const VAR_DUMP_OUTPUT = 'vdump';
const JSON_OUTPUT = 'json'; public function getDriver()
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( $output = isset($this->options["output"]) ? $this->options["output"] : self::JSON_OUTPUT;
"The output type '%s' declared in %s service is not valid.
$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." Available types are %s."
, $output , $output
, __CLASS__ , __CLASS__
, implode(", ", $outputs) , implode(", ", $outputs)
) )
); );
}
return new MonologSQLLogger($this->monolog, $output);
} }
return new MonologSQLLogger($this->monolog, $output); public function getType()
} {
return 'doctrine_monolog';
public function getType() }
{
return 'doctrine_monolog';
}
} }

View File

@@ -15,8 +15,8 @@ use Alchemy\Phrasea\Core,
Alchemy\Phrasea\Core\Service, Alchemy\Phrasea\Core\Service,
Alchemy\Phrasea\Core\Service\ServiceAbstract, Alchemy\Phrasea\Core\Service\ServiceAbstract,
Alchemy\Phrasea\Core\Service\ServiceInterface; Alchemy\Phrasea\Core\Service\ServiceInterface;
use Doctrine\DBAL\Logging\EchoSQLLogger; use Doctrine\DBAL\Logging\EchoSQLLogger;
/** /**
* *
* @package * @package
@@ -26,14 +26,13 @@ use Doctrine\DBAL\Logging\EchoSQLLogger;
class Phpecho extends ServiceAbstract class Phpecho extends ServiceAbstract
{ {
public function getDriver() public function getDriver()
{ {
return new EchoSQLLogger(); return new EchoSQLLogger();
} }
public function getType()
{
return 'phpecho';
}
public function getType()
{
return 'phpecho';
}
} }

View File

@@ -26,24 +26,21 @@ use Monolog\Handler\FirePHPHandler;
*/ */
class FirePHP extends ServiceAbstract class FirePHP extends ServiceAbstract
{ {
protected $logger;
protected $logger; public function getDriver()
public function getDriver()
{
if (!$this->logger)
{ {
$this->logger = new Logger('FirePHP'); if ( ! $this->logger) {
$this->logger = new Logger('FirePHP');
$this->logger->pushHandler(new FirePHPHandler()); $this->logger->pushHandler(new FirePHPHandler());
}
return $this->logger;
} }
return $this->logger; public function getType()
} {
return 'FirePHP Monolog';
public function getType() }
{
return 'FirePHP Monolog';
}
} }

View File

@@ -24,113 +24,105 @@ use Alchemy\Phrasea\Core,
*/ */
class Monolog extends ServiceAbstract class Monolog extends ServiceAbstract
{ {
const DEFAULT_MAX_DAY = 10; const DEFAULT_MAX_DAY = 10;
protected $handlers = array( protected $handlers = array(
'rotate' => 'RotatingFile' 'rotate' => 'RotatingFile'
, 'stream' => 'Stream' , 'stream' => 'Stream'
); );
/** /**
* *
* @var \Monolog\Logger * @var \Monolog\Logger
*/ */
protected $monolog; protected $monolog;
protected function init() protected function init()
{
$options = $this->getOptions();
if (empty($options))
{ {
throw new \Exception(sprintf("'%s' service options can not be empty", $this->name)); $options = $this->getOptions();
}
//defaut to main handler if (empty($options)) {
$handler = isset($options["handler"]) ? $options["handler"] : false; throw new \Exception(sprintf("'%s' service options can not be empty", $this->name));
}
if (!$handler) //defaut to main handler
{ $handler = isset($options["handler"]) ? $options["handler"] : false;
throw new \Exception(sprintf(
"You must specify at least one handler for '%s' service"
, __CLASS__
)
);
}
if (!array_key_exists($handler, $this->handlers)) if ( ! $handler) {
{ throw new \Exception(sprintf(
throw new \Exception(sprintf( "You must specify at least one handler for '%s' service"
"The handler type '%s' declared in %s %s service is not valid. , __CLASS__
)
);
}
if ( ! array_key_exists($handler, $this->handlers)) {
throw new \Exception(sprintf(
"The handler type '%s' declared in %s %s service is not valid.
Available types are %s." Available types are %s."
, $handler , $handler
, __CLASS__ , __CLASS__
, implode(", ", $this->handlers) , 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;
} }
$handlerName = $this->handlers[$handler]; public function getDriver()
$handlerClassName = sprintf('\Monolog\Handler\%sHandler', $handlerName);
if (!class_exists($handlerClassName))
{ {
throw new \Exception(sprintf( return $this->monolog;
'Unable to log monolog handler %s looked for class %s'
, $handlerName
, $handlerClassName)
);
} }
if (!isset($options["filename"])) public function getType()
{ {
throw new \Exception(sprintf( return 'monolog';
"Missing filename option in '%s' service"
, __CLASS__
)
);
} }
$logPath = __DIR__ . '/../../../../../../logs'; public function getMandatoryOptions()
$file = sprintf('%s/%s', $logPath, $options["filename"]);
if ($handler == 'rotate')
{ {
$maxDay = isset($options["max_day"]) ? return array('channel', 'handler', 'filename');
(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

@@ -26,209 +26,187 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
*/ */
class Doctrine extends ServiceAbstract class Doctrine extends ServiceAbstract
{ {
protected $loggers = array(
protected $loggers = array( 'Log\\Doctrine\Monolog'
'Log\\Doctrine\Monolog' , 'Log\\Doctrine\\Phpecho'
, 'Log\\Doctrine\\Phpecho'
);
protected $entityManager;
protected $debug;
protected function init()
{
$options = $this->getOptions();
$config = new \Doctrine\ORM\Configuration();
$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->core['CacheService']->get('ORMmetadata', 'Cache\\ArrayCache');
$queryCache = $this->core['CacheService']->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->core['CacheService']->get('ORMquery', $query);
$metaCache = $this->core['CacheService']->get('ORMmetadata', $meta);
}
$resultCache = $this->core['CacheService']->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 \Doctrine\ORM\Mapping\Driver\DriverChain();
$driverYaml = new \Doctrine\ORM\Mapping\Driver\YamlDriver(
array(__DIR__ . '/../../../../../conf.d/Doctrine')
); );
protected $entityManager;
protected $debug;
$chainDriverImpl->addDriver($driverYaml, 'Entities'); protected function init()
$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( $options = $this->getOptions();
"Missing dbal configuration for '%s' service"
, __CLASS__ $config = new \Doctrine\ORM\Configuration();
)
); $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->core['CacheService']->get('ORMmetadata', 'Cache\\ArrayCache');
$queryCache = $this->core['CacheService']->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->core['CacheService']->get('ORMquery', $query);
$metaCache = $this->core['CacheService']->get('ORMmetadata', $meta);
}
$resultCache = $this->core['CacheService']->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 \Doctrine\ORM\Mapping\Driver\DriverChain();
$driverYaml = new \Doctrine\ORM\Mapping\Driver\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->core->getConfiguration()->getConnexion($connexion)->all();
} catch (\Exception $e) {
throw new \Exception("Connexion '%s' is not declared");
}
$evm = new \Doctrine\Common\EventManager();
$evm->addEventSubscriber(new \Gedmo\Timestampable\TimestampableListener());
try {
$this->entityManager = \Doctrine\ORM\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;
} }
try protected function addTypes()
{ {
$dbalConf = $this->core->getConfiguration()->getConnexion($connexion)->all();
} $platform = $this->entityManager->getConnection()->getDatabasePlatform();
catch (\Exception $e)
{ if ( ! Type::hasType('blob')) {
throw new \Exception("Connexion '%s' is not declared"); 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;
} }
$evm = new \Doctrine\Common\EventManager(); private function getLog($serviceName)
$evm->addEventSubscriber(new \Gedmo\Timestampable\TimestampableListener());
try
{ {
$this->entityManager = \Doctrine\ORM\EntityManager::create($dbalConf, $config, $evm); try {
} $configuration = $this->core->getConfiguration()->getService($serviceName);
catch (\Exception $e) } catch (\Exception $e) {
{ $message = sprintf(
throw new \Exception(sprintf( "%s from %s service"
"Failed to create doctrine service for the following reason '%s'" , $e->getMessage()
, $e->getMessage() , __CLASS__
) );
);
}
$this->addTypes(); $e = new \Exception($message);
return $this; throw $e;
} }
protected function addTypes() $type = $configuration->get("type");
{
$platform = $this->entityManager->getConnection()->getDatabasePlatform(); if ( ! in_array($type, $this->loggers)) {
throw new \Exception(sprintf(
if (!Type::hasType('blob')) "The logger type '%s' declared in %s service is not valid.
{
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->core->getConfiguration()->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." Available types are %s."
, $type , $type
, __CLASS__ , __CLASS__
, implode(", ", $this->loggers) , implode(", ", $this->loggers)
) )
); );
}
$service = Core\Service\Builder::create($this->core, $configuration);
return $service->getDriver();
} }
$service = Core\Service\Builder::create($this->core, $configuration); public function getDriver()
{
return $this->entityManager;
}
return $service->getDriver(); public function getType()
} {
return 'doctrine';
}
public function getDriver() public function isDebug()
{ {
return $this->entityManager; return $this->debug;
} }
public function getType()
{
return 'doctrine';
}
public function isDebug()
{
return $this->debug;
}
public function getMandatoryOptions()
{
return array('debug', 'dbal');
}
public function getMandatoryOptions()
{
return array('debug', 'dbal');
}
} }

View File

@@ -22,56 +22,53 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
*/ */
abstract class ServiceAbstract implements ServiceInterface abstract class ServiceAbstract implements ServiceInterface
{ {
protected $core;
protected $options;
protected $core; final public function __construct(Core $core, Array $options)
protected $options;
final public function __construct(Core $core, Array $options)
{
$this->core = $core;
$this->options = $options;
$mandatory = $this->getMandatoryOptions();
if ($mandatory !== array_intersect($mandatory, array_keys($options)))
{ {
throw new Exception\MissingParameters( $this->core = $core;
sprintf( $this->options = $options;
'Missing parameters %s'
, implode(', ', array_diff($mandatory, array_keys($options))) $mandatory = $this->getMandatoryOptions();
)
); if ($mandatory !== array_intersect($mandatory, array_keys($options))) {
throw new Exception\MissingParameters(
sprintf(
'Missing parameters %s'
, implode(', ', array_diff($mandatory, array_keys($options)))
)
);
}
$this->init();
} }
$this->init(); protected function init()
} {
return;
}
protected function init() protected function getCore()
{ {
return; return $this->core;
} }
protected function getCore() /**
{ *
return $this->core; * @return Array
} */
public function getOptions()
/** {
* return $this->options;
* @return Array }
*/
public function getOptions()
{
return $this->options;
}
/**
*
* @return Array
*/
public function getMandatoryOptions()
{
return array();
}
/**
*
* @return Array
*/
public function getMandatoryOptions()
{
return array();
}
} }

View File

@@ -20,12 +20,11 @@ namespace Alchemy\Phrasea\Core\Service;
interface ServiceInterface interface ServiceInterface
{ {
public function getType(); public function getType();
public function getDriver(); public function getDriver();
public function getOptions(); public function getOptions();
public function getMandatoryOptions();
public function getMandatoryOptions();
} }

View File

@@ -18,196 +18,186 @@ use Alchemy\Phrasea\Core,
class Twig extends ServiceAbstract class Twig extends ServiceAbstract
{ {
/**
*
* @var \Twig_Environment
*/
protected $twig;
protected $templatesPath = array();
/** protected function init()
*
* @var \Twig_Environment
*/
protected $twig;
protected $templatesPath = array();
protected function init()
{
$this->templatesPath = $this->resolvePaths();
try
{ {
if (!$this->options['debug']) $this->templatesPath = $this->resolvePaths();
{
$this->options['cache'] = realpath(__DIR__ . '/../../../../../../tmp/cache_twig/');
}
$loader = new \Twig_Loader_Filesystem($this->templatesPath); try {
$this->twig = new \Twig_Environment($loader, $this->options); if ( ! $this->options['debug']) {
$this->loadGlobals(); $this->options['cache'] = realpath(__DIR__ . '/../../../../../../tmp/cache_twig/');
$this->loadExtensions(); }
$this->loadTests();
$this->loadFilters();
}
catch (\Exception $e)
{
throw new \Exception(sprintf(
"Unable to create '%s' service for the following reason %s"
, __CLASS__
, $e->getMessage()
)
);
}
}
/** $loader = new \Twig_Loader_Filesystem($this->templatesPath);
* Load phraseanet global variable $this->twig = new \Twig_Environment($loader, $this->options);
* it' s like any other template variable, $this->loadGlobals();
* except that its available in all templates and macros $this->loadExtensions();
* @return void $this->loadTests();
*/ $this->loadFilters();
private function loadGlobals() } catch (\Exception $e) {
{ throw new \Exception(sprintf(
$appbox = \appbox::get_instance($this->core); "Unable to create '%s' service for the following reason %s"
$session = $appbox->get_session(); , __CLASS__
$browser = \Browser::getInstance(); , $e->getMessage()
$registry = $appbox->get_registry(); )
$request = new \http_request(); );
}
$user = false;
if ($session->is_authenticated())
{
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
} }
$core = \bootstrap::execute(); /**
$eventsmanager = \eventsmanager_broker::getInstance($appbox, $core); * Load phraseanet global variable
* it' s like any other template variable,
$this->twig->addGlobal('session', $session); * except that its available in all templates and macros
$this->twig->addGlobal('version_number', $core->getVersion()->getNumber()); * @return void
$this->twig->addGlobal('version_name', $core->getVersion()->getName()); */
$this->twig->addGlobal('core', $core); private function loadGlobals()
$this->twig->addGlobal('browser', $browser);
$this->twig->addGlobal('request', $request);
$this->twig->addGlobal('events', $eventsmanager);
$this->twig->addGlobal('display_chrome_frame', $registry->is_set('GV_display_gcf') ? $registry->get('GV_display_gcf') : true);
$this->twig->addGlobal('user', $user);
$this->twig->addGlobal('current_date', new \DateTime());
$this->twig->addGlobal('home_title', $registry->get('GV_homeTitle'));
$this->twig->addGlobal('meta_description', $registry->get('GV_metaDescription'));
$this->twig->addGlobal('meta_keywords', $registry->get('GV_metaKeywords'));
$this->twig->addGlobal('maintenance', $registry->get('GV_maintenance'));
$this->twig->addGlobal('registry', $registry);
}
/**
* Load twig extensions
* @return void
*/
private function loadExtensions()
{
$this->twig->addExtension(new \Twig_Extension_Core());
$this->twig->addExtension(new \Twig_Extension_Optimizer());
$this->twig->addExtension(new \Twig_Extension_Escaper());
$this->twig->addExtension(new \Twig_Extensions_Extension_Debug());
// add filter trans
$this->twig->addExtension(new \Twig_Extensions_Extension_I18n());
// add filter localizeddate
$this->twig->addExtension(new \Twig_Extensions_Extension_Intl());
// add filters truncate, wordwrap, nl2br
$this->twig->addExtension(new \Twig_Extensions_Extension_Text());
}
private function loadTests()
{
$this->twig->addTest('null', new \Twig_Test_Function('is_null'));
}
/**
* Load twig filters
* return void
*/
private function loadFilters()
{
$this->twig->addFilter('serialize', new \Twig_Filter_Function('serialize'));
$this->twig->addFilter('sbas_names', new \Twig_Filter_Function('phrasea::sbas_names'));
$this->twig->addFilter('sbas_name', new \Twig_Filter_Function('phrasea::sbas_names'));
$this->twig->addFilter('unite', new \Twig_Filter_Function('p4string::format_octets'));
$this->twig->addFilter('stristr', new \Twig_Filter_Function('stristr'));
$this->twig->addFilter('implode', new \Twig_Filter_Function('implode'));
$this->twig->addFilter('get_class', new \Twig_Filter_Function('get_class'));
$this->twig->addFilter('stripdoublequotes', new \Twig_Filter_Function('stripdoublequotes'));
$this->twig->addFilter('phraseadate', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('format_octets', new \Twig_Filter_Function('p4string::format_octets'));
$this->twig->addFilter('geoname_display', new \Twig_Filter_Function('geonames::name_from_id'));
$this->twig->addFilter('get_collection_logo', new \Twig_Filter_Function('collection::getLogo'));
$this->twig->addFilter('nl2br', new \Twig_Filter_Function('nl2br'));
$this->twig->addFilter('floor', new \Twig_Filter_Function('floor'));
$this->twig->addFilter('bas_name', new \Twig_Filter_Function('phrasea::bas_names'));
$this->twig->addFilter('bas_names', new \Twig_Filter_Function('phrasea::bas_names'));
$this->twig->addFilter('basnames', new \Twig_Filter_Function('phrasea::bas_names'));
$this->twig->addFilter('urlencode', new \Twig_Filter_Function('urlencode'));
$this->twig->addFilter('sbasFromBas', new \Twig_Filter_Function('phrasea::sbasFromBas'));
$this->twig->addFilter('str_replace', new \Twig_Filter_Function('str_replace'));
$this->twig->addFilter('strval', new \Twig_Filter_Function('strval'));
$this->twig->addFilter('key_exists', new \Twig_Filter_Function('array_key_exists'));
$this->twig->addFilter('array_keys', new \Twig_Filter_Function('array_keys'));
$this->twig->addFilter('round', new \Twig_Filter_Function('round'));
$this->twig->addFilter('dump', new \Twig_Filter_Function('var_dump'));
$this->twig->addFilter('formatdate', new \Twig_Filter_Function('phraseadate::getDate'));
$this->twig->addFilter('getPrettyDate', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('prettyDate', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('prettyString', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('formatoctet', new \Twig_Filter_Function('p4string::format_octets'));
$this->twig->addFilter('getDate', new \Twig_Filter_Function('phraseadate::getDate'));
$this->twig->addFilter('geoname_name_from_id', new \Twig_Filter_Function('geonames::name_from_id'));
}
private function getDefaultTemplatePath()
{
return array(
'mobile' => array(
__DIR__ . '/../../../../../../config/templates/mobile',
__DIR__ . '/../../../../../../templates/mobile'
),
'web' => array(
__DIR__ . '/../../../../../../config/templates/web',
__DIR__ . '/../../../../../../templates/web'
)
);
}
/**
* Set default templates Path
* According to the client device
* @return void
*/
private function resolvePaths()
{
$browser = \Browser::getInstance();
$templatePath = $this->getDefaultTemplatePath();
if ($browser->isTablet() || $browser->isMobile())
{ {
$paths = $templatePath['mobile']; $appbox = \appbox::get_instance($this->core);
} $session = $appbox->get_session();
else $browser = \Browser::getInstance();
{ $registry = $appbox->get_registry();
$paths = $templatePath['web']; $request = new \http_request();
$user = false;
if ($session->is_authenticated()) {
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
}
$core = \bootstrap::execute();
$eventsmanager = \eventsmanager_broker::getInstance($appbox, $core);
$this->twig->addGlobal('session', $session);
$this->twig->addGlobal('version_number', $core->getVersion()->getNumber());
$this->twig->addGlobal('version_name', $core->getVersion()->getName());
$this->twig->addGlobal('core', $core);
$this->twig->addGlobal('browser', $browser);
$this->twig->addGlobal('request', $request);
$this->twig->addGlobal('events', $eventsmanager);
$this->twig->addGlobal('display_chrome_frame', $registry->is_set('GV_display_gcf') ? $registry->get('GV_display_gcf') : true);
$this->twig->addGlobal('user', $user);
$this->twig->addGlobal('current_date', new \DateTime());
$this->twig->addGlobal('home_title', $registry->get('GV_homeTitle'));
$this->twig->addGlobal('meta_description', $registry->get('GV_metaDescription'));
$this->twig->addGlobal('meta_keywords', $registry->get('GV_metaKeywords'));
$this->twig->addGlobal('maintenance', $registry->get('GV_maintenance'));
$this->twig->addGlobal('registry', $registry);
} }
return $paths; /**
} * Load twig extensions
* @return void
*/
private function loadExtensions()
{
$this->twig->addExtension(new \Twig_Extension_Core());
$this->twig->addExtension(new \Twig_Extension_Optimizer());
$this->twig->addExtension(new \Twig_Extension_Escaper());
$this->twig->addExtension(new \Twig_Extensions_Extension_Debug());
// add filter trans
$this->twig->addExtension(new \Twig_Extensions_Extension_I18n());
// add filter localizeddate
$this->twig->addExtension(new \Twig_Extensions_Extension_Intl());
// add filters truncate, wordwrap, nl2br
$this->twig->addExtension(new \Twig_Extensions_Extension_Text());
}
public function getDriver() private function loadTests()
{ {
return $this->twig; $this->twig->addTest('null', new \Twig_Test_Function('is_null'));
} }
public function getType() /**
{ * Load twig filters
return 'twig'; * return void
} */
private function loadFilters()
{
$this->twig->addFilter('serialize', new \Twig_Filter_Function('serialize'));
$this->twig->addFilter('sbas_names', new \Twig_Filter_Function('phrasea::sbas_names'));
$this->twig->addFilter('sbas_name', new \Twig_Filter_Function('phrasea::sbas_names'));
$this->twig->addFilter('unite', new \Twig_Filter_Function('p4string::format_octets'));
$this->twig->addFilter('stristr', new \Twig_Filter_Function('stristr'));
$this->twig->addFilter('implode', new \Twig_Filter_Function('implode'));
$this->twig->addFilter('get_class', new \Twig_Filter_Function('get_class'));
$this->twig->addFilter('stripdoublequotes', new \Twig_Filter_Function('stripdoublequotes'));
$this->twig->addFilter('phraseadate', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('format_octets', new \Twig_Filter_Function('p4string::format_octets'));
$this->twig->addFilter('geoname_display', new \Twig_Filter_Function('geonames::name_from_id'));
$this->twig->addFilter('get_collection_logo', new \Twig_Filter_Function('collection::getLogo'));
$this->twig->addFilter('nl2br', new \Twig_Filter_Function('nl2br'));
$this->twig->addFilter('floor', new \Twig_Filter_Function('floor'));
$this->twig->addFilter('bas_name', new \Twig_Filter_Function('phrasea::bas_names'));
$this->twig->addFilter('bas_names', new \Twig_Filter_Function('phrasea::bas_names'));
$this->twig->addFilter('basnames', new \Twig_Filter_Function('phrasea::bas_names'));
$this->twig->addFilter('urlencode', new \Twig_Filter_Function('urlencode'));
$this->twig->addFilter('sbasFromBas', new \Twig_Filter_Function('phrasea::sbasFromBas'));
$this->twig->addFilter('str_replace', new \Twig_Filter_Function('str_replace'));
$this->twig->addFilter('strval', new \Twig_Filter_Function('strval'));
$this->twig->addFilter('key_exists', new \Twig_Filter_Function('array_key_exists'));
$this->twig->addFilter('array_keys', new \Twig_Filter_Function('array_keys'));
$this->twig->addFilter('round', new \Twig_Filter_Function('round'));
$this->twig->addFilter('dump', new \Twig_Filter_Function('var_dump'));
$this->twig->addFilter('formatdate', new \Twig_Filter_Function('phraseadate::getDate'));
$this->twig->addFilter('getPrettyDate', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('prettyDate', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('prettyString', new \Twig_Filter_Function('phraseadate::getPrettyString'));
$this->twig->addFilter('formatoctet', new \Twig_Filter_Function('p4string::format_octets'));
$this->twig->addFilter('getDate', new \Twig_Filter_Function('phraseadate::getDate'));
$this->twig->addFilter('geoname_name_from_id', new \Twig_Filter_Function('geonames::name_from_id'));
}
public function getMandatoryOptions() private function getDefaultTemplatePath()
{ {
return array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer'); return array(
} 'mobile' => array(
__DIR__ . '/../../../../../../config/templates/mobile',
__DIR__ . '/../../../../../../templates/mobile'
),
'web' => array(
__DIR__ . '/../../../../../../config/templates/web',
__DIR__ . '/../../../../../../templates/web'
)
);
}
/**
* Set default templates Path
* According to the client device
* @return void
*/
private function resolvePaths()
{
$browser = \Browser::getInstance();
$templatePath = $this->getDefaultTemplatePath();
if ($browser->isTablet() || $browser->isMobile()) {
$paths = $templatePath['mobile'];
} else {
$paths = $templatePath['web'];
}
return $paths;
}
public function getDriver()
{
return $this->twig;
}
public function getType()
{
return 'twig';
}
public function getMandatoryOptions()
{
return array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
}
} }

View File

@@ -19,18 +19,16 @@ namespace Alchemy\Phrasea\Core;
*/ */
class Version class Version
{ {
protected static $number = '3.7.0.0.a2';
protected static $name = 'Carnosaurus';
protected static $number = '3.7.0.0.a2'; public static function getNumber()
protected static $name = 'Carnosaurus'; {
return static::$number;
public static function getNumber() }
{
return static::$number;
}
public static function getName()
{
return static::$name;
}
public static function getName()
{
return static::$name;
}
} }

View File

@@ -22,48 +22,46 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class Helper class Helper
{ {
/**
*
* @var \Alchemy\Phrasea\Core\Kernel
*/
protected $core;
/** /**
* *
* @var \Alchemy\Phrasea\Core\Kernel * @var \Symfony\Component\HttpFoundation\Request
*/ */
protected $core; protected $request;
/** /**
* *
* @var \Symfony\Component\HttpFoundation\Request * @param Kernel $kernel
*/ * @return Helper
protected $request; */
public function __construct(Core $core, Request $Request)
{
$this->core = $core;
$this->request = $Request;
/** return $this;
* }
* @param Kernel $kernel
* @return Helper
*/
public function __construct(Core $core, Request $Request)
{
$this->core = $core;
$this->request = $Request;
return $this; /**
} *
* @return \Alchemy\Phrasea\Core
/** */
* public function getCore()
* @return \Alchemy\Phrasea\Core {
*/ return $this->core;
public function getCore() }
{
return $this->core;
}
/**
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()
{
return $this->request;
}
/**
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()
{
return $this->request;
}
} }

View File

@@ -23,97 +23,88 @@ use Symfony\Component\HttpFoundation\Request;
class Prod extends Helper class Prod extends Helper
{ {
public function get_search_datas() public function get_search_datas()
{
$search_datas = array(
'bases' => array(),
'dates' => array(),
'fields' => array()
);
$bases = $fields = $dates = array();
$user = $this->getCore()->getAuthenticatedUser();
if(!$user instanceof \User_Adapter)
{ {
return $search_datas; $search_datas = array(
} 'bases' => array(),
'dates' => array(),
$searchSet = $user->getPrefs('search'); 'fields' => array()
foreach ($user->ACL()->get_granted_sbas() as $databox)
{
$sbas_id = $databox->get_sbas_id();
$bases[$sbas_id] = array(
'thesaurus' => (trim($databox->get_thesaurus()) != ""),
'cterms' => false,
'collections' => array(),
'sbas_id' => $sbas_id
);
foreach ($user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll)
{
$selected = ($searchSet &&
isset($searchSet->bases) &&
isset($searchSet->bases->$sbas_id)) ? (in_array($coll->get_base_id(), $searchSet->bases->$sbas_id)) : true;
$bases[$sbas_id]['collections'][] =
array(
'selected' => $selected,
'base_id' => $coll->get_base_id()
); );
}
$meta_struct = $databox->get_meta_structure(); $bases = $fields = $dates = array();
foreach ($meta_struct as $meta) $user = $this->getCore()->getAuthenticatedUser();
{
if (!$meta->is_indexable()) if ( ! $user instanceof \User_Adapter) {
continue; return $search_datas;
$id = $meta->get_id();
$name = $meta->get_name();
if ($meta->get_type() == 'date')
{
if (isset($dates[$id]))
$dates[$id]['sbas'][] = $sbas_id;
else
$dates[$id] = array('sbas' => array($sbas_id), 'fieldname' => $name);
} }
if (isset($fields[$name])) $searchSet = $user->getPrefs('search');
{
$fields[$name]['sbas'][] = $sbas_id;
}
else
{
$fields[$name] = array(
'sbas' => array($sbas_id)
, 'fieldname' => $name
, 'type' => $meta->get_type()
, 'id' => $id
);
}
}
if (!$bases[$sbas_id]['thesaurus']) foreach ($user->ACL()->get_granted_sbas() as $databox) {
continue; $sbas_id = $databox->get_sbas_id();
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modif_th'))
continue;
if (simplexml_load_string($databox->get_cterms())) $bases[$sbas_id] = array(
{ 'thesaurus' => (trim($databox->get_thesaurus()) != ""),
$bases[$sbas_id]['cterms'] = true; 'cterms' => false,
} 'collections' => array(),
'sbas_id' => $sbas_id
);
foreach ($user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll) {
$selected = ($searchSet &&
isset($searchSet->bases) &&
isset($searchSet->bases->$sbas_id)) ? (in_array($coll->get_base_id(), $searchSet->bases->$sbas_id)) : true;
$bases[$sbas_id]['collections'][] =
array(
'selected' => $selected,
'base_id' => $coll->get_base_id()
);
}
$meta_struct = $databox->get_meta_structure();
foreach ($meta_struct as $meta) {
if ( ! $meta->is_indexable())
continue;
$id = $meta->get_id();
$name = $meta->get_name();
if ($meta->get_type() == 'date') {
if (isset($dates[$id]))
$dates[$id]['sbas'][] = $sbas_id;
else
$dates[$id] = array('sbas' => array($sbas_id), 'fieldname' => $name);
}
if (isset($fields[$name])) {
$fields[$name]['sbas'][] = $sbas_id;
} else {
$fields[$name] = array(
'sbas' => array($sbas_id)
, 'fieldname' => $name
, 'type' => $meta->get_type()
, 'id' => $id
);
}
}
if ( ! $bases[$sbas_id]['thesaurus'])
continue;
if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modif_th'))
continue;
if (simplexml_load_string($databox->get_cterms())) {
$bases[$sbas_id]['cterms'] = true;
}
}
$search_datas['fields'] = $fields;
$search_datas['dates'] = $dates;
$search_datas['bases'] = $bases;
return $search_datas;
} }
$search_datas['fields'] = $fields; public function getRandom()
$search_datas['dates'] = $dates; {
$search_datas['bases'] = $bases; return md5(time() . mt_rand(100000, 999999));
}
return $search_datas;
}
public function getRandom()
{
return md5(time() . mt_rand(100000, 999999));
}
} }

View File

@@ -23,7 +23,6 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class Bridge extends RecordHelper class Bridge extends RecordHelper
{ {
protected $flatten_groupings = true;
protected $flatten_groupings = true;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -23,44 +23,40 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class Feed extends RecordHelper class Feed extends RecordHelper
{ {
/**
*
* @var Array
*/
protected $required_sbas_rights = array('bas_chupub');
/** /**
* *
* @var Array * @var boolean
*/ */
protected $required_sbas_rights = array('bas_chupub'); protected $works_on_unique_sbas = true;
/** /**
* *
* @var boolean * @var boolean
*/ */
protected $works_on_unique_sbas = true; protected $flatten_groupings = true;
/** /**
* *
* @var boolean * @param \Alchemy\Phrasea\Core $core
*/ * @return Feed
protected $flatten_groupings = true; */
public function __construct(Core $core, Request $Request)
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Feed
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
if ($this->is_single_grouping())
{ {
$record = array_pop($this->selection->get_elements()); parent::__construct($core, $Request);
foreach ($record->get_children() as $child)
{ if ($this->is_single_grouping()) {
$this->selection->add_element($child); $record = array_pop($this->selection->get_elements());
} foreach ($record->get_children() as $child) {
$this->selection->add_element($child);
}
}
return $this;
} }
return $this;
}
} }

View File

@@ -22,303 +22,290 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class Helper extends \Alchemy\Phrasea\Helper\Helper class Helper extends \Alchemy\Phrasea\Helper\Helper
{ {
/**
*
* @var set_selection
*/
protected $selection;
/** /**
* *
* @var set_selection * @var boolean
*/ */
protected $selection; protected $is_possible;
/** /**
* *
* @var boolean * @var Array
*/ */
protected $is_possible; protected $elements_received;
/** /**
* *
* @var Array * @var Array
*/ */
protected $elements_received; protected $single_grouping;
/** /**
* *
* @var Array * @var int
*/ */
protected $single_grouping; protected $sbas_id;
/** /**
* *
* @var int * @var boolean
*/ */
protected $sbas_id; protected $has_many_sbas;
/** /**
* *
* @var boolean * @var Array
*/ */
protected $has_many_sbas; protected $required_rights = array();
/** /**
* *
* @var Array * @var Array
*/ */
protected $required_rights = array(); protected $required_sbas_rights = array();
/** /**
* *
* @var Array * @var boolean
*/ */
protected $required_sbas_rights = array(); protected $works_on_unique_sbas = false;
/** /**
* *
* @var boolean * @var <type>
*/ */
protected $works_on_unique_sbas = false; protected $request;
protected $flatten_groupings = false;
/** /**
* *
* @var <type> * @var boolean
*/ */
protected $request; protected $is_basket = false;
protected $flatten_groupings = false;
/** /**
* *
* @var boolean * @var \Entities\Basket
*/ */
protected $is_basket = false; protected $original_basket;
/** /**
* *
* @var \Entities\Basket * @param \Alchemy\Phrasea\Core $core
*/ * @return Helper
protected $original_basket; */
public function __construct(Core $core, Request $Request)
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Helper
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$this->selection = new \set_selection();
$appbox = \appbox::get_instance($core);
$usr_id = $appbox->get_session()->get_usr_id();
if (trim($Request->get('ssel')) !== '')
{ {
$em = $this->getCore()->getEntityManager(); parent::__construct($core, $Request);
$repository = $em->getRepository('\Entities\Basket');
/* @var $$repository \Repositories\BasketRepository */ $this->selection = new \set_selection();
$Basket = $repository->findUserBasket($Request->get('ssel'), $this->getCore()->getAuthenticatedUser(), false);
$this->selection->load_basket($Basket); $appbox = \appbox::get_instance($core);
$usr_id = $appbox->get_session()->get_usr_id();
$this->is_basket = true; if (trim($Request->get('ssel')) !== '') {
$this->original_basket = $Basket; $em = $this->getCore()->getEntityManager();
} $repository = $em->getRepository('\Entities\Basket');
elseif (trim($Request->get('story')) !== '')
{
$em = $this->getCore()->getEntityManager();
$repository = $em->getRepository('\Entities\StoryWZ');
$storyWZ = $repository->findByUserAndId( /* @var $$repository \Repositories\BasketRepository */
$this->getCore()->getAuthenticatedUser() $Basket = $repository->findUserBasket($Request->get('ssel'), $this->getCore()->getAuthenticatedUser(), false);
, $Request->get('story')
);
$this->selection->load_list(array($storyWZ->getRecord()->get_serialize_key()), $this->flatten_groupings); $this->selection->load_basket($Basket);
}
else
{
$this->selection->load_list(explode(";", $Request->get('lst')), $this->flatten_groupings);
}
$this->elements_received = $this->selection->get_count();
$this->single_grouping = ($this->get_count_actionable() == 1 && $this->is_basket = true;
$this->get_count_actionable_groupings() == 1); $this->original_basket = $Basket;
} elseif (trim($Request->get('story')) !== '') {
$em = $this->getCore()->getEntityManager();
$repository = $em->getRepository('\Entities\StoryWZ');
$this->examinate_selection(); $storyWZ = $repository->findByUserAndId(
$this->getCore()->getAuthenticatedUser()
, $Request->get('story')
);
return $this; $this->selection->load_list(array($storyWZ->getRecord()->get_serialize_key()), $this->flatten_groupings);
} } else {
$this->selection->load_list(explode(";", $Request->get('lst')), $this->flatten_groupings);
}
$this->elements_received = $this->selection->get_count();
/** $this->single_grouping = ($this->get_count_actionable() == 1 &&
* Tells if the original selection was a basket $this->get_count_actionable_groupings() == 1);
*
* @return boolean
*/
public function is_basket()
{
return $this->is_basket;
}
/** $this->examinate_selection();
* If the original selection was a basket, returns the basket object
*
* @return \Entities\Basket
*/
public function get_original_basket()
{
return $this->original_basket;
}
protected function examinate_selection() return $this;
{
$this->selection->grep_authorized($this->required_rights, $this->required_sbas_rights);
if ($this->works_on_unique_sbas === true)
{
$this->sbas_ids = $this->selection->get_distinct_sbas_ids();
$this->is_possible = count($this->sbas_ids) == 1;
$this->has_many_sbas = count($this->sbas_ids) > 1;
$this->sbas_id = $this->is_possible ? array_pop($this->sbas_ids) : false;
} }
return $this; /**
} * Tells if the original selection was a basket
*
/** * @return boolean
* Is action applies on single grouping */
* public function is_basket()
* @return <type>
*/
public function is_single_grouping()
{
return $this->single_grouping;
}
/**
* When action on a single grouping, returns the image of himself
*
* @return record_adapter
*/
public function get_grouping_head()
{
if (!$this->is_single_grouping())
throw new Exception('Cannot use ' . __METHOD__ . ' here');
foreach ($this->get_elements() as $record)
{ {
return $record; return $this->is_basket;
}
}
/**
* Get elements for the action
*
* @return Array
*/
public function get_elements()
{
return $this->selection->get_elements();
}
/**
* Returns true if elements comes from many sbas
*
* @return boolean
*/
public function has_many_sbas()
{
return $this->has_many_sbas;
}
/**
* Returns true if the action is possible with the current elements
* for the user
*
* @return boolean
*/
public function is_possible()
{
return $this->is_possible;
}
/**
* Returns the number of elements on which the action can not be done
*
* @return int
*/
public function get_count_not_actionable()
{
return $this->get_count_element_received() - $this->get_count_actionable();
}
/**
* Returns the number of elements on which the action can be done
*
* @return int
*/
public function get_count_actionable()
{
return $this->selection->get_count();
}
/**
* Returns the number of groupings on which the action can be done
*
* @return int
*/
public function get_count_actionable_groupings()
{
return $this->selection->get_count_groupings();
}
/**
* Return the number of elements receveid when starting action
*
* @return int
*/
public function get_count_element_received()
{
return $this->elements_received;
}
/**
* Return sbas_ids of the current selection
*
* @return int
*/
public function get_sbas_id()
{
return $this->sbas_id;
}
/**
* Get the selection as a serialized string base_id"_"record_id
*
* @return string
*/
public function get_serialize_list()
{
if ($this->is_single_grouping())
{
return $this->get_grouping_head()->get_serialize_key();
}
else
{
return $this->selection->serialize_list();
}
}
public function grep_records(\Closure $closure)
{
foreach ($this->selection->get_elements() as $record)
{
if (!$closure($record))
$this->selection->remove_element($record);
} }
return $this; /**
} * If the original selection was a basket, returns the basket object
*
* @return \Entities\Basket
*/
public function get_original_basket()
{
return $this->original_basket;
}
protected function examinate_selection()
{
$this->selection->grep_authorized($this->required_rights, $this->required_sbas_rights);
if ($this->works_on_unique_sbas === true) {
$this->sbas_ids = $this->selection->get_distinct_sbas_ids();
$this->is_possible = count($this->sbas_ids) == 1;
$this->has_many_sbas = count($this->sbas_ids) > 1;
$this->sbas_id = $this->is_possible ? array_pop($this->sbas_ids) : false;
}
return $this;
}
/**
* Is action applies on single grouping
*
* @return <type>
*/
public function is_single_grouping()
{
return $this->single_grouping;
}
/**
* When action on a single grouping, returns the image of himself
*
* @return record_adapter
*/
public function get_grouping_head()
{
if ( ! $this->is_single_grouping())
throw new Exception('Cannot use ' . __METHOD__ . ' here');
foreach ($this->get_elements() as $record) {
return $record;
}
}
/**
* Get elements for the action
*
* @return Array
*/
public function get_elements()
{
return $this->selection->get_elements();
}
/**
* Returns true if elements comes from many sbas
*
* @return boolean
*/
public function has_many_sbas()
{
return $this->has_many_sbas;
}
/**
* Returns true if the action is possible with the current elements
* for the user
*
* @return boolean
*/
public function is_possible()
{
return $this->is_possible;
}
/**
* Returns the number of elements on which the action can not be done
*
* @return int
*/
public function get_count_not_actionable()
{
return $this->get_count_element_received() - $this->get_count_actionable();
}
/**
* Returns the number of elements on which the action can be done
*
* @return int
*/
public function get_count_actionable()
{
return $this->selection->get_count();
}
/**
* Returns the number of groupings on which the action can be done
*
* @return int
*/
public function get_count_actionable_groupings()
{
return $this->selection->get_count_groupings();
}
/**
* Return the number of elements receveid when starting action
*
* @return int
*/
public function get_count_element_received()
{
return $this->elements_received;
}
/**
* Return sbas_ids of the current selection
*
* @return int
*/
public function get_sbas_id()
{
return $this->sbas_id;
}
/**
* Get the selection as a serialized string base_id"_"record_id
*
* @return string
*/
public function get_serialize_list()
{
if ($this->is_single_grouping()) {
return $this->get_grouping_head()->get_serialize_key();
} else {
return $this->selection->serialize_list();
}
}
public function grep_records(\Closure $closure)
{
foreach ($this->selection->get_elements() as $record) {
if ( ! $closure($record))
$this->selection->remove_element($record);
}
return $this;
}
} }

View File

@@ -23,124 +23,116 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class MoveCollection extends RecordHelper class MoveCollection extends RecordHelper
{ {
/**
*
* @var Array
*/
protected $required_rights = array('candeleterecord');
/** /**
* *
* @var Array * @var Array
*/ */
protected $required_rights = array('candeleterecord'); protected $available_destinations;
/** /**
* *
* @var Array */
*/ protected $works_on_unique_sbas = true;
protected $available_destinations;
/** /**
* *
*/ * @param \Alchemy\Phrasea\Core $core
protected $works_on_unique_sbas = true; * @return MoveCollection
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$this->evaluate_destinations();
/** return $this;
* }
* @param \Alchemy\Phrasea\Core $core
* @return MoveCollection
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$this->evaluate_destinations();
return $this; /**
} * Check which collections can receive the documents
*
* @return action_move
*/
protected function evaluate_destinations()
{
$this->available_destinations = array();
/** if ( ! $this->is_possible)
* Check which collections can receive the documents return $this;
*
* @return action_move
*/
protected function evaluate_destinations()
{
$this->available_destinations = array();
if (!$this->is_possible) $this->available_destinations = array_keys(
return $this;
$this->available_destinations = array_keys(
$this->getCore()->getAuthenticatedUser()->ACL()->get_granted_base( $this->getCore()->getAuthenticatedUser()->ACL()->get_granted_base(
array('canaddrecord'), array($this->sbas_id) array('canaddrecord'), array($this->sbas_id)
) )
); );
return $this; return $this;
} }
/** /**
* Returns an array of base_id * Returns an array of base_id
* *
* @return Array * @return Array
*/ */
public function available_destination() public function available_destination()
{ {
return $this->available_destinations; return $this->available_destinations;
} }
public function propose() public function propose()
{ {
return $this; return $this;
} }
/** /**
* *
* @param http_request $request * @param http_request $request
* @return action_move * @return action_move
*/ */
public function execute(Request $request) public function execute(Request $request)
{ {
$appbox = \appbox::get_instance($this->core); $appbox = \appbox::get_instance($this->core);
$user = $this->getCore()->getAuthenticatedUser(); $user = $this->getCore()->getAuthenticatedUser();
$baseId = $request->get('base_id'); $baseId = $request->get('base_id');
$base_dest = $base_dest =
$user->ACL()->has_right_on_base($baseId, 'canaddrecord') ? $user->ACL()->has_right_on_base($baseId, 'canaddrecord') ?
$request->get('base_id') : false; $request->get('base_id') : false;
if(!$user->ACL()->has_right_on_base($baseId, 'canaddrecord')) if ( ! $user->ACL()->has_right_on_base($baseId, 'canaddrecord')) {
{ throw new \Exception_Unauthorized(sprintf("%s do not have the permission to move records to %s", $user->get_login()));
throw new \Exception_Unauthorized(sprintf("%s do not have the permission to move records to %s", $user->get_login()));
}
if (!$this->is_possible())
throw new Exception('This action is not possible');
if ($request->get("chg_coll_son") == "1")
{
foreach ($this->selection as $record)
{
if (!$record->is_grouping())
continue;
foreach ($record->get_children() as $child)
{
if (!$user->ACL()->has_right_on_base(
$child->get_base_id(), 'candeleterecord'))
continue;
$this->selection->add_element($child);
} }
}
if ( ! $this->is_possible())
throw new Exception('This action is not possible');
if ($request->get("chg_coll_son") == "1") {
foreach ($this->selection as $record) {
if ( ! $record->is_grouping())
continue;
foreach ($record->get_children() as $child) {
if ( ! $user->ACL()->has_right_on_base(
$child->get_base_id(), 'candeleterecord'))
continue;
$this->selection->add_element($child);
}
}
}
$collection = \collection::get_from_base_id($base_dest);
foreach ($this->selection as $record) {
$record->move_to_collection($collection, $appbox);
}
return $this;
} }
$collection = \collection::get_from_base_id($base_dest);
foreach ($this->selection as $record)
{
$record->move_to_collection($collection, $appbox);
}
return $this;
}
} }

View File

@@ -27,71 +27,57 @@ use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper,
*/ */
class Printer extends RecordHelper class Printer extends RecordHelper
{ {
protected $flatten_groupings = true;
protected $flatten_groupings = true; /**
*
* @param \Alchemy\Phrasea\Core $core
* @return Printer
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
/** $grep = function(\record_adapter $record) {
*
* @param \Alchemy\Phrasea\Core $core
* @return Printer
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$grep = function(\record_adapter $record) try {
{ return $record->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE ||
try
{
return $record->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE ||
$record->get_preview()->get_type() == \media_subdef::TYPE_IMAGE; $record->get_preview()->get_type() == \media_subdef::TYPE_IMAGE;
} } catch (\Exception $e) {
catch (\Exception $e) return false;
{ }
return false;
}
}; };
$this->grep_records($grep); $this->grep_records($grep);
}
public function get_count_preview()
{
$n = 0;
foreach ($this->get_elements() as $element)
{
try
{
$element->get_preview()->get_type() == \media_subdef::TYPE_IMAGE;
$n++;
}
catch (\Exception $e)
{
}
} }
return $n; public function get_count_preview()
}
public function get_count_thumbnail()
{
$n = 0;
foreach ($this->get_elements() as $element)
{ {
try $n = 0;
{ foreach ($this->get_elements() as $element) {
$element->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE; try {
$n++; $element->get_preview()->get_type() == \media_subdef::TYPE_IMAGE;
} $n ++;
catch (\Exception $e) } catch (\Exception $e) {
{
} }
}
return $n;
} }
return $n; public function get_count_thumbnail()
} {
$n = 0;
foreach ($this->get_elements() as $element) {
try {
$element->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE;
$n ++;
} catch (\Exception $e) {
}
}
return $n;
}
} }

View File

@@ -27,9 +27,7 @@ use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper,
*/ */
class Push extends RecordHelper class Push extends RecordHelper
{ {
protected $flatten_groupings = true;
protected $flatten_groupings = true; protected $required_rights = array('canpush');
protected $required_rights = array('canpush');
} }

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Core; use Alchemy\Phrasea\Core;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper; use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper;

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Helper\Record; namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Core; use Alchemy\Phrasea\Core;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper; use Alchemy\Phrasea\Helper\Record\Helper as RecordHelper;

File diff suppressed because it is too large Load Diff

View File

@@ -22,92 +22,93 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class Manage extends \Alchemy\Phrasea\Helper\Helper class Manage extends \Alchemy\Phrasea\Helper\Helper
{ {
/**
*
* @var array
*/
protected $results;
/** /**
* *
* @var array * @var array
*/ */
protected $results; protected $query_parms;
/**
*
* @var array
*/
protected $query_parms;
/**
*
* @var int
*/
protected $usr_id;
public function export() /**
{ *
$request = $this->request; * @var int
$appbox = \appbox::get_instance($this->core); */
$session = $appbox->get_session(); protected $usr_id;
$offset_start = (int) $request->get('offset_start'); public function export()
$offset_start = $offset_start < 0 ? 0 : $offset_start; {
$request = $this->request;
$appbox = \appbox::get_instance($this->core);
$session = $appbox->get_session();
$this->query_parms = array( $offset_start = (int) $request->get('offset_start');
'inactives' => $request->get('inactives') $offset_start = $offset_start < 0 ? 0 : $offset_start;
, 'like_field' => $request->get('like_field')
, 'like_value' => $request->get('like_value')
, 'sbas_id' => $request->get('sbas_id')
, 'base_id' => $request->get('base_id')
, 'srt' => $request->get("srt", \User_Query::SORT_CREATIONDATE)
, 'ord' => $request->get("ord", \User_Query::ORD_DESC)
, 'offset_start' => 0
);
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox); $this->query_parms = array(
$query = new \User_Query($appbox); 'inactives' => $request->get('inactives')
, 'like_field' => $request->get('like_field')
, 'like_value' => $request->get('like_value')
, 'sbas_id' => $request->get('sbas_id')
, 'base_id' => $request->get('base_id')
, 'srt' => $request->get("srt", \User_Query::SORT_CREATIONDATE)
, 'ord' => $request->get("ord", \User_Query::ORD_DESC)
, 'offset_start' => 0
);
if (is_array($this->query_parms['base_id'])) $user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
$query->on_base_ids($this->query_parms['base_id']); $query = new \User_Query($appbox);
elseif (is_array($this->query_parms['sbas_id']))
$query->on_sbas_ids($this->query_parms['sbas_id']);
$this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"]) if (is_array($this->query_parms['base_id']))
$query->on_base_ids($this->query_parms['base_id']);
elseif (is_array($this->query_parms['sbas_id']))
$query->on_sbas_ids($this->query_parms['sbas_id']);
$this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"])
->like($this->query_parms['like_field'], $this->query_parms['like_value']) ->like($this->query_parms['like_field'], $this->query_parms['like_value'])
->get_inactives($this->query_parms['inactives']) ->get_inactives($this->query_parms['inactives'])
->include_templates(false) ->include_templates(false)
->on_bases_where_i_am($user->ACL(), array('canadmin')) ->on_bases_where_i_am($user->ACL(), array('canadmin'))
->execute(); ->execute();
return $this->results->get_results(); return $this->results->get_results();
} }
public function search() public function search()
{ {
$request = $this->request; $request = $this->request;
$appbox = \appbox::get_instance($this->core); $appbox = \appbox::get_instance($this->core);
$offset_start = (int) $this->request->get('offset_start'); $offset_start = (int) $this->request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start; $offset_start = $offset_start < 0 ? 0 : $offset_start;
$results_quantity = (int) $this->request->get('per_page'); $results_quantity = (int) $this->request->get('per_page');
$results_quantity = ($results_quantity < 10 || $results_quantity > 50) ? 20 : $results_quantity; $results_quantity = ($results_quantity < 10 || $results_quantity > 50) ? 20 : $results_quantity;
$this->query_parms = array( $this->query_parms = array(
'inactives' => $this->request->get('inactives') 'inactives' => $this->request->get('inactives')
, 'like_field' => $this->request->get('like_field') , 'like_field' => $this->request->get('like_field')
, 'like_value' => $this->request->get('like_value') , 'like_value' => $this->request->get('like_value')
, 'sbas_id' => $this->request->get('sbas_id') , 'sbas_id' => $this->request->get('sbas_id')
, 'base_id' => $this->request->get('base_id') , 'base_id' => $this->request->get('base_id')
, 'srt' => $this->request->get("srt", \User_Query::SORT_CREATIONDATE) , 'srt' => $this->request->get("srt", \User_Query::SORT_CREATIONDATE)
, 'ord' => $this->request->get("ord", \User_Query::ORD_DESC) , 'ord' => $this->request->get("ord", \User_Query::ORD_DESC)
, 'per_page' => $results_quantity , 'per_page' => $results_quantity
, 'offset_start' => $offset_start , 'offset_start' => $offset_start
); );
$user = $this->getCore()->getAuthenticatedUser(); $user = $this->getCore()->getAuthenticatedUser();
$query = new \User_Query($appbox); $query = new \User_Query($appbox);
if (is_array($this->query_parms['base_id'])) if (is_array($this->query_parms['base_id']))
$query->on_base_ids($this->query_parms['base_id']); $query->on_base_ids($this->query_parms['base_id']);
elseif (is_array($this->query_parms['sbas_id'])) elseif (is_array($this->query_parms['sbas_id']))
$query->on_sbas_ids($this->query_parms['sbas_id']); $query->on_sbas_ids($this->query_parms['sbas_id']);
$this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"]) $this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"])
->like($this->query_parms['like_field'], $this->query_parms['like_value']) ->like($this->query_parms['like_field'], $this->query_parms['like_value'])
->get_inactives($this->query_parms['inactives']) ->get_inactives($this->query_parms['inactives'])
->include_templates(true) ->include_templates(true)
@@ -115,96 +116,83 @@ class Manage extends \Alchemy\Phrasea\Helper\Helper
->limit($offset_start, $results_quantity) ->limit($offset_start, $results_quantity)
->execute(); ->execute();
try try {
{ $invite_id = \User_Adapter::get_usr_id_from_login('invite');
$invite_id = \User_Adapter::get_usr_id_from_login('invite'); $invite = \User_Adapter::getInstance($invite_id, $appbox);
$invite = \User_Adapter::getInstance($invite_id, $appbox); } catch (\Exception $e) {
} $invite = \User_Adapter::create($appbox, 'invite', 'invite', '', false);
catch (\Exception $e) }
{
$invite = \User_Adapter::create($appbox, 'invite', 'invite', '', false); try {
$autoregister_id = \User_Adapter::get_usr_id_from_login('autoregister');
$autoregister = \User_Adapter::getInstance($autoregister_id, $appbox);
} catch (Exception $e) {
$autoregister = \User_Adapter::create($appbox, 'autoregister', 'autoregister', '', false);
}
foreach ($this->query_parms as $k => $v) {
if (is_null($v))
$this->query_parms[$k] = false;
}
$query = new \User_Query($appbox);
$templates = $query
->only_templates(true)
->execute()->get_results();
return array(
'users' => $this->results,
'parm' => $this->query_parms,
'invite_user' => $invite,
'autoregister_user' => $autoregister,
'templates' => $templates
);
} }
try public function create_newuser()
{ {
$autoregister_id = \User_Adapter::get_usr_id_from_login('autoregister'); $email = $this->request->get('value');
$autoregister = \User_Adapter::getInstance($autoregister_id, $appbox);
} if ( ! \mail::validateEmail($email)) {
catch (Exception $e) throw new \Exception_InvalidArgument(_('Invalid mail address'));
{ }
$autoregister = \User_Adapter::create($appbox, 'autoregister', 'autoregister', '', false);
$appbox = \appbox::get_instance($this->core);
$conn = $appbox->get_connection();
$sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$count = count($row);
if ( ! is_array($row) || $count == 0) {
$created_user = \User_Adapter::create($appbox, $email, \random::generatePassword(16), $email, false, false);
$this->usr_id = $created_user->get_id();
} else {
$this->usr_id = $row['usr_id'];
$created_user = \User_Adapter::getInstance($this->usr_id, $appbox);
}
return $created_user;
} }
foreach ($this->query_parms as $k => $v) public function create_template()
{ {
if (is_null($v)) $name = $this->request->get('value');
$this->query_parms[$k] = false;
if (trim($name) === '') {
throw new \Exception_InvalidArgument(_('Invalid template name'));
}
$appbox = \appbox::get_instance($this->core);
$user = $this->getCore()->getAuthenticatedUser();
$created_user = \User_Adapter::create($appbox, $name, \random::generatePassword(16), null, false, false);
$created_user->set_template($user);
$this->usr_id = $user->get_id();
return $created_user;
} }
$query = new \User_Query($appbox);
$templates = $query
->only_templates(true)
->execute()->get_results();
return array(
'users' => $this->results,
'parm' => $this->query_parms,
'invite_user' => $invite,
'autoregister_user' => $autoregister,
'templates' => $templates
);
}
public function create_newuser()
{
$email = $this->request->get('value');
if(!\mail::validateEmail($email))
{
throw new \Exception_InvalidArgument(_('Invalid mail address'));
}
$appbox = \appbox::get_instance($this->core);
$conn = $appbox->get_connection();
$sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$count = count($row);
if (!is_array($row) || $count == 0)
{
$created_user = \User_Adapter::create($appbox, $email, \random::generatePassword(16), $email, false, false);
$this->usr_id = $created_user->get_id();
}
else
{
$this->usr_id = $row['usr_id'];
$created_user = \User_Adapter::getInstance($this->usr_id, $appbox);
}
return $created_user;
}
public function create_template()
{
$name = $this->request->get('value');
if(trim($name) === '')
{
throw new \Exception_InvalidArgument(_('Invalid template name'));
}
$appbox = \appbox::get_instance($this->core);
$user = $this->getCore()->getAuthenticatedUser();
$created_user = \User_Adapter::create($appbox, $name, \random::generatePassword(16), null, false, false);
$created_user->set_template($user);
$this->usr_id = $user->get_id();
return $created_user;
}
} }

View File

@@ -26,56 +26,50 @@ use Symfony\Component\HttpFoundation\Request;
*/ */
class WorkZone extends Helper class WorkZone extends Helper
{ {
const BASKETS = 'baskets';
const STORIES = 'stories';
const VALIDATIONS = 'validations';
const BASKETS = 'baskets'; /**
const STORIES = 'stories'; *
const VALIDATIONS = 'validations'; * Returns an ArrayCollection containing three keys :
* - self::BASKETS : an ArrayCollection of the actives baskets
* (Non Archived)
* - self::STORIES : an ArrayCollection of working stories
* - self::VALIDATIONS : the validation people are waiting from me
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getContent($sort)
{
$em = $this->getCore()->getEntityManager();
$current_user = $this->getCore()->getAuthenticatedUser();
/** /* @var $repo_baskets \Doctrine\Repositories\BasketRepository */
* $repo_baskets = $em->getRepository('Entities\Basket');
* Returns an ArrayCollection containing three keys :
* - self::BASKETS : an ArrayCollection of the actives baskets
* (Non Archived)
* - self::STORIES : an ArrayCollection of working stories
* - self::VALIDATIONS : the validation people are waiting from me
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getContent($sort)
{
$em = $this->getCore()->getEntityManager();
$current_user = $this->getCore()->getAuthenticatedUser();
/* @var $repo_baskets \Doctrine\Repositories\BasketRepository */ $sort = in_array($sort, array('date', 'name')) ? $sort : 'name';
$repo_baskets = $em->getRepository('Entities\Basket');
$sort = in_array($sort, array('date', 'name')) ? $sort : 'name'; $ret = new \Doctrine\Common\Collections\ArrayCollection();
$ret = new \Doctrine\Common\Collections\ArrayCollection(); $baskets = $repo_baskets->findActiveByUser($current_user, $sort);
$validations = $repo_baskets->findActiveValidationByUser($current_user, $sort);
$baskets = $repo_baskets->findActiveByUser($current_user, $sort); /* @var $repo_stories \Doctrine\Repositories\StoryWZRepository */
$validations = $repo_baskets->findActiveValidationByUser($current_user, $sort); $repo_stories = $em->getRepository('Entities\StoryWZ');
/* @var $repo_stories \Doctrine\Repositories\StoryWZRepository */ $stories = $repo_stories->findByUser($current_user, $sort);
$repo_stories = $em->getRepository('Entities\StoryWZ');
$stories = $repo_stories->findByUser($current_user, $sort); $ret->set(self::BASKETS, $baskets);
$ret->set(self::VALIDATIONS, $validations);
$ret->set(self::STORIES, $stories);
$ret->set(self::BASKETS, $baskets); return $ret;
$ret->set(self::VALIDATIONS, $validations); }
$ret->set(self::STORIES, $stories);
return $ret;
}
protected function sortBaskets(array $baskets)
{
$tmp_baskets = array();
}
protected function sortBaskets(array $baskets)
{
$tmp_baskets = array();
}
} }

View File

@@ -27,12 +27,12 @@ use Doctrine\Common\Cache\ApcCache;
*/ */
Class ApcAutoloader extends ApcCache implements CacheStrategy Class ApcAutoloader extends ApcCache implements CacheStrategy
{ {
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return extension_loaded('apc');
}
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return extension_loaded('apc');
}
} }

View File

@@ -23,90 +23,83 @@ use Symfony\Component\ClassLoader\UniversalClassLoader;
*/ */
class Autoloader extends UniversalClassLoader class Autoloader extends UniversalClassLoader
{ {
/**
* An array of path to check
* @var type
*/
private $paths = array();
private $classmap = array();
/** /**
* An array of path to check * Construct a new phrasea Autoloader
* @var type * Because some custom classes from library folder might be
*/ * overwritten in config folder
private $paths = array(); * Phraseanet Loader look classes in configuration folders first
private $classmap = array(); * then check library folder if no classes where matched
*/
public function __construct()
{
$this->paths['config'] = __DIR__ . '/../../../../config/classes/';
$this->paths['library'] = __DIR__ . '/../../../classes/';
/** $getComposerClassMap = function() {
* Construct a new phrasea Autoloader return require realpath(__DIR__ . '/../../../../vendor/.composer/autoload_classmap.php');
* Because some custom classes from library folder might be
* overwritten in config folder
* Phraseanet Loader look classes in configuration folders first
* then check library folder if no classes where matched
*/
public function __construct()
{
$this->paths['config'] = __DIR__ . '/../../../../config/classes/';
$this->paths['library'] = __DIR__ . '/../../../classes/';
$getComposerClassMap = function()
{
return require realpath(__DIR__ . '/../../../../vendor/.composer/autoload_classmap.php');
}; };
$this->classmap = $getComposerClassMap(); $this->classmap = $getComposerClassMap();
}
/**
* {@inheritdoc}
*/
public function findFile($class)
{
if (!$file = $this->checkFile($class))
{
$file = parent::findFile($class);
} }
return $file; /**
} * {@inheritdoc}
*/
/** public function findFile($class)
* Add a path to look for autoloading phraseanet classes
* @param string $name
* @param string $path
*/
public function addPath($name, $path)
{
$this->paths[$name] = \p4string::addEndSlash($path);
}
/**
* Check whether a class with $class name exists
* foreach declared paths
* @param string $class
* @return mixed string|null
*/
private function checkFile($classname)
{
if (isset($this->classmap[$classname]))
{ {
return $this->classmap[$classname]; if ( ! $file = $this->checkFile($class)) {
} $file = parent::findFile($class);
}
$normalized_classname = str_replace('_', '/', $classname);
foreach ($this->paths as $path)
{
$file = $path . $normalized_classname . '.class.php';
if (file_exists($file))
{
return $file; return $file;
}
} }
}
/** /**
* Get Paths where classes are checked for autoloading * Add a path to look for autoloading phraseanet classes
* @return Array * @param string $name
*/ * @param string $path
public function getPaths() */
{ public function addPath($name, $path)
return $this->paths; {
} $this->paths[$name] = \p4string::addEndSlash($path);
}
/**
* Check whether a class with $class name exists
* foreach declared paths
* @param string $class
* @return mixed string|null
*/
private function checkFile($classname)
{
if (isset($this->classmap[$classname])) {
return $this->classmap[$classname];
}
$normalized_classname = str_replace('_', '/', $classname);
foreach ($this->paths as $path) {
$file = $path . $normalized_classname . '.class.php';
if (file_exists($file)) {
return $file;
}
}
}
/**
* Get Paths where classes are checked for autoloading
* @return Array
*/
public function getPaths()
{
return $this->paths;
}
} }

View File

@@ -23,117 +23,107 @@ require_once __DIR__ . '/Autoloader.php';
*/ */
class CacheAutoloader extends Autoloader class CacheAutoloader extends Autoloader
{ {
/**
* Array of all cache adapters
* @var type
*/
private $cacheAdapters = array(
'Apc',
'Xcache'
);
/** /**
* Array of all cache adapters * The cache adapater
* @var type * @var type
*/ */
private $cacheAdapters = array( private $cacheAdapter;
'Apc',
'Xcache'
);
/** /**
* The cache adapater * The prefix used to store id's in cache
* @var type * @var string
*/ */
private $cacheAdapter; private $prefix;
/** /**
* The prefix used to store id's in cache * Take a identifier cache key prefix
* @var string * @param string $prefix
*/ * @throws \Exceptionwhen none of the op cache code are available
private $prefix; */
public function __construct($prefix, $namespace = null)
/**
* Take a identifier cache key prefix
* @param string $prefix
* @throws \Exceptionwhen none of the op cache code are available
*/
public function __construct($prefix, $namespace = null)
{
parent::__construct();
$this->prefix = $prefix;
foreach ($this->cacheAdapters as $className)
{ {
$file = sprintf("%s/%sAutoloader.php", __DIR__, $className); parent::__construct();
if (!file_exists($file)) $this->prefix = $prefix;
{
continue;
}
require_once $file; foreach ($this->cacheAdapters as $className) {
$file = sprintf("%s/%sAutoloader.php", __DIR__, $className);
$className = sprintf("\Alchemy\Phrasea\Loader\%sAutoloader", $className); if ( ! file_exists($file)) {
continue;
}
if (!class_exists($className)) require_once $file;
{
continue;
}
$method = new $className(); $className = sprintf("\Alchemy\Phrasea\Loader\%sAutoloader", $className);
if($namespace) if ( ! class_exists($className)) {
{ continue;
$method->setNamespace($namespace); }
}
if ($method instanceof LoaderStrategy && $method->isAvailable()) $method = new $className();
{
$this->cacheAdapter = $method; if ($namespace) {
break; $method->setNamespace($namespace);
} }
if ($method instanceof LoaderStrategy && $method->isAvailable()) {
$this->cacheAdapter = $method;
break;
}
}
if (null === $this->cacheAdapter) {
throw new \Exception('No Cache available');
}
} }
if (null === $this->cacheAdapter) /**
* {@inheritdoc}
*/
public function findFile($class)
{ {
throw new \Exception('No Cache available'); $file = $this->cacheAdapter->fetch($this->prefix . $class);
}
}
/** if (false === $file) {
* {@inheritdoc} $this->cacheAdapter->save($this->prefix . $class, $file = parent::findFile($class));
*/ }
public function findFile($class)
{
$file = $this->cacheAdapter->fetch($this->prefix . $class);
if (false === $file) return $file;
{
$this->cacheAdapter->save($this->prefix . $class, $file = parent::findFile($class));
} }
return $file; /**
} * {@inheritdoc}
*/
/** public function register($prepend = false)
* {@inheritdoc} {
*/ spl_autoload_register(array($this, 'loadClass'), true, $prepend);
public function register($prepend = false) }
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Get the current cache Adapter
* @return LoaderStrategy
*/
public function getAdapter()
{
return $this->cacheAdapter;
}
/**
* Get the identifier cache key prefix
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Get the current cache Adapter
* @return LoaderStrategy
*/
public function getAdapter()
{
return $this->cacheAdapter;
}
/**
* Get the identifier cache key prefix
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
} }

View File

@@ -20,10 +20,9 @@ namespace Alchemy\Phrasea\Loader;
interface LoaderStrategy interface LoaderStrategy
{ {
/** /**
* Check wether the cacheAdapter is available * Check wether the cacheAdapter is available
* @Return boolean * @Return boolean
*/ */
public function isAvailable(); public function isAvailable();
} }

View File

@@ -18,6 +18,7 @@ require_once __DIR__ . '/../../../../vendor/doctrine/common/lib/Doctrine/Common/
use Alchemy\Phrasea\Loader\LoaderStrategy as CacheStrategy; use Alchemy\Phrasea\Loader\LoaderStrategy as CacheStrategy;
use Doctrine\Common\Cache\XcacheCache; use Doctrine\Common\Cache\XcacheCache;
/** /**
* *
* @package * @package
@@ -27,12 +28,11 @@ use Doctrine\Common\Cache\XcacheCache;
Class XcacheAutoloader extends XcacheCache implements CacheStrategy Class XcacheAutoloader extends XcacheCache implements CacheStrategy
{ {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function isAvailable() public function isAvailable()
{ {
return extension_loaded('xcache') && PHP_SAPI !== 'cli'; return extension_loaded('xcache') && PHP_SAPI !== 'cli';
} }
} }

View File

@@ -13,17 +13,16 @@ namespace Alchemy\Phrasea\Media\Subdef;
class Audio extends Provider class Audio extends Provider
{ {
const OPTION_BITRATE = 'bitrate';
const OPTION_BITRATE = 'bitrate'; const OPTION_THREADS = 'threads';
const OPTION_THREADS = 'threads'; const OPTION_ACODEC = 'a_codec';
const OPTION_ACODEC = 'a_codec';
const OPTION_AUDIOSAMPLERATE = 'audiosamplerate'; const OPTION_AUDIOSAMPLERATE = 'audiosamplerate';
public function __construct() public function __construct()
{ {
$AVaudiosamplerate = array( $AVaudiosamplerate = array(
8000, 11025, 16000, 22050, 32000, 44056, 44100, 8000, 11025, 16000, 22050, 32000, 44056, 44100,
47250, 48000, 50000, 50400, 88200, 96000, null 47250, 48000, 50000, 50400, 88200, 96000, null
); );
$this->registerOption(new OptionType\Range(self::OPTION_BITRATE, 100, 4000, 800)); $this->registerOption(new OptionType\Range(self::OPTION_BITRATE, 100, 4000, 800));
@@ -44,8 +43,7 @@ class Audio extends Provider
public function getMediaAlchemystSpec() public function getMediaAlchemystSpec()
{ {
if ( ! $this->spec) if ( ! $this->spec) {
{
$this->spec = new \MediaAlchemyst\Specification\Audio(); $this->spec = new \MediaAlchemyst\Specification\Audio();
} }
@@ -55,5 +53,4 @@ class Audio extends Provider
return $this->spec; return $this->spec;
} }
} }

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef;
class FlexPaper extends Provider class FlexPaper extends Provider
{ {
protected $options = array(); protected $options = array();
public function __construct() public function __construct()
@@ -33,12 +32,10 @@ class FlexPaper extends Provider
public function getMediaAlchemystSpec() public function getMediaAlchemystSpec()
{ {
if ( ! $this->spec) if ( ! $this->spec) {
{
$this->spec = new \MediaAlchemyst\Specification\Flash(); $this->spec = new \MediaAlchemyst\Specification\Flash();
} }
return $this->spec; return $this->spec;
} }
} }

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef;
class Gif extends Image class Gif extends Image
{ {
const OPTION_DELAY = 'delay'; const OPTION_DELAY = 'delay';
public function __construct() public function __construct()
@@ -35,12 +34,11 @@ class Gif extends Image
public function getMediaAlchemystSpec() public function getMediaAlchemystSpec()
{ {
if ( ! $this->spec) if ( ! $this->spec) {
{
$this->spec = new \MediaAlchemyst\Specification\Animation(); $this->spec = new \MediaAlchemyst\Specification\Animation();
} }
$size = $this->getOption(self::OPTION_SIZE)->getValue(); $size = $this->getOption(self::OPTION_SIZE)->getValue();
$resolution = $this->getOption(self::OPTION_RESOLUTION)->getValue(); $resolution = $this->getOption(self::OPTION_RESOLUTION)->getValue();
$this->spec->setDelay($this->getOption(self::OPTION_DELAY)->getValue()); $this->spec->setDelay($this->getOption(self::OPTION_DELAY)->getValue());
@@ -51,5 +49,4 @@ class Gif extends Image
return $this->spec; return $this->spec;
} }
} }

View File

@@ -13,11 +13,11 @@ namespace Alchemy\Phrasea\Media\Subdef;
class Image extends Provider class Image extends Provider
{ {
const OPTION_SIZE = 'size'; const OPTION_SIZE = 'size';
const OPTION_RESOLUTION = 'resolution'; const OPTION_RESOLUTION = 'resolution';
const OPTION_STRIP = 'strip'; const OPTION_STRIP = 'strip';
const OPTION_QUALITY = 'quality'; const OPTION_QUALITY = 'quality';
protected $options = array(); protected $options = array();
public function __construct() public function __construct()
@@ -40,12 +40,11 @@ class Image extends Provider
public function getMediaAlchemystSpec() public function getMediaAlchemystSpec()
{ {
if ( ! $this->spec) if ( ! $this->spec) {
{
$this->spec = new \MediaAlchemyst\Specification\Image(); $this->spec = new \MediaAlchemyst\Specification\Image();
} }
$size = $this->getOption(self::OPTION_SIZE)->getValue(); $size = $this->getOption(self::OPTION_SIZE)->getValue();
$resolution = $this->getOption(self::OPTION_RESOLUTION)->getValue(); $resolution = $this->getOption(self::OPTION_RESOLUTION)->getValue();
$this->spec->setDimensions($size, $size); $this->spec->setDimensions($size, $size);
@@ -55,5 +54,4 @@ class Image extends Provider
return $this->spec; return $this->spec;
} }
} }

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef\OptionType;
class Boolean implements OptionType class Boolean implements OptionType
{ {
protected $name; protected $name;
protected $default_value; protected $default_value;
protected $value; protected $value;
@@ -23,8 +22,7 @@ class Boolean implements OptionType
$this->name = $name; $this->name = $name;
$this->default_value = $default_value; $this->default_value = $default_value;
if ($default_value) if ($default_value) {
{
$this->setValue($default_value); $this->setValue($default_value);
} }
} }
@@ -50,5 +48,4 @@ class Boolean implements OptionType
{ {
return $this->value; return $this->value;
} }
} }

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef\OptionType;
class Enum implements OptionType class Enum implements OptionType
{ {
protected $default_value; protected $default_value;
protected $value; protected $value;
protected $available; protected $available;
@@ -24,23 +23,21 @@ class Enum implements OptionType
$this->available = $available; $this->available = $available;
$this->default_value = $default_value; $this->default_value = $default_value;
if ($default_value) if ($default_value) {
{
$this->setValue($default_value); $this->setValue($default_value);
} }
} }
public function setValue($value) public function setValue($value)
{ {
if ( ! in_array($value, $this->available)) if ( ! in_array($value, $this->available)) {
{
throw new \Exception_InvalidArgument( throw new \Exception_InvalidArgument(
sprintf( sprintf(
'The value provided `%s` for %s does not fit in range ; available are %s' 'The value provided `%s` for %s does not fit in range ; available are %s'
, $value , $value
, $this->getName() , $this->getName()
, implode(', ', $this->getAvailableValues()) , implode(', ', $this->getAvailableValues())
) )
); );
} }
@@ -68,5 +65,4 @@ class Enum implements OptionType
{ {
return $this->value; return $this->value;
} }
} }

View File

@@ -18,6 +18,8 @@ interface OptionType
const TYPE_BOOLEAN = 'Boolean'; const TYPE_BOOLEAN = 'Boolean';
public function getType(); public function getType();
public function getName(); public function getName();
public function getValue(); public function getValue();
} }

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef\OptionType;
class Range implements OptionType class Range implements OptionType
{ {
protected $min_value; protected $min_value;
protected $max_value; protected $max_value;
protected $default_value; protected $default_value;
@@ -28,16 +27,14 @@ class Range implements OptionType
$this->default_value = $default_value; $this->default_value = $default_value;
$this->step = $step; $this->step = $step;
if ($default_value) if ($default_value) {
{
$this->setValue($default_value); $this->setValue($default_value);
} }
} }
public function setValue($value) public function setValue($value)
{ {
if ($value > $this->max_value || $value < $this->min_value) if ($value > $this->max_value || $value < $this->min_value) {
{
throw new \Exception_InvalidArgument('The value provided does not fit in range'); throw new \Exception_InvalidArgument('The value provided does not fit in range');
} }
@@ -75,5 +72,4 @@ class Range implements OptionType
{ {
return $this->max_value; return $this->max_value;
} }
} }

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef;
abstract class Provider implements Subdef abstract class Provider implements Subdef
{ {
protected $options = array(); protected $options = array();
protected $spec; protected $spec;
@@ -40,5 +39,4 @@ abstract class Provider implements Subdef
return $this; return $this;
} }
} }

View File

@@ -13,11 +13,10 @@ namespace Alchemy\Phrasea\Media\Subdef;
interface Subdef interface Subdef
{ {
const TYPE_IMAGE = 'image';
const TYPE_IMAGE = 'image';
const TYPE_ANIMATION = 'gif'; const TYPE_ANIMATION = 'gif';
const TYPE_VIDEO = 'video'; const TYPE_VIDEO = 'video';
const TYPE_AUDIO = 'audio'; const TYPE_AUDIO = 'audio';
const TYPE_FLEXPAPER = 'flexpaper'; const TYPE_FLEXPAPER = 'flexpaper';
public function getType(); public function getType();
@@ -25,5 +24,4 @@ interface Subdef
public function getDescription(); public function getDescription();
public function getMediaAlchemystSpec(); public function getMediaAlchemystSpec();
} }

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