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

View File

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

View File

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

View File

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

View File

@@ -17,50 +17,45 @@ set_time_limit(0);
$finder = new Finder();
$finder
->files()
->name('*.gif')
->name('*.jpeg')
->name('*.jpg')
->name('*.png')
->notName('ui-*.png')
->exclude(
array(
'substitution'
, 'client/959595/images'
, 'client/000000/images'
, 'client/FFFFFF/images'
, 'skins/lng'
)
)
->in(__DIR__ . '/www/skins');
->files()
->name('*.gif')
->name('*.jpeg')
->name('*.jpg')
->name('*.png')
->notName('ui-*.png')
->exclude(
array(
'substitution'
, 'client/959595/images'
, 'client/000000/images'
, 'client/FFFFFF/images'
, 'skins/lng'
)
)
->in(__DIR__ . '/www/skins');
$files = array();
foreach ($finder as $file)
{
$result = '';
foreach ($finder as $file) {
$result = '';
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;
$result .= @exec($cmd);
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;
$result .= @exec($cmd);
if (trim($result) !== '')
{
break;
if (trim($result) !== '') {
break;
}
}
}
if (trim($result) === '')
{
$files[] = $file->getPathname();
}
if (trim($result) === '') {
$files[] = $file->getPathname();
}
}
foreach ($files as $file)
{
echo "rm $file\n";
unlink($file);
foreach ($files as $file) {
echo "rm $file\n";
unlink($file);
}
exit(0);

View File

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

View File

@@ -21,24 +21,23 @@ use Alchemy\Phrasea\Controller\Utils as ControllerUtils;
* @link www.phraseanet.com
*/
return call_user_func(
function()
{
$app = new \Silex\Application();
function() {
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore();
$app['Core'] = \bootstrap::getCore();
$app->mount('/', new Controller\Root());
$app->mount('/publications', new Controller\Publications());
$app->mount('/users', new Controller\Users());
$app->mount('/fields', new Controller\Fields());
$app->mount('/subdefs', new Controller\Subdefs);
$app->mount('/description', new Controller\Description());
$app->mount('/tests/connection', new ControllerUtils\ConnectionTest());
$app->mount('/tests/pathurl', new ControllerUtils\PathFileTest());
$app->mount('/', new Controller\Root());
$app->mount('/publications', new Controller\Publications());
$app->mount('/users', new Controller\Users());
$app->mount('/fields', new Controller\Fields());
$app->mount('/subdefs', new Controller\Subdefs);
$app->mount('/description', new Controller\Description());
$app->mount('/tests/connection', new ControllerUtils\ConnectionTest());
$app->mount('/tests/pathurl', new ControllerUtils\PathFileTest());
$app->error(function($e){
return new \Symfony\Component\HttpFoundation\Response($e->getMessage(), 403);
});
$app->error(function($e) {
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
* @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(
'/', function() use ($app)
{
$registry = $app["Core"]->getRegistry();
$app->get(
'/', function() use ($app) {
$registry = $app["Core"]->getRegistry();
$apiAdapter = new \API_V1_adapter(false, $app["appbox"], $app["Core"]);
$versionNumber = (float) \Alchemy\Phrasea\Core\Version::getNumber();
$ret = array(
'install_name' => $registry->get('GV_homeTitle'),
'description' => $registry->get('GV_metaDescription'),
'documentation' => 'https://docs.phraseanet.com/Devel',
'versions' => array(
'1' => array(
'number' => $apiAdapter->get_version(),
'uri' => '/api/v1/',
'authenticationProtocol' => 'OAuth2',
'authenticationVersion' => 'draft#v9',
'authenticationEndPoints' => array(
'authorization_token' => '/api/oauthv2/authorize',
'access_token' => '/api/oauthv2/token'
)
)
)
);
$apiAdapter = new \API_V1_adapter(false, $app["appbox"], $app["Core"]);
$versionNumber = (float) \Alchemy\Phrasea\Core\Version::getNumber();
$ret = array(
'install_name' => $registry->get('GV_homeTitle'),
'description' => $registry->get('GV_metaDescription'),
'documentation' => 'https://docs.phraseanet.com/Devel',
'versions' => array(
'1' => array(
'number' => $apiAdapter->get_version(),
'uri' => '/api/v1/',
'authenticationProtocol' => 'OAuth2',
'authenticationVersion' => 'draft#v9',
'authenticationEndPoints' => array(
'authorization_token' => '/api/oauthv2/authorize',
'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 $app;
return new Response($json, 200, array('content-type' => 'application/json'));
});
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
* @link www.phraseanet.com
*/
return call_user_func(function()
{
$app = new \Silex\Application();
return call_user_func(function() {
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore();
$app['Core'] = \bootstrap::getCore();
$app->register(new \Silex\Provider\ValidatorServiceProvider(), array(
'validator.class_path' => __DIR__ . '/../../../../vendor/symfony/validator',
));
$app->register(new \Silex\Provider\ValidatorServiceProvider(), array(
'validator.class_path' => __DIR__ . '/../../../../vendor/symfony/validator',
));
$app['appbox'] = function() use ($app)
{
return \appbox::get_instance($app['Core']);
};
$app['appbox'] = function() use ($app) {
return \appbox::get_instance($app['Core']);
};
$app['oauth'] = function($app)
{
return new \API_OAuth2_Adapter($app['appbox']);
};
$app['oauth'] = function($app) {
return new \API_OAuth2_Adapter($app['appbox']);
};
/**
* Protected Closure
* @var Closure
* @return Symfony\Component\HttpFoundation\Response
*/
$app['response'] = $app->protect(function ($template, $variable) use ($app)
{
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/**
* Protected Closure
* @var Closure
* @return Symfony\Component\HttpFoundation\Response
*/
$app['response'] = $app->protect(function ($template, $variable) use ($app) {
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$response = new Response(
$twig->render($template, $variable)
, 200
, array('Content-Type' => 'text/html')
);
$response->setCharset('UTF-8');
$response = new Response(
$twig->render($template, $variable)
, 200
, array('Content-Type' => 'text/html')
);
$response->setCharset('UTF-8');
return $response;
});
return $response;
});
/* * *******************************************************************
* AUTHENTIFICATION API
*/
/* * *******************************************************************
* AUTHENTIFICATION API
*/
/**
* AUTHORIZE ENDPOINT
*
* Authorization endpoint - used to obtain authorization from the
* resource owner via user-agent redirection.
*/
$authorize_func = function() use ($app)
{
$request = $app['request'];
$oauth2_adapter = $app['oauth'];
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$session = $app['appbox']->get_session();
/**
* AUTHORIZE ENDPOINT
*
* Authorization endpoint - used to obtain authorization from the
* resource owner via user-agent redirection.
*/
$authorize_func = function() use ($app) {
$request = $app['request'];
$oauth2_adapter = $app['oauth'];
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$session = $app['appbox']->get_session();
//Check for auth params, send error or redirect if not valid
$params = $oauth2_adapter->getAuthorizationRequestParameters($request);
//Check for auth params, send error or redirect if not valid
$params = $oauth2_adapter->getAuthorizationRequestParameters($request);
$authenticated = $session->is_authenticated();
$app_authorized = false;
$errorMessage = false;
$authenticated = $session->is_authenticated();
$app_authorized = 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_login = $request->get("action_login", null);
$action_accept = $request->get("action_accept", 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(
"%sconfig/templates/web/api/auth/end_user_authorization/%s.twig"
, $app['appbox']->get_registry()->get('GV_RootPath')
, $client->get_id()
);
$custom_template = sprintf(
"%sconfig/templates/web/api/auth/end_user_authorization/%s.twig"
, $app['appbox']->get_registry()->get('GV_RootPath')
, $client->get_id()
);
if (file_exists($custom_template))
{
$template = sprintf(
'api/auth/end_user_authorization/%s.twig'
, $client->get_id()
);
}
if (file_exists($custom_template)) {
$template = sprintf(
'api/auth/end_user_authorization/%s.twig'
, $client->get_id()
);
}
if ( ! $authenticated)
{
if ($action_login !== null)
{
try
{
$login = $request->get("login");
$password = $request->get("password");
$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
{
if ( ! $authenticated) {
if ($action_login !== null) {
try {
$login = $request->get("login");
$password = $request->get("password");
$auth = new \Session_Authentication_Native($app['appbox'], $login, $password);
$session->authenticate($auth);
} catch (\Exception $e) {
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['Core']->getAuthenticatedUser()
"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"));
}
}
//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()
} else {
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['Core']->getAuthenticatedUser()
);
$html = $twig->render($template, $params);
foreach ($user_auth_clients as $auth_client)
{
if ($client->get_client_id() == $auth_client->get_client_id())
$app_authorized = true;
}
return new Response($html, 200, array("content-type" => "text/html"));
}
}
$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)
{
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['Core']->getAuthenticatedUser()
);
$account = $oauth2_adapter->updateAccount($session->get_usr_id());
$html = $twig->render($template, $params);
$params['account_id'] = $account->get_id();
return new Response($html, 200, array("content-type" => "text/html"));
}
elseif ( ! $app_authorized && $action_accept !== null)
{
$app_authorized = ! ! $action_accept;
$account->set_revoked( ! $app_authorized);
}
if ( ! $app_authorized && $action_accept === null) {
$params = array(
"auth" => $oauth2_adapter
, "session" => $session
, "errorMessage" => $errorMessage
, "user" => $app['Core']->getAuthenticatedUser()
);
//if native app show template
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);
$html = $twig->render($template, $params);
return new Response($html, 200, array("content-type" => "text/html"));
}
else
{
$oauth2_adapter->finishClientAuthorization($app_authorized, $params);
}
};
return new Response($html, 200, array("content-type" => "text/html"));
} elseif ( ! $app_authorized && $action_accept !== null) {
$app_authorized = ! ! $action_accept;
$account->set_revoked( ! $app_authorized);
}
$route = '/authorize';
$app->get($route, $authorize_func);
$app->post($route, $authorize_func);
//if native app show template
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"));
} else {
$oauth2_adapter->finishClientAuthorization($app_authorized, $params);
}
};
$route = '/authorize';
$app->get($route, $authorize_func);
$app->post($route, $authorize_func);
/**
* TOKEN ENDPOINT
* Token endpoint - used to exchange an authorization grant for an access token.
*/
$route = '/token';
$app->post($route, function(\Silex\Application $app, Request $request)
{
if(!$request->isSecure())
{
throw new HttpException(400, 'require the use of the https', null, array('content-type'=> 'application/json'));
}
/**
* TOKEN ENDPOINT
* Token endpoint - used to exchange an authorization grant for an access token.
*/
$route = '/token';
$app->post($route, function(\Silex\Application $app, Request $request) {
if ( ! $request->isSecure()) {
throw new HttpException(400, 'require the use of the https', null, array('content-type' => 'application/json'));
}
$app['oauth']->grantAccessToken();
ob_flush();
flush();
$app['oauth']->grantAccessToken();
ob_flush();
flush();
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;
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;
});

View File

@@ -23,235 +23,199 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @link www.phraseanet.com
*/
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']);
$session = $appbox->get_session();
$appbox = \appbox::get_instance($app['Core']);
$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);
if ($file->get_baseurl() !== '')
{
return $app->redirect($file->get_url());
}
$file = $record->get_subdef($subdef);
if ($file->get_baseurl() !== '') {
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)
{
$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());
}
if ($watermark === true && $file->get_type() === \media_subdef::TYPE_IMAGE) {
$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());
}
$log_id = null;
try
{
$registry = \registry::get_instance();
$logger = $session->get_logger($record->get_databox());
$log_id = $logger->get_id();
$log_id = null;
try {
$registry = \registry::get_instance();
$logger = $session->get_logger($record->get_databox());
$log_id = $logger->get_id();
$referrer = 'NO REFERRER';
$referrer = 'NO REFERRER';
if (isset($_SERVER['HTTP_REFERER']))
$referrer = $_SERVER['HTTP_REFERER'];
if (isset($_SERVER['HTTP_REFERER']))
$referrer = $_SERVER['HTTP_REFERER'];
$record->log_view($log_id, $referrer, $registry->get('GV_sit'));
}
catch (\Exception $e)
{
$record->log_view($log_id, $referrer, $registry->get('GV_sit'));
} 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);
$record = new \record_adapter($sbas_id, $record_id);
$databox = \databox::get_instance((int) $sbas_id);
$record = new \record_adapter($sbas_id, $record_id);
$record->get_type();
$record->get_type();
if ( ! $session->is_authenticated())
throw new \Exception_Session_NotAuthenticated();
if ( ! $session->is_authenticated())
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))
throw new \Exception_UnauthorizedAction();
if ( ! $user->ACL()->has_access_to_subdef($record, $subdef))
throw new \Exception_UnauthorizedAction();
$stamp = false;
$watermark = ! $user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark');
$stamp = false;
$watermark = ! $user->ACL()->has_right_on_base($record->get_base_id(), 'nowatermark');
if ($watermark)
{
$subdef_class = $databox
->get_subdef_structure()
->get_subdef($record->get_type(), $subdef)
->get_class();
if ($watermark) {
$subdef_class = $databox
->get_subdef_structure()
->get_subdef($record->get_type(), $subdef)
->get_class();
if ($subdef_class == \databox_subdef::CLASS_PREVIEW && $user->ACL()->has_preview_grant($record))
{
$watermark = false;
}
elseif ($subdef_class == \databox_subdef::CLASS_DOCUMENT && $user->ACL()->has_hd_grant($record))
{
$watermark = false;
}
}
if ($subdef_class == \databox_subdef::CLASS_PREVIEW && $user->ACL()->has_preview_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);
$ReceptionByRecord = $repository->findReceivedElementsByRecord($record, $user);
$ValidationByRecord = $repository->findReceivedValidationElementsByRecord($record, $user);
$ReceptionByRecord = $repository->findReceivedElementsByRecord($record, $user);
if ($ValidationByRecord && $ValidationByRecord->count() > 0)
{
$watermark = false;
}
elseif ($ReceptionByRecord && $ReceptionByRecord->count() > 0)
{
$watermark = false;
}
}
if ($ValidationByRecord && $ValidationByRecord->count() > 0) {
$watermark = false;
} elseif ($ReceptionByRecord && $ReceptionByRecord->count() > 0) {
$watermark = false;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/view/'
, function($label, $sbas_id, $record_id, $key, $subdef) use($app)
{
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/view/'
, 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))
throw new \Exception('bad luck');
if ( ! ($record instanceof \record_adapter))
throw new \Exception('bad luck');
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$params = array(
'subdef_name' => $subdef
, 'module_name' => 'overview'
, 'module' => 'overview'
, 'view' => 'overview'
, 'record' => $record
);
$params = array(
'subdef_name' => $subdef
, 'module_name' => 'overview'
, 'module' => 'overview'
, 'view' => 'overview'
, 'record' => $record
);
return $twig->render('overview.twig', $params);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
return $twig->render('overview.twig', $params);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/'
, function($label, $sbas_id, $record_id, $key, $subdef) use ($app, $session, $deliver_content)
{
$databox = \databox::get_instance((int) $sbas_id);
$record = \media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef);
if ( ! ($record instanceof \record_adapter))
throw new \Exception('bad luck');
$app->get('/permalink/v1/{label}/{sbas_id}/{record_id}/{key}/{subdef}/'
, function($label, $sbas_id, $record_id, $key, $subdef) use ($app, $session, $deliver_content) {
$databox = \databox::get_instance((int) $sbas_id);
$record = \media_Permalink_Adapter::challenge_token($databox, $key, $record_id, $subdef);
if ( ! ($record instanceof \record_adapter))
throw new \Exception('bad luck');
$watermark = $stamp = false;
$watermark = $stamp = false;
if ($session->is_authenticated())
{
$user = \User_Adapter::getInstance($session->get_usr_id(), \appbox::get_instance($app['Core']));
if ($session->is_authenticated()) {
$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)
{
$watermark = false;
}
elseif ($repository->findReceivedElementsByRecord($record, $user)->count() > 0)
{
$watermark = false;
}
}
if ($repository->findReceivedValidationElementsByRecord($record, $user)->count() > 0) {
$watermark = false;
} elseif ($repository->findReceivedElementsByRecord($record, $user)->count() > 0) {
$watermark = false;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
}
else
{
$collection = \collection::get_from_base_id($record->get_base_id());
switch ($collection->get_pub_wm())
{
default:
case 'none':
$watermark = false;
break;
case 'stamp':
$stamp = true;
break;
case 'wm':
$watermark = false;
break;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
} else {
$collection = \collection::get_from_base_id($record->get_base_id());
switch ($collection->get_pub_wm()) {
default:
case 'none':
$watermark = false;
break;
case 'stamp':
$stamp = true;
break;
case 'wm':
$watermark = false;
break;
}
}
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
}
)
->assert('sbas_id', '\d+')->assert('record_id', '\d+');
return $deliver_content($session, $record, $subdef, $watermark, $stamp, $app);
}
)
->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$app->error(function (\Exception $e)
{
if ($e instanceof \Exception_Session_NotAuthenticated)
{
$code = 403;
$message = 'Forbidden';
}
elseif ($e instanceof \Exception_NotAllowed)
{
$code = 403;
$message = 'Forbidden';
}
elseif ($e instanceof \Exception_NotFound)
{
$code = 404;
$message = 'Not Found';
}
else
{
$code = 404;
$message = 'Not Found';
}
$app->error(function (\Exception $e) {
if ($e instanceof \Exception_Session_NotAuthenticated) {
$code = 403;
$message = 'Forbidden';
} elseif ($e instanceof \Exception_NotAllowed) {
$code = 403;
$message = 'Forbidden';
} elseif ($e instanceof \Exception_NotFound) {
$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
* @link www.phraseanet.com
*/
return call_user_func(function()
{
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore();
return call_user_func(function() {
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore();
$app->before(function(Request $request)
{
$request->setRequestFormat(
$request->getFormat(
array_shift(
$request->getAcceptableContentTypes()
)
)
);
$app->before(function(Request $request) {
$request->setRequestFormat(
$request->getFormat(
array_shift(
$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
* @link www.phraseanet.com
*/
return call_user_func(function()
{
$app = new \Silex\Application();
return call_user_func(function() {
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore();
$app['Core'] = \bootstrap::getCore();
if (!\setup::is_installed())
{
$response = new \Symfony\Component\HttpFoundation\RedirectResponse('/setup/');
if ( ! \setup::is_installed()) {
$response = new \Symfony\Component\HttpFoundation\RedirectResponse('/setup/');
return $response->send();
}
return $response->send();
}
$app->get('/', function() use ($app)
{
$browser = \Browser::getInstance();
if ($browser->isMobile())
$app->get('/', function() use ($app) {
$browser = \Browser::getInstance();
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");
elseif ($browser->isNewGeneration())
$app->get('/robots.txt', function() use ($app) {
$appbox = \appbox::get_instance($app['Core']);
return $app->redirect("/login/?redirect=/prod");
else
$registry = $appbox->get_registry();
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)
{
$appbox = \appbox::get_instance($app['Core']);
$response = new Response($buffer, 200, array('Content-Type' => 'text/plain'));
$response->setCharset('UTF-8');
$registry = $appbox->get_registry();
return $response;
});
if ($registry->get('GV_allow_search_engine') === true)
{
$buffer = "User-Agent: *\n"
. "Allow: /\n";
}
else
{
$buffer = "User-Agent: *\n"
. "Disallow: /\n";
}
$app->mount('/feeds/', new Controller\RSSFeeds());
$response = new Response($buffer, 200, array('Content-Type' => 'text/plain'));
$response->setCharset('UTF-8');
return $response;
});
$app->mount('/feeds/', new Controller\RSSFeeds());
return $app;
}
return $app;
}
);

View File

@@ -22,72 +22,59 @@ use Alchemy\Phrasea\Controller\Utils as ControllerUtils;
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
return call_user_func(function()
{
$app = new \Silex\Application();
return call_user_func(function() {
$app = new \Silex\Application();
$app['Core'] = \bootstrap::getCore();
$app['Core'] = \bootstrap::getCore();
$app['install'] = false;
$app['upgrade'] = false;
$app['install'] = false;
$app['upgrade'] = false;
$app->before(function($a) use ($app)
{
if (\setup::is_installed())
{
$appbox = \appbox::get_instance($app['Core']);
$app->before(function($a) use ($app) {
if (\setup::is_installed()) {
$appbox = \appbox::get_instance($app['Core']);
if (!$appbox->need_major_upgrade())
{
throw new \Exception_Setup_PhraseaAlreadyInstalled();
}
if ( ! $appbox->need_major_upgrade()) {
throw new \Exception_Setup_PhraseaAlreadyInstalled();
}
$app['upgrade'] = true;
}
elseif (\setup::needUpgradeConfigurationFile())
{
$connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
$configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
$app['upgrade'] = true;
} elseif (\setup::needUpgradeConfigurationFile()) {
$connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
$configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
$configuration = \Alchemy\Phrasea\Core\Configuration::build();
$configuration->upgradeFromOldConf($configInc, $connexionInc);
$configuration = \Alchemy\Phrasea\Core\Configuration::build();
$configuration->upgradeFromOldConf($configInc, $connexionInc);
$app['install'] = true;
}
else
{
$app['install'] = true;
}
$app['install'] = true;
} else {
$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
{
public function isServer()
{
return false;
}
public function get($key)
{
if (!$this->contains($key))
public function isServer()
{
throw new Exception('Unable to retrieve the value');
return false;
}
return $this->fetch($key);
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
public function get($key)
{
$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
{
public function isServer()
{
return false;
}
public function get($id)
{
if (!$this->contains($id))
public function isServer()
{
throw new Exception(sprintf('Unable to find key %s', $id));
return false;
}
return $this->fetch($id);
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
public function get($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
{
public function isServer();
public function isServer();
public function get($key);
public function deleteMulti(array $array_keys);
public function get($key);
public function deleteMulti(array $array_keys);
}

View File

@@ -22,100 +22,92 @@ use \Alchemy\Phrasea\Core\Service\Builder,
*/
class Manager
{
/**
*
* @var \SplFileObject
*/
protected $cacheFile;
protected $core;
/**
*
* @var \SplFileObject
*/
protected $cacheFile;
protected $core;
/**
*
* @var \Alchemy\Phrasea\Core\Configuration\Parser
*/
protected $parser;
/**
*
* @var \Alchemy\Phrasea\Core\Configuration\Parser
*/
protected $parser;
/**
*
* @var array
*/
protected $registry = array();
/**
*
* @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)
public function __construct(Core $core, \SplFileObject $file)
{
$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(), '');
return $this;
}
public function get($cacheKey, $service_name)
{
try
protected function exists($name)
{
$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;
return isset($this->registry[$name]);
}
if ($this->hasChange($cacheKey, $service_name))
public function flushAll()
{
$service->getDriver()->flushAll();
if ($write)
{
$this->registry[$cacheKey] = $service_name;
$this->save($cacheKey, $service_name);
}
foreach ($this->registry as $cacheKey => $service_name) {
$this->get($cacheKey, $service_name)->getDriver()->flushAll();
}
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)
{
return $this->exists($name) ? $this->registry[$name] !== $driver : true;
}
if ($this->hasChange($cacheKey, $service_name)) {
$service->getDriver()->flushAll();
if ($write) {
$this->registry[$cacheKey] = $service_name;
$this->save($cacheKey, $service_name);
}
}
protected function save($name, $driver)
{
$date = new \DateTime();
return $service;
}
$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);
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
{
public function isServer()
{
return true;
}
public function get($key)
{
if (!$this->contains($key))
public function isServer()
{
throw new Exception('Unable to retrieve the value');
return true;
}
return $this->fetch($key);
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
public function get($key)
{
$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
{
/**
* @var \Redis
*/
private $_redis;
/**
* @var \Redis
*/
private $_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)
/**
* Sets the redis instance to use.
*
* @param Redis $memcache
*/
public function setRedis(\Redis $redis)
{
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');
$this->_redis = $redis;
}
return $this->fetch($key);
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
/**
* Gets the memcache instance used by the cache.
*
* @return Memcache
*/
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
{
public function isServer()
{
return false;
}
public function get($key)
{
if (!$this->contains($key))
public function isServer()
{
throw new Exception('Unable to retrieve the value');
return false;
}
return $this->fetch($key);
}
public function deleteMulti(array $array_keys)
{
foreach ($array_keys as $id)
public function get($key)
{
$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
{
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)
{
$Core = $app['Core'];
$user = $Core->getAuthenticatedUser();
$controllers->post('/{sbas_id}/', function(Application $app, $sbas_id) {
$Core = $app['Core'];
$user = $Core->getAuthenticatedUser();
$request = $app['request'];
$request = $app['request'];
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
{
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 ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct')) {
throw new \Exception_Forbidden('You are not allowed to access this zone');
}
if ($request->get('newfield'))
{
$field = \databox_field::create($databox, $request->get('newfield'));
$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')) {
$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')))
{
foreach ($request->get('todelete_ids') as $id)
{
try
{
$field = \databox_field::get_instance($databox, $id);
$field->delete();
}
catch (\Exception $e)
{
if ($error)
$databox->get_connection()->rollBack();
else
$databox->get_connection()->commit();
}
}
}
}
catch (\Exception $e)
{
$error = true;
}
if ($error)
$databox->get_connection()->rollBack();
else
$databox->get_connection()->commit();
return new RedirectResponse('/admin/description/' . $sbas_id . '/');
return new RedirectResponse('/admin/description/' . $sbas_id . '/');
})->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'];
$user = $Core->getAuthenticatedUser();
$Core = $app['Core'];
$user = $Core->getAuthenticatedUser();
$request = $app['request'];
$request = $app['request'];
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
{
throw new \Exception_Forbidden('You are not allowed to access this zone');
}
if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct')) {
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 = \databox::get_instance((int) $sbas_id);
$fields = $databox->get_meta_structure();
$available_fields = \databox::get_available_metadatas();
$available_dc_fields = $databox->get_available_dcfields();
$params = array(
'databox' => $databox,
'fields' => $fields,
'available_fields' => $available_fields,
'available_dc_fields' => $available_dc_fields,
'vocabularies' => \Alchemy\Phrasea\Vocabulary\Controller::getAvailable(),
);
$params = array(
'databox' => $databox,
'fields' => $fields,
'available_fields' => $available_fields,
'available_dc_fields' => $available_dc_fields,
'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+');
return $controllers;
}
return $controllers;
}
}

View File

@@ -28,56 +28,53 @@ use Silex\ControllerCollection;
class Fields implements ControllerProviderInterface
{
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
$controllers = new ControllerCollection();
$controllers = new ControllerCollection();
$controllers->get('/checkmulti/', function() use ($app, $appbox)
{
$request = $app['request'];
$controllers->get('/checkmulti/', function() use ($app, $appbox) {
$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(
'result' => ($multi === $metadata->is_multi())
, 'is_multi' => $metadata->is_multi()
);
$datas = array(
'result' => ($multi === $metadata->is_multi())
, 'is_multi' => $metadata->is_multi()
);
$Serializer = $app['Core']['Serializer'];
$Serializer = $app['Core']['Serializer'];
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->get('/checkreadonly/', function() use ($app, $appbox)
{
$request = $app['request'];
$readonly = ($request->get('readonly') === 'true');
$controllers->get('/checkreadonly/', function() use ($app, $appbox) {
$request = $app['request'];
$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(
'result' => ($readonly === $metadata->is_readonly())
, 'is_readonly' => $metadata->is_readonly()
);
$datas = array(
'result' => ($readonly === $metadata->is_readonly())
, 'is_readonly' => $metadata->is_readonly()
);
$Serializer = $app['Core']['Serializer'];
$Serializer = $app['Core']['Serializer'];
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')
);
});
return $controllers;
}
return $controllers;
}
}

View File

@@ -28,178 +28,153 @@ use Silex\ControllerCollection;
class Publications implements ControllerProviderInterface
{
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
$session = $appbox->get_session();
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
$session = $appbox->get_session();
$controllers = new ControllerCollection();
$controllers = new ControllerCollection();
$controllers->get('/list/', function() use ($app, $appbox)
{
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$feeds = \Feed_Collection::load_all($appbox, $user);
$controllers->get('/list/', function() use ($app, $appbox) {
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$feeds = \Feed_Collection::load_all($appbox, $user);
$template = 'admin/publications/list.html';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$template = 'admin/publications/list.html';
/* @var $twig \Twig_Environment */
$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);
$request = $app['request'];
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
$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')
$feed->set_public(true);
elseif ($request->get('base_id'))
$feed->set_collection(\collection::get_from_base_id($request->get('base_id')));
if ($request->get('public') == '1')
$feed->set_public(true);
elseif ($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)
{
$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);
$controllers->get('/feed/{id}/', function($id) use ($app, $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);
/* @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}/removepublisher/', function($id) use ($app, $appbox)
{
try
{
$request = $app['request'];
$controllers->post('/feed/{id}/update/', function($id) use ($app, $appbox) {
$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();
}
$user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
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+');
$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+');
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
{
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'];
$appbox = \appbox::get_instance($app['Core']);
$user = $Core->getAuthenticatedUser();
$Core = $app['Core'];
$appbox = \appbox::get_instance($app['Core']);
$user = $Core->getAuthenticatedUser();
\User_Adapter::updateClientInfos(3);
\User_Adapter::updateClientInfos(3);
$section = $request->get('section', false);
$section = $request->get('section', false);
$available = array(
'connected'
, 'registrations'
, 'taskmanager'
, 'base'
, 'bases'
, 'collection'
, 'user'
, 'users'
);
$available = array(
'connected'
, 'registrations'
, 'taskmanager'
, 'base'
, 'bases'
, 'collection'
, 'user'
, 'users'
);
$feature = 'connected';
$featured = false;
$position = explode(':', $section);
if (count($position) > 0)
{
if (in_array($position[0], $available))
{
$feature = $position[0];
if (isset($position[1]))
$featured = $position[1];
$feature = 'connected';
$featured = false;
$position = explode(':', $section);
if (count($position) > 0) {
if (in_array($position[0], $available)) {
$feature = $position[0];
if (isset($position[1]))
$featured = $position[1];
}
}
}
$databoxes = $off_databoxes = array();
foreach ($appbox->get_databoxes() as $databox)
{
try
{
if (!$user->ACL()->has_access_to_sbas($databox->get_sbas_id()))
continue;
$databoxes = $off_databoxes = array();
foreach ($appbox->get_databoxes() as $databox) {
try {
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(
'module' => 'admin'
, 'events' => \eventsmanager_broker::getInstance($appbox, $Core)
, 'module_name' => 'Admin'
, 'notice' => $request->get("notice")
, 'feature' => $feature
, 'featured' => $featured
, 'databoxes' => $databoxes
, 'off_databoxes' => $off_databoxes
, 'tree' => \module_admin::getTree($section)
))
);
return new Response($twig->render('admin/index.html.twig', array(
'module' => 'admin'
, 'events' => \eventsmanager_broker::getInstance($appbox, $Core)
, 'module_name' => 'Admin'
, 'notice' => $request->get("notice")
, 'feature' => $feature
, 'featured' => $featured
, 'databoxes' => $databoxes
, 'off_databoxes' => $off_databoxes
, 'tree' => \module_admin::getTree($section)
))
);
});
return $controllers;
}
return $controllers;
}
}

View File

@@ -29,109 +29,95 @@ use Silex\ControllerCollection;
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)
{
$databox = \databox::get_instance((int) $sbas_id);
$controllers->get('/{sbas_id}/', function(Application $app, $sbas_id) {
$databox = \databox::get_instance((int) $sbas_id);
return new response($app['Core']->getTwig()->render(
'admin/subdefs.twig', array(
'databox' => $databox,
'subdefs' => $databox->get_subdef_structure()
)
)
);
return new response($app['Core']->getTwig()->render(
'admin/subdefs.twig', array(
'databox' => $databox,
'subdefs' => $databox->get_subdef_structure()
)
)
);
})->assert('sbas_id', '\d+');
$controllers->post('/{sbas_id}/', function(Application $app, Request $request, $sbas_id)
{
$delete_subdef = $request->get('delete_subdef');
$toadd_subdef = $request->get('add_subdef');
$Parmsubdefs = $request->get('subdefs', array());
$controllers->post('/{sbas_id}/', function(Application $app, Request $request, $sbas_id) {
$delete_subdef = $request->get('delete_subdef');
$toadd_subdef = $request->get('add_subdef');
$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);
foreach ($add_subdef as $k => $v)
{
if (!isset($toadd_subdef[$k]) || trim($toadd_subdef[$k]) === '')
unset($add_subdef[$k]);
else
$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);
$add_subdef = array('class' => null, 'name' => null, 'group' => null);
foreach ($add_subdef as $k => $v) {
if ( ! isset($toadd_subdef[$k]) || trim($toadd_subdef[$k]) === '')
unset($add_subdef[$k]);
else
$add_subdef[$k] = $toadd_subdef[$k];
}
}
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+');
return $controllers;
}
return $controllers;
}
}

View File

@@ -30,420 +30,384 @@ use Alchemy\Phrasea\Helper\User as UserHelper;
class Users implements ControllerProviderInterface
{
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
$controllers = new ControllerCollection();
$controllers = new ControllerCollection();
$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
{
$controllers->post('/rights/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
$rights->apply_rights();
if ($app['request']->get('template'))
{
$rights->apply_template();
$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();
}
$rights->apply_infos();
$datas = array('error' => false);
}
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()
return new Response(
$core->getSerializer()->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
}
$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']);
$controllers->post('/delete/', function(Application $app) {
$module = new UserHelper\Edit($app['Core'], $app['request']);
$module->delete_users();
$users->apply_template();
return new RedirectResponse('/admin/users/search/');
return $app->redirect('/admin/users/search/');
}
);
);
$controllers->get('/typeahead/search/', function(Application $app) use ($appbox)
{
$request = $app['request'];
$controllers->post('/rights/apply/', function(Application $app) {
$datas = array('error' => true);
$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 = $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();
$rights->apply_infos();
$datas = array('error' => false);
} catch (\Exception $e) {
$datas['message'] = $e->getMessage();
}
$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();
$Serializer = $app['Core']['Serializer'];
$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()
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
}
}
);
$Serializer = $app['Core']['Serializer'];
$controllers->post('/rights/quotas/', function(Application $app) {
$rights = new UserHelper\Edit($app['Core'], $app['request']);
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-type' => 'application/json')
);
$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) {
$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);
try
{
$datas = array('error' => false, 'message' => '', 'data' => null);
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'];
$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');
$user_query = new \User_Query($appbox, $app['Core']);
$datas['data'] = $user->get_id();
}
catch (\Exception $e)
{
$datas['error'] = true;
$datas['message'] = $e->getMessage();
}
$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;
$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
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Controller;
/**
*
* @package

View File

@@ -31,538 +31,481 @@ use Alchemy\Phrasea\RouteProcessor\Basket as BasketRoute,
class Basket implements ControllerProviderInterface
{
public function connect(Application $app)
{
$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);
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$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)
{
$message = _('Basket has been archived');
}
else
{
$message = _('Basket has been unarchived');
}
$data = array(
'success' => true
, 'archive' => $archive_status
, 'message' => $message
);
/* @var $request \Symfony\Component\HttpFoundation\Request */
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'));
}
else
{
return new RedirectResponse('/');
}
})->assert('basket_id', '\d+');
$Basket = new \Entities\Basket();
/**
* Add a BasketElement to a basket
*/
$controllers->post(
'/{basket_id}/addElements/'
, function(Application $app, Request $request, $basket_id)
{
$em = $app['Core']->getEntityManager();
$Basket->setName($request->get('name', ''));
$Basket->setOwner($app['Core']->getAuthenticatedUser());
$Basket->setDescription($request->get('desc'));
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), true);
$em->persist($Basket);
$user = $app['Core']->getAuthenticatedUser();
/* @var $user \User_Adapter */
$n = 0;
$n = 0;
foreach (explode(';', $request->get('lst')) as $sbas_rec) {
$sbas_rec = explode('_', $sbas_rec);
foreach (explode(';', $request->get('lst')) as $sbas_rec)
{
$sbas_rec = explode('_', $sbas_rec);
if (count($sbas_rec) !== 2)
continue;
if (count($sbas_rec) !== 2)
continue;
$record = new \record_adapter($sbas_rec[0], $sbas_rec[1]);
$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())
&& !$user->ACL()->has_hd_grant($record)
&& !$user->ACL()->has_preview_grant($record))
{
continue;
}
if ($basket->hasRecord($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');
$basket_element = new \Entities\BasketElement();
$basket_element->setRecord($record);
$basket_element->setBasket($basket);
$em->persist($basket_element);
$basket->addBasketElement($basket_element);
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();
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;
$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+');
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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$appbox = \appbox::get_instance($app['Core']);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$appbox = \appbox::get_instance($app['Core']);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$app['require_connection'] = $app->protect(function(\Bridge_Account $account) use ($app)
{
$app['current_account'] = function() use ($account)
{
$app['require_connection'] = $app->protect(function(\Bridge_Account $account) use ($app) {
$app['current_account'] = function() use ($account) {
return $account;
};
};
if (!$account->get_api()->get_connector()->is_configured())
throw new \Bridge_Exception_ApiConnectorNotConfigured("Bridge API Connector is not configured");
if (!$account->get_api()->get_connector()->is_connected())
throw new \Bridge_Exception_ApiConnectorNotConnected("Bridge API Connector is not connected");
if ( ! $account->get_api()->get_connector()->is_configured())
throw new \Bridge_Exception_ApiConnectorNotConfigured("Bridge API Connector is not configured");
if ( ! $account->get_api()->get_connector()->is_connected())
throw new \Bridge_Exception_ApiConnectorNotConnected("Bridge API Connector is not connected");
return;
return;
});
$controllers->post('/manager/'
, function(Application $app) use ($twig)
{
$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
{
$controllers->post('/manager/'
, function(Application $app) use ($twig) {
$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);
$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(
'route' => $route
, 'account' => $account
, 'error_message' => _('Request contains invalid datas')
, 'constraint_errors' => $errors
'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']);
$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);
$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;
}
$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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->post('/', function(Application $app, Request $request)
{
$handler = new RecordHelper\Edit($app['Core'], $request);
$controllers->post('/', function(Application $app, Request $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 */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$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)
{
$datas = array('success' => false, 'message' => '', 'results' => array());
$controllers->get('/vocabulary/{vocabulary}/', function(Application $app, Request $request, $vocabulary) {
$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
{
$VC = \Alchemy\Phrasea\Vocabulary\Controller::get($vocabulary);
$databox = \databox::get_instance($sbas_id);
}
catch (\Exception $e)
{
$datas['message'] = _('Vocabulary not found');
try {
$VC = \Alchemy\Phrasea\Vocabulary\Controller::get($vocabulary);
$databox = \databox::get_instance($sbas_id);
} 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)
{
/* @var $Term \Alchemy\Phrasea\Vocabulary\Term */
$list[] = array(
'id' => $Term->getId(),
'context' => $Term->getContext(),
'value' => $Term->getValue(),
);
}
foreach ($results as $Term) {
/* @var $Term \Alchemy\Phrasea\Vocabulary\Term */
$list[] = array(
'id' => $Term->getId(),
'context' => $Term->getContext(),
'value' => $Term->getValue(),
);
}
$datas['success'] = true;
$datas['results'] = $list;
$datas['success'] = true;
$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)
{
$editing = new RecordHelper\Edit($app['Core'], $app['request']);
$editing->execute($request);
$controllers->post('/apply/', function(Application $app, Request $request) {
$editing = new RecordHelper\Edit($app['Core'], $app['request']);
$editing->execute($request);
$template = 'prod/actions/edit_default.twig';
$template = 'prod/actions/edit_default.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$appbox = \appbox::get_instance($app['Core']);
public function connect(Application $app)
{
$controllers = new ControllerCollection();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$appbox = \appbox::get_instance($app['Core']);
/**
* I got a selection of docs, which publications are available forthese docs ?
*/
$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
{
/**
* I got a selection of docs, which publications are available forthese docs ?
*/
$controllers->post('/requestavailable/', function(Application $app, Request $request) use ($appbox, $twig) {
$user = $app["Core"]->getAuthenticatedUser();
$feed = new \Feed_Adapter($appbox, $request->get('feed_id'));
$publisher = \Feed_Publisher_Adapter::getPublisher($appbox, $feed, $user);
$feeds = \Feed_Collection::load_all($appbox, $user);
$publishing = new RecordHelper\Feed($app['Core'], $request);
$title = $request->get('title');
$subtitle = $request->get('subtitle');
$author_name = $request->get('author_name');
$author_mail = $request->get('author_mail');
$datas = $twig->render('prod/actions/publish/publish.html', array('publishing' => $publishing, 'feeds' => $feeds));
$entry = \Feed_Entry_Adapter::create($appbox, $feed, $publisher, $title, $subtitle, $author_name, $author_mail);
$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')
);
return new Response($datas);
});
$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())
{
throw new \Exception_UnauthorizedAction();
}
$publishing = new RecordHelper\Feed($app['Core'], $app['request']);
$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);
})->assert('id', '\d+');
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('Content-Type' => 'application/json')
);
});
$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();
$controllers->get('/entry/{id}/edit/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
$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();
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');
$feeds = \Feed_Collection::load_all($appbox, $user);
$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_title($title)
->set_subtitle($subtitle);
$items = explode(';', $request->get('sorted_lst'));
$items = explode(';', $request->get('sorted_lst'));
foreach ($items as $item_sort)
{
$item_sort_datas = explode('_', $item_sort);
if (count($item_sort_datas) != 2)
{
continue;
}
foreach ($items as $item_sort) {
$item_sort_datas = explode('_', $item_sort);
if (count($item_sort_datas) != 2) {
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);
}
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();
}
$Serializer = $app['Core']['Serializer'];
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')
);
})->assert('id', '\d+');
$controllers->post('/entry/{id}/delete/', function(Application $app, Request $request, $id) use ($appbox, $twig)
{
$datas = array('error' => true, 'message' => '');
try
{
$appbox->get_connection()->beginTransaction();
$controllers->post('/entry/{id}/delete/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
$datas = array('error' => true, 'message' => '');
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()
&& $entry->get_feed()->is_owner($user) === false)
{
throw new \Exception_UnauthorizedAction(_('Action Forbidden : You are not the publisher'));
if ($entry->get_publisher()->get_user()->get_id() !== $user->get_id()
&& $entry->get_feed()->is_owner($user) === false) {
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();
$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();
}
$Serializer = $app['Core']['Serializer'];
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')
);
})->assert('id', '\d+');
//$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)
{
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page > 0 ? $page : 1;
$controllers->get('/', function(Application $app, Request $request) use ($appbox, $twig) {
$request = $app['request'];
$page = (int) $request->get('page');
$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'
, array(
'feeds' => $feeds
, 'feed' => $feeds->get_aggregate()
, 'page' => $page
)
);
$datas = $twig->render('prod/feeds/feeds.html'
, array(
'feeds' => $feeds
, 'feed' => $feeds->get_aggregate()
, 'page' => $page
)
);
return new Response($datas);
return new Response($datas);
});
$controllers->get('/feed/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig)
{
$page = (int) $request->get('page');
$page = $page > 0 ? $page : 1;
$controllers->get('/feed/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
$page = (int) $request->get('page');
$page = $page > 0 ? $page : 1;
$user = $app["Core"]->getAuthenticatedUser();
$user = $app["Core"]->getAuthenticatedUser();
$feed = \Feed_Adapter::load_with_user($appbox, $user, $id);
$feeds = \Feed_Collection::load_all($appbox, $user);
$feed = \Feed_Adapter::load_with_user($appbox, $user, $id);
$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+');
$controllers->get('/subscribe/aggregated/', function(Application $app, Request $request) use ( $appbox, $twig)
{
$renew = ($request->get('renew') === 'true');
$controllers->get('/subscribe/aggregated/', function(Application $app, Request $request) use ( $appbox, $twig) {
$renew = ($request->get('renew') === 'true');
$user = $app["Core"]->getAuthenticatedUser();
$user = $app["Core"]->getAuthenticatedUser();
$feeds = \Feed_Collection::load_all($appbox, $user);
$registry = $appbox->get_registry();
$feeds = \Feed_Collection::load_all($appbox, $user);
$registry = $appbox->get_registry();
$output = array(
'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>
$output = array(
'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>
<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(
$Serializer->serialize($output, 'json')
, 200
, array('Content-Type' => 'application/json')
);
return new Response(
$Serializer->serialize($output, 'json')
, 200
, array('Content-Type' => 'application/json')
);
});
$controllers->get('/subscribe/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig)
{
$renew = ($request->get('renew') === 'true');
$user = $app["Core"]->getAuthenticatedUser();
$feed = \Feed_Adapter::load_with_user($appbox, $user, $id);
$registry = $appbox->get_registry();
$controllers->get('/subscribe/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) {
$renew = ($request->get('renew') === 'true');
$user = $app["Core"]->getAuthenticatedUser();
$feed = \Feed_Adapter::load_with_user($appbox, $user, $id);
$registry = $appbox->get_registry();
$output = array(
'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>
$output = array(
'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>
<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(
$Serializer->serialize($output, 'json')
, 200
, array('Content-Type' => 'application/json')
);
return new Response(
$Serializer->serialize($output, 'json')
, 200
, array('Content-Type' => 'application/json')
);
})->assert('id', '\d+');
return $controllers;
}
return $controllers;
}
}

View File

@@ -29,85 +29,83 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class Language implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controller = new ControllerCollection();
public function connect(Application $app)
{
$controller = new ControllerCollection();
$controller->get("/", function(Application $app)
{
$registry = $app["Core"]->getRegistry();
$controller->get("/", function(Application $app) {
$registry = $app["Core"]->getRegistry();
$out = array();
$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['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique');
$out['serverName'] = $registry->get('GV_ServerName');
$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['hideMessage'] = _('phraseanet::Ne plus afficher ce message');
$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['cancel'] = _('boutton::annuler');
$out['deleteTitle'] = _('boutton::supprimer');
$out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\'');
$out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?');
$out['loading'] = _('phraseanet::chargement');
$out['valider'] = _('boutton::valider');
$out['annuler'] = _('boutton::annuler');
$out['create'] = _('boutton::creer');
$out['rechercher'] = _('boutton::rechercher');
$out['renewRss'] = _('boutton::renouveller');
$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['needTitle'] = _('Vous devez donner un titre');
$out['newPreset'] = _('Nouveau modele');
$out['fermer'] = _('boutton::fermer');
$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['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['advsearch_title'] = _('phraseanet::recherche avancee');
$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['error'] = _('phraseanet:: Erreur');
$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['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes');
$out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes');
$out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant');
$out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant');
$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['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['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['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, 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['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['sureToRemoveList'] = _('Are you sure you want to delete this list ?');
$out['newListName'] = _('New list name ?');
$out['listNameCannotBeEmpty'] = _('List name can not be empty');
$out['FeedBackName'] = _('Name');
$out['FeedBackMessage'] = _('Message');
$out['FeedBackDuration'] = _('Time for feedback (days)');
$out['send'] = _('Send');
$out['Recept'] = _('Accuse de reception');
$out['nFieldsChanged'] = _('%d fields have been updated');
$out['FeedBackNoUsersSelected'] = _('No users selected');
$out = array();
$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['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique');
$out['serverName'] = $registry->get('GV_ServerName');
$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['hideMessage'] = _('phraseanet::Ne plus afficher ce message');
$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['cancel'] = _('boutton::annuler');
$out['deleteTitle'] = _('boutton::supprimer');
$out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\'');
$out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?');
$out['loading'] = _('phraseanet::chargement');
$out['valider'] = _('boutton::valider');
$out['annuler'] = _('boutton::annuler');
$out['create'] = _('boutton::creer');
$out['rechercher'] = _('boutton::rechercher');
$out['renewRss'] = _('boutton::renouveller');
$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['needTitle'] = _('Vous devez donner un titre');
$out['newPreset'] = _('Nouveau modele');
$out['fermer'] = _('boutton::fermer');
$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['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['advsearch_title'] = _('phraseanet::recherche avancee');
$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['error'] = _('phraseanet:: Erreur');
$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['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes');
$out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes');
$out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant');
$out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant');
$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['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['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['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, 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['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['sureToRemoveList'] = _('Are you sure you want to delete this list ?');
$out['newListName'] = _('New list name ?');
$out['listNameCannotBeEmpty'] = _('List name can not be empty');
$out['FeedBackName'] = _('Name');
$out['FeedBackMessage'] = _('Message');
$out['FeedBackDuration'] = _('Time for feedback (days)');
$out['send'] = _('Send');
$out['Recept'] = _('Accuse de reception');
$out['nFieldsChanged'] = _('%d fields have been updated');
$out['FeedBackNoUsersSelected'] = _('No users selected');
$Serializer = $app['Core']['Serializer'];
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize($out, 'json')
, 200
, array('Content-Type' => 'application/json')
);
return new Response(
$Serializer->serialize($out, 'json')
, 200
, 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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->post('/', function(Application $app, Request $request)
{
$request = $app['request'];
$move = new RecordHelper\MoveCollection($app['Core'], $app['request']);
$move->propose();
$controllers->post('/', function(Application $app, Request $request) {
$request = $app['request'];
$move = new RecordHelper\MoveCollection($app['Core'], $app['request']);
$move->propose();
$template = 'prod/actions/collection_default.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$template = 'prod/actions/collection_default.twig';
/* @var $twig \Twig_Environment */
$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)
{
$request = $app['request'];
$move = new RecordHelper\MoveCollection($app['Core'], $app['request']);
$move->execute($request);
$template = 'prod/actions/collection_submit.twig';
$controllers->post('/apply/', function(Application $app) {
$request = $app['request'];
$move = new RecordHelper\MoveCollection($app['Core'], $app['request']);
$move->execute($request);
$template = 'prod/actions/collection_submit.twig';
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/', function(Application $app, Request $request)
{
$template_name = $request->get('template');
$controllers->get('/', function(Application $app, Request $request) {
$template_name = $request->get('template');
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name))
{
throw new \Exception_BadRequest('Wrong template name : ' . $template_name);
}
if ( ! preg_match('/^[a-zA-Z0-9-_]+$/', $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))
{
throw new \Exception_NotFound('Template does not exists : ' . $template_path);
}
if ( ! file_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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->post('/', function(Application $app)
{
$printer = new RecordHelper\Printer($app['Core'], $app['request']);
$controllers->post('/', function(Application $app) {
$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 */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$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)
{
$printer = new RecordHelper\Printer($app['Core'], $app['request']);
$controllers->post('/print.pdf', function(Application $app) {
$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)
{
$session->get_logger($record->get_databox())
foreach ($printer->get_elements() as $record) {
$session->get_logger($record->get_databox())
->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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->match('/', function(Application $app, Request $request)
{
$controllers->match('/', function(Application $app, Request $request) {
$appbox = \appbox::get_instance($app['Core']);
$registry = $appbox->get_registry();
$appbox = \appbox::get_instance($app['Core']);
$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 */
if ($user->ACL()->has_right('modifyrecord'))
{
$options->set_business_fields(array());
/* @var $user \User_Adapter */
if ($user->ACL()->has_right('modifyrecord')) {
$options->set_business_fields(array());
$BF = array();
$BF = array();
foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection)
{
if (count($bas) === 0 || in_array($collection->get_base_id(), $bas))
{
$BF[] = $collection->get_base_id();
}
}
$options->set_business_fields($BF);
}
else
{
$options->set_business_fields(array());
}
foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) {
if (count($bas) === 0 || in_array($collection->get_base_id(), $bas)) {
$BF[] = $collection->get_base_id();
}
}
$options->set_business_fields($BF);
} else {
$options->set_business_fields(array());
}
$status = is_array($request->get('status')) ? $request->get('status') : array();
$fields = is_array($request->get('fields')) ? $request->get('fields') : array();
$status = is_array($request->get('status')) ? $request->get('status') : array();
$fields = is_array($request->get('fields')) ? $request->get('fields') : array();
$options->set_fields($fields);
$options->set_status($status);
$options->set_bases($bas, $user->ACL());
$options->set_fields($fields);
$options->set_status($status);
$options->set_bases($bas, $user->ACL());
$options->set_search_type($request->get('search_type'));
$options->set_record_type($request->get('recordtype'));
$options->set_min_date($request->get('datemin'));
$options->set_max_date($request->get('datemax'));
$options->set_date_fields(explode('|', $request->get('datefield')));
$options->set_sort($request->get('sort'), $request->get('ord', PHRASEA_ORDER_DESC));
$options->set_use_stemming($request->get('stemme'));
$options->set_search_type($request->get('search_type'));
$options->set_record_type($request->get('recordtype'));
$options->set_min_date($request->get('datemin'));
$options->set_max_date($request->get('datemax'));
$options->set_date_fields(explode('|', $request->get('datefield')));
$options->set_sort($request->get('sort'), $request->get('ord', PHRASEA_ORDER_DESC));
$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->set_options($options);
$search_engine = new \searchEngine_adapter($registry);
$search_engine->set_options($options);
$page = (int) $request->get('pag');
$page = (int) $request->get('pag');
if ($page < 1)
{
$search_engine->set_is_first_page(true);
$search_engine->reset_cache();
$page = 1;
}
if ($page < 1) {
$search_engine->set_is_first_page(true);
$search_engine->reset_cache();
$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);
$d2bottom = $page;
$d2top = ($npages - $page);
$d2bottom = $page;
if (min($d2top, $d2bottom) < 4)
{
if ($d2bottom < 4)
{
for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i ++ )
{
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
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
}
if ($npages > 4)
$string .= "<a onclick='gotopage(" . ($npages) . ");return false;'>&gt;&gt;</a>";
}
else
{
$start = $npages - 4;
if (($start) > 0)
$string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
else
$start = 1;
for ($i = ($start); $i <= $npages; $i ++ )
{
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
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
}
}
}
else
{
$string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
if (min($d2top, $d2bottom) < 4) {
if ($d2bottom < 4) {
for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i ++ ) {
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
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
}
if ($npages > 4)
$string .= "<a onclick='gotopage(" . ($npages) . ");return false;'>&gt;&gt;</a>";
}
else {
$start = $npages - 4;
if (($start) > 0)
$string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
else
$start = 1;
for ($i = ($start); $i <= $npages; $i ++ ) {
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
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
}
}
}
else {
$string .= "<a onclick='gotopage(1);return false;'>&lt;&lt;</a>";
for ($i = ($page - 2); $i <= ($page + 2); $i ++ )
{
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
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</a>";
}
for ($i = ($page - 2); $i <= ($page + 2); $i ++ ) {
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
$string .= "<a onclick='gotopage(" . $i . ");return false;'>" . $i . "</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 .= "<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>';
$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())
{
$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());
}
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());
} else {
$explain .= sprintf(_('reponses:: %d Resultats'), $result->get_count_total_results());
}
$explain .= " </b></span>";
$explain .= '<br><div>' . $result->get_query_time() . ' s</div>dans index ' . $result->get_search_indexes();
$explain .= "</div>";
$explain .= " </b></span>";
$explain .= '<br><div>' . $result->get_query_time() . ' s</div>dans index ' . $result->get_search_indexes();
$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['navigation'] = $string;
$json['infos'] = $infoResult;
$json['navigation'] = $string;
$prop = null;
$prop = null;
if ($search_engine->is_first_page())
{
$propals = $result->get_suggestions();
if (count($propals) > 0)
{
foreach ($propals as $prop_array)
{
if ($prop_array['value'] !== $query && $prop_array['hits'] > $result->get_count_total_results())
{
$prop = $prop_array['value'];
break;
}
}
}
}
if ($search_engine->is_first_page()) {
$propals = $result->get_suggestions();
if (count($propals) > 0) {
foreach ($propals as $prop_array) {
if ($prop_array['value'] !== $query && $prop_array['hits'] > $result->get_count_total_results()) {
$prop = $prop_array['value'];
break;
}
}
}
}
$core = \bootstrap::getCore();
$twig = $core->getTwig();
$core = \bootstrap::getCore();
$twig = $core->getTwig();
if ($result->get_count_total_results() === 0)
{
$template = 'prod/results/help.twig';
}
else
{
if ($mod == 'thumbs')
{
$template = 'prod/results/answergrid.html';
}
else
{
$template = 'prod/results/answerlist.html';
}
}
if ($result->get_count_total_results() === 0) {
$template = 'prod/results/help.twig';
} else {
if ($mod == 'thumbs') {
$template = 'prod/results/answergrid.html';
} else {
$template = 'prod/results/answerlist.html';
}
}
$json['results'] = $twig->render($template, array(
'results' => $result,
'GV_social_tools' => $registry->get('GV_social_tools'),
'highlight' => $search_engine->get_query(),
'searchEngine' => $search_engine,
'suggestions' => $prop
)
);
$json['results'] = $twig->render($template, array(
'results' => $result,
'GV_social_tools' => $registry->get('GV_social_tools'),
'highlight' => $search_engine->get_query(),
'searchEngine' => $search_engine,
'suggestions' => $prop
)
);
$json['query'] = $query;
$json['phrasea_props'] = $proposals;
$json['total_answers'] = (int) $result->get_count_available_results();
$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['form'] = $form;
$json['query'] = $query;
$json['phrasea_props'] = $proposals;
$json['total_answers'] = (int) $result->get_count_available_results();
$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['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 $controllers;
}
return new Response($datas, 200, array('Content-Type' => 'application/json'));
});
return $controllers;
}
}

View File

@@ -31,118 +31,108 @@ use Alchemy\Phrasea\Helper;
class Root implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$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']);
$registry = $app['Core']->getRegistry();
$user = $app['Core']->getAuthenticatedUser();
$cssPath = $registry->get('GV_RootPath') . 'www/skins/prod/';
$appbox = \appbox::get_instance($app['Core']);
$registry = $app['Core']->getRegistry();
$user = $app['Core']->getAuthenticatedUser();
$cssPath = $registry->get('GV_RootPath') . 'www/skins/prod/';
$css = array();
$cssfile = false;
$css = array();
$cssfile = false;
$finder = new Finder();
$finder = new Finder();
$iterator = $finder
->directories()
->depth(0)
->filter(function(\SplFileInfo $fileinfo)
{
return ctype_xdigit($fileinfo->getBasename());
})
->in($cssPath);
$iterator = $finder
->directories()
->depth(0)
->filter(function(\SplFileInfo $fileinfo) {
return ctype_xdigit($fileinfo->getBasename());
})
->in($cssPath);
foreach ($iterator as $dir)
{
$baseName = $dir->getBaseName();
$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
);
foreach ($iterator as $dir) {
$baseName = $dir->getBaseName();
$css[$baseName] = $baseName;
}
}
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$cssfile = $user->getPrefs('css');
$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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/create/', function(Application $app)
{
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$controllers->get('/create/', function(Application $app) {
/* @var $twig \Twig_Environment */
$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)
{
/* @var $request \Symfony\Component\HttpFoundation\Request */
$em = $app['Core']->getEntityManager();
$controllers->post('/', function(Application $app, Request $request) {
/* @var $request \Symfony\Component\HttpFoundation\Request */
$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'))
{
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;
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');
}
$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);
}
$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
$system_file = new \system_file(
$app['Core']->getRegistry()
->get('GV_RootPath') . 'www/skins/icons/substitution/regroup_doc.png'
);
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();
$StoryWZ->setUser($user);
$StoryWZ->setRecord($Story);
if (count($sbas_rec) !== 2) {
continue;
}
$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(
'success' => true
, 'message' => _('Story created')
, 'WorkZone' => $StoryWZ->getId()
, 'story' => array(
'sbas_id' => $Story->get_sbas_id(),
'record_id' => $Story->get_record_id(),
)
, 'message' => sprintf(_('%d records added'), $n)
);
$datas = $app['Core']['Serializer']->serialize($data, 'json');
if ($request->getRequestFormat() == 'json') {
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
return new RedirectResponse(sprintf('/%d/', $StoryWZ->getId()));
}
});
$datas = $app['Core']['Serializer']->serialize($data, 'json');
$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;
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/');
}
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+');
$controllers->post(
'/{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)
{
$Story = new \record_adapter($sbas_id, $record_id);
$controllers->post(
'/{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) {
$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');
/* @var $user \User_Adapter */
/* @var $user \User_Adapter */
$Story->removeChild($record);
$Story->removeChild($record);
$data = array(
'success' => true
, 'message' => _('Record removed from story')
);
$data = array(
'success' => true
, 'message' => _('Record removed from story')
);
if ($request->getRequestFormat() == 'json')
{
if ($request->getRequestFormat() == 'json') {
$datas = $app['Core']['Serializer']->serialize($data, 'json');
return new Response($datas, 200, array('Content-type' => 'application/json'));
}
else
{
} else {
return new RedirectResponse('/');
}
})
}
})
->assert('sbas_id', '\d+')
->assert('record_id', '\d+')
->assert('child_sbas_id', '\d+')
->assert('child_record_id', '\d+');
/**
* Get the Basket reorder form
*/
$controllers->get(
'/{sbas_id}/{record_id}/reorder/'
, function(Application $app, $sbas_id, $record_id)
{
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
/**
* Get the Basket reorder form
*/
$controllers->get(
'/{sbas_id}/{record_id}/reorder/'
, function(Application $app, $sbas_id, $record_id) {
/* @var $em \Doctrine\ORM\EntityManager */
$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');
}
}
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'prod/Story/Reorder.html.twig'
, array('story' => $story)
)
);
})
return new Response(
$twig->render(
'prod/Story/Reorder.html.twig'
, array('story' => $story)
)
);
})
->assert('sbas_id', '\d+')
->assert('record_id', '\d+');
$controllers->post(
'/{sbas_id}/{record_id}/reorder/'
, function(Application $app, $sbas_id, $record_id)
{
$ret = array('success' => false, 'message' => _('An error occured'));
try
{
$controllers->post(
'/{sbas_id}/{record_id}/reorder/'
, function(Application $app, $sbas_id, $record_id) {
$ret = array('success' => false, 'message' => _('An error occured'));
try {
$user = $app['Core']->getAuthenticatedUser();
/* @var $user \User_Adapter */
$story = new \record_adapter($sbas_id, $record_id);
if (!$story->is_grouping())
{
throw new \Exception('This is not a story');
if ( ! $story->is_grouping()) {
throw new \Exception('This is not a story');
}
if (!$user->ACL()->has_right_on_base($story->get_base_id(), 'canmodifrecord'))
{
throw new ControllerException(_('You can not edit this story'));
if ( ! $user->ACL()->has_right_on_base($story->get_base_id(), 'canmodifrecord')) {
throw new ControllerException(_('You can not edit this story'));
}
$sql = 'UPDATE regroup SET ord = :ord
WHERE rid_parent = :parent_id AND rid_child = :children_id';
$stmt = $story->get_databox()->get_connection()->prepare($sql);
foreach ($app['request']->get('element') as $record_id => $ord)
{
$params = array(
':ord' => $ord,
':parent_id' => $story->get_record_id(),
':children_id' => $record_id
);
$stmt->execute($params);
foreach ($app['request']->get('element') as $record_id => $ord) {
$params = array(
':ord' => $ord,
':parent_id' => $story->get_record_id(),
':children_id' => $record_id
);
$stmt->execute($params);
}
$stmt->closeCursor();
$ret = array('success' => true, 'message' => _('Story updated'));
}
catch (ControllerException $e)
{
} catch (ControllerException $e) {
$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('record_id', '\d+');
return $controllers;
}
return $controllers;
}
}

View File

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

View File

@@ -36,287 +36,243 @@ class Tools implements ControllerProviderInterface
{
$controllers = new ControllerCollection();
$controllers->get('/', function(Application $app, Request $request)
{
$helper = new Helper\Record\Tools($app['Core'], $request);
$controllers->get('/', function(Application $app, Request $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;
$record = null;
$metadatasFirst = $metadatasSecond = array();
$metadatas = false;
$record = null;
$metadatasFirst = $metadatasSecond = array();
if (count($selection) == 1 && ! empty($binary))
{
try
{
$record = reset($selection);
$file = $record->get_subdef('document')->get_pathfile();
$cmd = $binary . ' -h ' . escapeshellarg($file);
if (count($selection) == 1 && ! empty($binary)) {
try {
$record = reset($selection);
$file = $record->get_subdef('document')->get_pathfile();
$cmd = $binary . ' -h ' . escapeshellarg($file);
$out = "";
exec($cmd, $out);
foreach ($out as $liout)
{
if (strpos($liout, '<tr><td>Directory') === false)
$metadatasFirst[] = $liout;
}
$out = "";
$cmd = $binary . ' -X -n -fast ' . escapeshellarg($file) . '';
exec($cmd, $out);
foreach ($out as $liout)
{
$metadatasSecond[] = htmlentities($liout);
}
$metadatas = true;
}
catch (\Exception $e)
{
$out = "";
exec($cmd, $out);
foreach ($out as $liout) {
if (strpos($liout, '<tr><td>Directory') === false)
$metadatasFirst[] = $liout;
}
$out = "";
$cmd = $binary . ' -X -n -fast ' . escapeshellarg($file) . '';
exec($cmd, $out);
foreach ($out as $liout) {
$metadatasSecond[] = htmlentities($liout);
}
$metadatas = true;
} catch (\Exception $e) {
}
}
}
}
$template = 'prod/actions/Tools/index.html.twig';
$template = 'prod/actions/Tools/index.html.twig';
$var = array(
'helper' => $helper,
'selection' => $selection,
'record' => $record,
'metadatas' => $metadatas,
'metadatasFirst' => $metadatasFirst,
'metadatasSecond' => $metadatasSecond
);
$var = array(
'helper' => $helper,
'selection' => $selection,
'record' => $record,
'metadatas' => $metadatas,
'metadatasFirst' => $metadatasFirst,
'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)
{
$return = array('success' => false, 'errorMessage' => '');
$controllers->post('/rotate/', function(Application $app, Request $request) {
$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)
{
try
{
$record->rotate_subdefs($rotation);
$return['success'] = true;
}
catch (\Exception $e)
{
$return['errorMessage'] = $e->getMessage();
}
}
foreach ($selection as $record) {
try {
$record->rotate_subdefs($rotation);
$return['success'] = true;
} 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)
{
$return = array('success' => true);
$controllers->post('/image/', function(Application $app, Request $request) {
$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')
{
foreach ($selection as $record)
{
try
{
$record->rebuild_subdefs();
}
catch (\Exception $e)
{
$return['success'] = false;
$return['message'] = _('an error occured');
}
}
}
if ($request->get('ForceThumbSubstit') == '1') {
foreach ($selection as $record) {
try {
$record->rebuild_subdefs();
} 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)
{
$success = false;
$errorMessage = "";
$fileName = null;
$controllers->post('/hddoc/', function(Application $app, Request $request) {
$success = false;
$errorMessage = "";
$fileName = null;
if ($file = $request->files->get('newHD'))
{
$fileName = $file->getClientOriginalName();
$size = $file->getClientSize();
if ($file = $request->files->get('newHD')) {
$fileName = $file->getClientOriginalName();
$size = $file->getClientSize();
if ($size && $fileName && $file->isValid())
{
if ($size && $fileName && $file->isValid()) {
try
{
$record = new \record_adapter(
$request->get('sbas_id')
, $request->get('record_id')
);
try {
$record = new \record_adapter(
$request->get('sbas_id')
, $request->get('record_id')
);
$record->substitute_subdef(
'document'
, new \system_file($file->getPathname())
);
$record->substitute_subdef(
'document'
, new \system_file($file->getPathname())
);
if ((int) $request->get('ccfilename') === 1)
{
$record->set_original_name($fileName);
}
if ((int) $request->get('ccfilename') === 1) {
$record->set_original_name($fileName);
}
$success = true;
}
catch (\Exception $e)
{
$errorMessage = $e->getMessage();
}
}
else
{
$errorMessage = _('file is not valid');
}
}
$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
, '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(
$template = 'prod/actions/Tools/iframeUpload.html.twig';
$var = array(
'success' => $success
, 'fileName' => $fileName
, '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
{
$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;
}
$controllers->post('/chgthumb/', function(Application $app, Request $request) {
$success = false;
$errorMessage = "";
$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)
{
$return = array('success' => false, 'message' => '');
if ($size && $fileName && $file->isValid()) {
try {
$rootPath = $app['Core']->getRegistry()->get('GV_RootPath');
$tmpFile = $rootPath . 'tmp/' . $fileName;
rename($file->getPathname(), $tmpFile);
try
{
$record = new \record_adapter($request->get('sbas_id'), $request->get('record_id'));
$record = new \record_adapter(
$request->get('sbas_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;
}
catch (\Exception $e)
{
$return['message'] = $e->getMessage();
}
$json = $app['Core']->getSerializer()->serialize($return, 'json');
$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;
}
}

View File

@@ -29,178 +29,166 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper;
class Tooltip implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$app['appbox'] = \appbox::get_instance($app['Core']);
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$app['appbox'] = \appbox::get_instance($app['Core']);
$controllers->post('/basket/{basket_id}/'
, function(Application $app, $basket_id)
{
$em = $app['Core']->getEntityManager();
$controllers->post('/basket/{basket_id}/'
, function(Application $app, $basket_id) {
$em = $app['Core']->getEntityManager();
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$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+');
$controllers->post('/Story/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $record_id)
{
$Story = new \record_adapter($sbas_id, $record_id);
$controllers->post('/Story/{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();
/* @var $twig \Twig_Environment */
$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+');
$controllers->post('/user/{usr_id}/'
, function(Application $app, $usr_id)
{
$user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
$controllers->post('/user/{usr_id}/'
, function(Application $app, $usr_id) {
$user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response($twig->render(
'prod/Tooltip/User.html.twig'
, array('user' => $user)
)
);
return new Response($twig->render(
'prod/Tooltip/User.html.twig'
, array('user' => $user)
)
);
})->assert('usr_id', '\d+');
$controllers->post('/preview/{sbas_id}/{record_id}/'
, function(Application $app, $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);
}
}
$controllers->post('/preview/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $record_id) {
$record = new \record_adapter($sbas_id, $record_id);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$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
)
)
);
return new Response($twig->render(
'common/preview.html'
, array(
'record' => $record
, 'not_wrapped' => true
)
)
);
})->assert('sbas_id', '\d+')->assert('record_id', '\d+');
$controllers->post('/tc_datas/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $record_id)
{
$record = new \record_adapter($sbas_id, $record_id);
$document = $record->get_subdef('document');
$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);
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$search_engine = null;
return new Response(
$twig->render(
'common/technical_datas.twig'
, array('record' => $record, 'document' => $document)
)
);
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 */
$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+');
$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);
$controllers->post('/tc_datas/{sbas_id}/{record_id}/'
, function(Application $app, $sbas_id, $record_id) {
$record = new \record_adapter($sbas_id, $record_id);
$document = $record->get_subdef('document');
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'common/databox_field.twig'
, array('field' => $field)
)
);
return new Response(
$twig->render(
'common/technical_datas.twig'
, 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+');
$controllers->post('/DCESInfos/{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);
$controllers->post('/DCESInfos/{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();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'common/databox_field_DCES.twig'
, array('field' => $field)
)
);
return new Response(
$twig->render(
'common/databox_field_DCES.twig'
, array('field' => $field)
)
);
})->assert('sbas_id', '\d+')->assert('field_id', '\d+');
$controllers->post('/metas/restrictionsInfos/{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);
$controllers->post('/metas/restrictionsInfos/{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();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
return new Response(
$twig->render(
'common/databox_field_restrictions.twig'
, array('field' => $field)
)
);
return new Response(
$twig->render(
'common/databox_field_restrictions.twig'
, array('field' => $field)
)
);
})->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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->post('/save/', function(Application $app, Request $request)
{
$ret = array('success' => false, 'message' => _('Error while saving preference'));
$controllers->post('/save/', function(Application $app, Request $request) {
$ret = array('success' => false, 'message' => _('Error while saving preference'));
try
{
$user = $app['Core']->getAuthenticatedUser();
try {
$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'))
$output = "1";
else
$output = "0";
if ($ret == $request->get('value'))
$output = "1";
else
$output = "0";
$ret = array('success' => true, 'message' => _('Preference saved !'));
}
catch (\Exception $e)
{
$ret = array('success' => true, 'message' => _('Preference saved !'));
} catch (\Exception $e) {
}
}
$Serializer = $app['Core']['Serializer'];
$datas = $Serializer->serialize($ret, 'json');
$Serializer = $app['Core']['Serializer'];
$datas = $Serializer->serialize($ret, 'json');
return new Response($datas, 200, array('Content-Type' => 'application/json'));
});
return $controllers;
}
return new Response($datas, 200, array('Content-Type' => 'application/json'));
});
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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/', function(Application $app)
{
$params = array(
'WorkZone' => new Helper\WorkZone($app['Core'], $app['request'])
, 'selected_type' => $app['request']->get('type')
, 'selected_id' => $app['request']->get('id')
, 'srt' => $app['request']->get('sort')
);
$controllers->get('/', function(Application $app) {
$params = array(
'WorkZone' => new Helper\WorkZone($app['Core'], $app['request'])
, 'selected_type' => $app['request']->get('type')
, 'selected_id' => $app['request']->get('id')
, '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)
{
$date_obj = new \DateTime();
$controllers->get('/Browse/', function(Application $app) {
$date_obj = new \DateTime();
$params = array(
'CurrentYear' => $date_obj->format('Y')
);
$params = array(
'CurrentYear' => $date_obj->format('Y')
);
return new Response(
$app['Core']->getTwig()->render('prod/WorkZone/Browser/Browser.html.twig'
, $params
)
);
});
return new Response(
$app['Core']->getTwig()->render('prod/WorkZone/Browser/Browser.html.twig'
, $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();
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
/* @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;
$offsetStart = max(($Page - 1) * $PerPage, 0);
$PerPage = 10;
$offsetStart = max(($Page - 1) * $PerPage, 0);
$Baskets = $BasketRepo->findWorkzoneBasket(
$user
, $request->get('Query')
, $request->get('Year')
, $request->get('Type')
, $offsetStart
, $PerPage
);
$Baskets = $BasketRepo->findWorkzoneBasket(
$user
, $request->get('Query')
, $request->get('Year')
, $request->get('Type')
, $offsetStart
, $PerPage
);
$page = floor($offsetStart / $PerPage) + 1;
$maxPage = floor(count($Baskets) / $PerPage) + 1;
$page = floor($offsetStart / $PerPage) + 1;
$maxPage = floor(count($Baskets) / $PerPage) + 1;
$params = array(
'Baskets' => $Baskets
, 'Page' => $page
, 'MaxPage' => $maxPage
, 'Total' => count($Baskets)
, 'Query' => $request->get('Query')
, 'Year' => $request->get('Year')
, 'Type' => $request->get('Type')
);
$params = array(
'Baskets' => $Baskets
, 'Page' => $page
, 'MaxPage' => $maxPage
, 'Total' => count($Baskets)
, 'Query' => $request->get('Query')
, 'Year' => $request->get('Year')
, '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')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
$basket = $em->getRepository('\Entities\Basket')
->findUserBasket($basket_id, $app['Core']->getAuthenticatedUser(), false);
$params = array(
'Basket' => $basket
);
$params = array(
'Basket' => $basket
);
return new Response($app['Core']->getTwig()->render('prod/WorkZone/Browser/Basket.html.twig', $params));
})->assert('basket_id', '\d+');
return new Response($app['Core']->getTwig()->render('prod/WorkZone/Browser/Basket.html.twig', $params));
})->assert('basket_id', '\d+');
$controllers->post(
'/attachStories/'
, function(Application $app, Request $request)
{
if (!$request->get('stories'))
throw new \Exception_BadRequest();
$controllers->post(
'/attachStories/'
, function(Application $app, Request $request) {
if ( ! $request->get('stories'))
throw new \Exception_BadRequest();
$user = $app['Core']->getAuthenticatedUser();
$user = $app['Core']->getAuthenticatedUser();
$em = $app['Core']->getEntityManager();
/* @var $em \Doctrine\ORM\EntityManager */
$em = $app['Core']->getEntityManager();
/* @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)
{
$element = explode('_', $element);
$Story = new \record_adapter($element[0], $element[1]);
foreach ($stories as $element) {
$element = explode('_', $element);
$Story = new \record_adapter($element[0], $element[1]);
if (!$Story->is_grouping())
throw new \Exception('You can only attach stories');
if ( ! $Story->is_grouping())
throw new \Exception('You can only attach stories');
if (!$user->ACL()->has_access_to_base($Story->get_base_id()))
throw new \Exception_Forbidden('You do not have access to this Story');
if ( ! $user->ACL()->has_access_to_base($Story->get_base_id()))
throw new \Exception_Forbidden('You do not have access to this Story');
if ($StoryWZRepo->findUserStory($user, $Story))
{
$alreadyFixed++;
continue;
}
if ($StoryWZRepo->findUserStory($user, $Story)) {
$alreadyFixed ++;
continue;
}
$StoryWZ = new \Entities\StoryWZ();
$StoryWZ->setUser($user);
$StoryWZ->setRecord($Story);
$StoryWZ = new \Entities\StoryWZ();
$StoryWZ->setUser($user);
$StoryWZ->setRecord($Story);
$em->persist($StoryWZ);
$done++;
}
$em->persist($StoryWZ);
$done ++;
}
$em->flush();
$em->flush();
if ($alreadyFixed === 0)
{
if ($done <= 1)
{
$message = sprintf(
_('%d Story attached to the WorkZone')
, $done
);
}
else
{
$message = sprintf(
_('%d Stories attached to the WorkZone')
, $done
);
}
}
else
{
if ($done <= 1)
{
$message = sprintf(
_('%1$d Story attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
}
else
{
$message = sprintf(
_('%1$d Stories attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
}
}
if ($alreadyFixed === 0) {
if ($done <= 1) {
$message = sprintf(
_('%d Story attached to the WorkZone')
, $done
);
} else {
$message = sprintf(
_('%d Stories attached to the WorkZone')
, $done
);
}
} else {
if ($done <= 1) {
$message = sprintf(
_('%1$d Story attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
} else {
$message = sprintf(
_('%1$d Stories attached to the WorkZone, %2$d already attached')
, $done
, $alreadyFixed
);
}
}
$data = array(
'success' => true
, 'message' => $message
);
$data = array(
'success' => true
, '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'));
}
else
{
return new RedirectResponse('/{sbas_id}/{record_id}/');
}
});
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/{sbas_id}/{record_id}/');
}
});
$controllers->post(
'/detachStory/{sbas_id}/{record_id}/'
, function(Application $app, Request $request, $sbas_id, $record_id)
{
$Story = new \record_adapter($sbas_id, $record_id);
$controllers->post(
'/detachStory/{sbas_id}/{record_id}/'
, function(Application $app, Request $request, $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 */
$StoryWZ = $repository->findUserStory($user, $Story);
/* @var $repository \Repositories\StoryWZRepository */
$StoryWZ = $repository->findUserStory($user, $Story);
if (!$StoryWZ)
{
throw new \Exception_NotFound('Story not found');
}
$em->remove($StoryWZ);
if ( ! $StoryWZ) {
throw new \Exception_NotFound('Story not found');
}
$em->remove($StoryWZ);
$em->flush();
$em->flush();
$data = array(
'success' => true
, 'message' => _('Story detached from the WorkZone')
);
$data = array(
'success' => true
, 'message' => _('Story detached from the WorkZone')
);
if ($request->getRequestFormat() == 'json')
{
$datas = $app['Core']['Serializer']->serialize($data, 'json');
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+');
return new Response($datas, 200, array('Content-type' => 'application/json'));
} else {
return new RedirectResponse('/');
}
})->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
* @link www.phraseanet.com
*/
class RSSFeeds implements ControllerProviderInterface
{
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
public function connect(Application $app)
{
$appbox = \appbox::get_instance($app['Core']);
$controllers = new ControllerCollection();
$controllers = new ControllerCollection();
$display_feed = function($feed, $format, $page, $user = null)
{
$total = $feed->get_count_total_entries();
$perPage = 5;
$entries = $feed->get_entries((($page - 1) * $perPage), $perPage);
$display_feed = function($feed, $format, $page, $user = null) {
$total = $feed->get_count_total_entries();
$perPage = 5;
$entries = $feed->get_entries((($page - 1) * $perPage), $perPage);
$registry = \registry::get_instance();
$registry = \registry::get_instance();
if ($format == \Feed_Adapter::FORMAT_RSS)
{
$content = new \Feed_XML_RSS();
}
if ($format == \Feed_Adapter::FORMAT_RSS) {
$content = new \Feed_XML_RSS();
}
if ($format == \Feed_Adapter::FORMAT_ATOM)
{
$content = new \Feed_XML_Atom();
}
if ($format == \Feed_Adapter::FORMAT_ATOM) {
$content = new \Feed_XML_Atom();
}
if($format == \Feed_Adapter::FORMAT_COOLIRIS)
{
$content = new \Feed_XML_Cooliris();
}
if ($format == \Feed_Adapter::FORMAT_COOLIRIS) {
$content = new \Feed_XML_Cooliris();
}
if ($user instanceof \User_Adapter)
$link = $feed->get_user_link($registry, $user, $format, $page);
else
$link = $feed->get_homepage_link($registry, $format, $page);
if ($user instanceof \User_Adapter)
$link = $feed->get_user_link($registry, $user, $format, $page);
else
$link = $feed->get_homepage_link($registry, $format, $page);
$content->set_updated_on(new \DateTime());
$content->set_title($feed->get_title());
$content->set_subtitle($feed->get_subtitle());
$content->set_generator('Phraseanet');
$content->set_link($link);
$content->set_updated_on(new \DateTime());
$content->set_title($feed->get_title());
$content->set_subtitle($feed->get_subtitle());
$content->set_generator('Phraseanet');
$content->set_link($link);
if ($user instanceof \User_Adapter)
{
if ($page > 1)
$content->set_previous_page($feed->get_user_link($registry, $user, $format, ($page - 1)));
if ($total > ($page * $perPage))
$content->set_next_page($feed->get_user_link($registry, $user, $format, ($page + 1)));
}
else
{
if ($page > 1)
$content->set_previous_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);
if ($user instanceof \User_Adapter) {
if ($page > 1)
$content->set_previous_page($feed->get_user_link($registry, $user, $format, ($page - 1)));
if ($total > ($page * $perPage))
$content->set_next_page($feed->get_user_link($registry, $user, $format, ($page + 1)));
}
else {
if ($page > 1)
$content->set_previous_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);
$render = $content->render();
$response = new Response($render, 200, array('Content-Type' => $content->get_mimetype()));
$response->setCharset('UTF-8');
$render = $content->render();
$response = new Response($render, 200, array('Content-Type' => $content->get_mimetype()));
$response->setCharset('UTF-8');
return $response;
return $response;
};
$controllers->get('/feed/{id}/{format}/', function($id, $format) use ($app, $appbox, $display_feed)
{
$feed = new \Feed_Adapter($appbox, $id);
$controllers->get('/feed/{id}/{format}/', function($id, $format) use ($app, $appbox, $display_feed) {
$feed = new \Feed_Adapter($appbox, $id);
if (!$feed->is_public())
{
return new Response('Forbidden', 403);
}
if ( ! $feed->is_public()) {
return new Response('Forbidden', 403);
}
$request = $app['request'];
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
$page = (int) $request->get('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)');
$controllers->get('/userfeed/{token}/{id}/{format}/', function($token, $id, $format) use ($app, $appbox, $display_feed)
{
try
{
$token = new \Feed_Token($appbox, $token, $id);
$feed = $token->get_feed();
}
catch (\Exception_FeedNotFound $e)
{
return new Response('Not Found', 404);
}
$request = $app['request'];
$controllers->get('/userfeed/{token}/{id}/{format}/', function($token, $id, $format) use ($app, $appbox, $display_feed) {
try {
$token = new \Feed_Token($appbox, $token, $id);
$feed = $token->get_feed();
} catch (\Exception_FeedNotFound $e) {
return new Response('Not Found', 404);
}
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
$page = (int) $request->get('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)');
$controllers->get('/userfeed/aggregated/{token}/{format}/', function($token, $format) use ($app, $appbox, $display_feed)
{
try
{
$token = new \Feed_TokenAggregate($appbox, $token);
$feed = $token->get_feed();
}
catch (\Exception_FeedNotFound $e)
{
return new Response('', 404);
}
$controllers->get('/userfeed/aggregated/{token}/{format}/', function($token, $format) use ($app, $appbox, $display_feed) {
try {
$token = new \Feed_TokenAggregate($appbox, $token);
$feed = $token->get_feed();
} catch (\Exception_FeedNotFound $e) {
return new Response('', 404);
}
$request = $app['request'];
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
$page = (int) $request->get('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)');
$controllers->get('/aggregated/{format}/', function($format) use ($app, $appbox, $display_feed)
{
$feeds = \Feed_Collection::load_public_feeds($appbox);
$feed = $feeds->get_aggregate();
$controllers->get('/aggregated/{format}/', function($format) use ($app, $appbox, $display_feed) {
$feeds = \Feed_Collection::load_public_feeds($appbox);
$feed = $feeds->get_aggregate();
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
return $display_feed($feed, $format, $page);
return $display_feed($feed, $format, $page);
})->assert('format', '(rss|atom)');
$controllers->get('/cooliris/', function() use ($app, $appbox, $display_feed) {
$feeds = \Feed_Collection::load_public_feeds($appbox);
$feed = $feeds->get_aggregate();
$controllers->get('/cooliris/', function() use ($app, $appbox, $display_feed) {
$feeds = \Feed_Collection::load_public_feeds($appbox);
$feed = $feeds->get_aggregate();
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
$request = $app['request'];
$page = (int) $request->get('page');
$page = $page < 1 ? 1 : $page;
return $display_feed($feed, \Feed_Adapter::FORMAT_COOLIRIS , $page);
});
return $controllers;
}
return $display_feed($feed, \Feed_Adapter::FORMAT_COOLIRIS, $page);
});
return $controllers;
}
}

View File

@@ -28,329 +28,297 @@ use Silex\ControllerCollection;
class Installer implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/', function() use ($app)
{
$request = $app['request'];
$controllers->get('/', function() use ($app) {
$request = $app['request'];
$php_constraint = \setup::check_php_version();
$writability_constraints = \setup::check_writability(new \Setup_Registry());
$extension_constraints = \setup::check_php_extension();
$opcode_constraints = \setup::check_cache_opcode();
$php_conf_constraints = \setup::check_php_configuration();
$locales_constraints = \setup::check_system_locales();
$php_constraint = \setup::check_php_version();
$writability_constraints = \setup::check_writability(new \Setup_Registry());
$extension_constraints = \setup::check_php_extension();
$opcode_constraints = \setup::check_cache_opcode();
$php_conf_constraints = \setup::check_php_configuration();
$locales_constraints = \setup::check_system_locales();
$constraints_coll = array(
'php_constraint' => $php_constraint
, 'writability_constraints' => $writability_constraints
, 'extension_constraints' => $extension_constraints
, 'opcode_constraints' => $opcode_constraints
, 'php_conf_constraints' => $php_conf_constraints
, 'locales_constraints' => $locales_constraints
);
$redirect = true;
$constraints_coll = array(
'php_constraint' => $php_constraint
, 'writability_constraints' => $writability_constraints
, 'extension_constraints' => $extension_constraints
, 'opcode_constraints' => $opcode_constraints
, 'php_conf_constraints' => $php_conf_constraints
, 'locales_constraints' => $locales_constraints
);
$redirect = true;
foreach ($constraints_coll as $key => $constraints)
{
$unset = true;
foreach ($constraints as $constraint)
{
if (!$constraint->is_ok() && $constraint->is_blocker())
$redirect = $unset = false;
foreach ($constraints_coll as $key => $constraints) {
$unset = true;
foreach ($constraints as $constraint) {
if ( ! $constraint->is_ok() && $constraint->is_blocker())
$redirect = $unset = false;
}
if ($unset === true) {
unset($constraints_coll[$key]);
}
}
if ($unset === true)
{
unset($constraints_coll[$key]);
if ($redirect) {
return $app->redirect('/setup/installer/step2/');
}
}
if ($redirect)
{
return $app->redirect('/setup/installer/step2/');
}
$ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new \Twig_Environment($loader);
$ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new \Twig_Environment($loader);
$html = $twig->render(
'/setup/index.html.twig'
, array_merge($constraints_coll, array(
'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['Core']::getAvailableLanguages()
, 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName()
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
))
);
$html = $twig->render(
'/setup/index.html.twig'
, array_merge($constraints_coll, array(
'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['Core']::getAvailableLanguages()
, 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName()
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
))
);
return new Response($html);
return new Response($html);
});
$controllers->get('/step2/', function() use ($app)
{
\phrasea::use_i18n(\Session_Handler::get_locale());
$controllers->get('/step2/', function() use ($app) {
\phrasea::use_i18n(\Session_Handler::get_locale());
$ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new \Twig_Loader_Filesystem($ld_path);
$ld_path = array(__DIR__ . '/../../../../../templates/web');
$loader = new \Twig_Loader_Filesystem($ld_path);
$twig = new \Twig_Environment($loader);
$twig->addExtension(new \Twig_Extensions_Extension_I18n());
$twig = new \Twig_Environment($loader);
$twig->addExtension(new \Twig_Extensions_Extension_I18n());
$request = $app['request'];
$request = $app['request'];
$warnings = array();
$warnings = array();
$php_constraint = \setup::check_php_version();
$writability_constraints = \setup::check_writability(new \Setup_Registry());
$extension_constraints = \setup::check_php_extension();
$opcode_constraints = \setup::check_cache_opcode();
$php_conf_constraints = \setup::check_php_configuration();
$locales_constraints = \setup::check_system_locales();
$php_constraint = \setup::check_php_version();
$writability_constraints = \setup::check_writability(new \Setup_Registry());
$extension_constraints = \setup::check_php_extension();
$opcode_constraints = \setup::check_cache_opcode();
$php_conf_constraints = \setup::check_php_configuration();
$locales_constraints = \setup::check_system_locales();
$constraints_coll = array(
'php_constraint' => $php_constraint
, 'writability_constraints' => $writability_constraints
, 'extension_constraints' => $extension_constraints
, 'opcode_constraints' => $opcode_constraints
, 'php_conf_constraints' => $php_conf_constraints
, 'locales_constraints' => $locales_constraints
);
$constraints_coll = array(
'php_constraint' => $php_constraint
, 'writability_constraints' => $writability_constraints
, 'extension_constraints' => $extension_constraints
, 'opcode_constraints' => $opcode_constraints
, 'php_conf_constraints' => $php_conf_constraints
, 'locales_constraints' => $locales_constraints
);
foreach ($constraints_coll as $key => $constraints)
{
$unset = true;
foreach ($constraints as $constraint)
{
if (!$constraint->is_ok() && !$constraint->is_blocker())
{
$warnings[] = $constraint->get_message();
}
foreach ($constraints_coll as $key => $constraints) {
$unset = true;
foreach ($constraints as $constraint) {
if ( ! $constraint->is_ok() && ! $constraint->is_blocker()) {
$warnings[] = $constraint->get_message();
}
}
}
}
if ($request->getScheme() == 'http')
{
$warnings[] = _('It is not recommended to install Phraseanet without HTTPS support');
}
if ($request->getScheme() == 'http') {
$warnings[] = _('It is not recommended to install Phraseanet without HTTPS support');
}
$html = $twig->render(
'/setup/step2.html.twig'
, array(
'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['Core']::getAvailableLanguages()
, 'available_templates' => \appbox::list_databox_templates()
, 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName()
, 'warnings' => $warnings
, 'error' => $request->get('error')
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
, 'discovered_binaries' => \setup::discover_binaries()
, 'rootpath' => dirname(dirname(dirname(dirname(__DIR__)))) . '/'
)
);
$html = $twig->render(
'/setup/step2.html.twig'
, array(
'locale' => \Session_Handler::get_locale()
, 'available_locales' => $app['Core']::getAvailableLanguages()
, 'available_templates' => \appbox::list_databox_templates()
, 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName()
, 'warnings' => $warnings
, 'error' => $request->get('error')
, 'current_servername' => $request->getScheme() . '://' . $request->getHttpHost() . '/'
, 'discovered_binaries' => \setup::discover_binaries()
, 'rootpath' => dirname(dirname(dirname(dirname(__DIR__)))) . '/'
)
);
return new Response($html);
return new Response($html);
});
$controllers->post('/install/', function() use ($app)
{
set_time_limit(360);
\phrasea::use_i18n(\Session_Handler::get_locale());
$request = $app['request'];
$controllers->post('/install/', function() use ($app) {
set_time_limit(360);
\phrasea::use_i18n(\Session_Handler::get_locale());
$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->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())
{
$serviceName = $configuration->getOrm();
$confService = $configuration->getService($serviceName);
$appbox_name = $request->get('ab_name');
$databox_name = $request->get('db_name');
$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);
}
}
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'));
}
$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;
}
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'));
}
$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()));
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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/', function() use ($app)
{
require_once __DIR__ . '/../../../../bootstrap.php';
$upgrade_status = \Setup_Upgrade::get_status();
$controllers->get('/', function() use ($app) {
require_once __DIR__ . '/../../../../bootstrap.php';
$upgrade_status = \Setup_Upgrade::get_status();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
/* @var $twig \Twig_Environment */
$twig = $app['Core']->getTwig();
$html = $twig->render(
'/setup/upgrader.html.twig'
, array(
'locale' => \Session_Handler::get_locale()
, 'upgrade_status' => $upgrade_status
, 'available_locales' => $app['Core']::getAvailableLanguages()
, 'bad_users' => \User_Adapter::get_wrong_email_users(\appbox::get_instance($app['Core']))
, 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName()
)
);
ini_set('display_errors', 'on');
$html = $twig->render(
'/setup/upgrader.html.twig'
, array(
'locale' => \Session_Handler::get_locale()
, 'upgrade_status' => $upgrade_status
, 'available_locales' => $app['Core']::getAvailableLanguages()
, 'bad_users' => \User_Adapter::get_wrong_email_users(\appbox::get_instance($app['Core']))
, 'version_number' => $app['Core']['Version']->getNumber()
, 'version_name' => $app['Core']['Version']->getName()
)
);
ini_set('display_errors', 'on');
return new Response($html);
return new Response($html);
});
$controllers->get('/status/', function() use ($app)
{
require_once __DIR__ . '/../../../../bootstrap.php';
$controllers->get('/status/', function() use ($app) {
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(
$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('/execute/', function() use ($app)
{
require_once __DIR__ . '/../../../../bootstrap.php';
set_time_limit(0);
session_write_close();
ignore_user_abort(true);
$controllers->post('/execute/', function() use ($app) {
require_once __DIR__ . '/../../../../bootstrap.php';
set_time_limit(0);
session_write_close();
ignore_user_abort(true);
$appbox = \appbox::get_instance($app['Core']);
$upgrader = new \Setup_Upgrade($appbox);
$appbox->forceUpgrade($upgrader);
$appbox = \appbox::get_instance($app['Core']);
$upgrader = new \Setup_Upgrade($appbox);
$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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/mysql/', function() use ($app)
{
require_once __DIR__ . '/../../../../classes/connection/pdo.class.php';
$controllers->get('/mysql/', function() use ($app) {
require_once __DIR__ . '/../../../../classes/connection/pdo.class.php';
$request = $app['request'];
$hostname = $request->get('hostname', '127.0.0.1');
$port = (int) $request->get('port', 3306);
$user = $request->get('user');
$password = $request->get('password');
$dbname = $request->get('dbname');
$request = $app['request'];
$hostname = $request->get('hostname', '127.0.0.1');
$port = (int) $request->get('port', 3306);
$user = $request->get('user');
$password = $request->get('password');
$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
{
$conn = new \connection_pdo('test', $hostname, $port, $user, $password);
$connection_ok = true;
}
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)
{
try {
$conn = new \connection_pdo('test', $hostname, $port, $user, $password);
$connection_ok = 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(
'connection' => $connection_ok
, 'database' => $db_ok
, 'is_empty' => $empty
, 'is_appbox' => $is_appbox
, 'is_databox' => $is_databox
);
$sql = "SHOW TABLE STATUS";
$stmt = $conn->prepare($sql);
$stmt->execute();
return new Response(
$Serializer->serialize($datas, 'json')
, 200
, array('content-type' => 'application/json')
);
$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'];
$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
{
public function connect(Application $app)
{
$controllers = new ControllerCollection();
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('/path/', function() use ($app)
{
$path = $app['request']->get('path');
$controllers->get('/path/', function() use ($app) {
$path = $app['request']->get('path');
$Serializer = $app['Core']['Serializer'];
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize(
array(
'exists' => file_exists($path)
, 'file' => is_file($path)
, 'dir' => is_dir($path)
, 'readable' => is_readable($path)
, 'writeable' => is_writable($path)
, 'executable' => is_executable($path)
)
, 'json'
)
, 200
, array('content-type' => 'application/json')
);
return new Response(
$Serializer->serialize(
array(
'exists' => file_exists($path)
, 'file' => is_file($path)
, 'dir' => is_dir($path)
, 'readable' => is_readable($path)
, 'writeable' => is_writable($path)
, 'executable' => is_executable($path)
)
, 'json'
)
, 200
, array('content-type' => 'application/json')
);
});
$controllers->get('/url/', function() use ($app)
{
$url = $app['request']->get('url');
$controllers->get('/url/', function() use ($app) {
$url = $app['request']->get('url');
$Serializer = $app['Core']['Serializer'];
$Serializer = $app['Core']['Serializer'];
return new Response(
$Serializer->serialize(
array(
'code' => \http_query::getHttpCodeFromUrl($url)
)
, 'json'
)
, 200
, array('content-type' => 'application/json')
);
return new Response(
$Serializer->serialize(
array(
'code' => \http_query::getHttpCodeFromUrl($url)
)
, 'json'
)
, 200
, 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
{
protected static $availableLanguages = array(
'ar_SA' => 'العربية'
, 'de_DE' => 'Deutsch'
, 'en_GB' => 'English'
, 'es_ES' => 'Español'
, 'fr_FR' => 'Français'
'ar_SA' => 'العربية'
, 'de_DE' => 'Deutsch'
, 'en_GB' => 'English'
, 'es_ES' => 'Español'
, 'fr_FR' => 'Français'
);
protected static $autoloader_initialized = false;
/**
@@ -70,109 +68,94 @@ class Core extends \Pimple
/**
* Set version
*/
$this['Version'] = $this->share(function()
{
return new Core\Version();
});
$this['Version'] = $this->share(function() {
return new Core\Version();
});
if ($this->configuration->isInstalled())
{
$this['Registry'] = $this->share(function() use ($core)
{
return \registry::get_instance($core);
});
if ($this->configuration->isInstalled()) {
$this['Registry'] = $this->share(function() use ($core) {
return \registry::get_instance($core);
});
\phrasea::start($this);
}
else
{
} else {
$this['Registry'] = $this->share(function()
{
return new \Setup_Registry();
});
$this['Registry'] = $this->share(function() {
return new \Setup_Registry();
});
}
$this['CacheService'] = $this->share(function() use ($core)
{
if ( ! file_exists(__DIR__ . '/../../../tmp/cache_registry.yml'))
{
touch(__DIR__ . '/../../../tmp/cache_registry.yml');
}
$this['CacheService'] = $this->share(function() use ($core) {
if ( ! file_exists(__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
*/
$this['EM'] = $this->share(function() use ($core)
{
$serviceName = $core->getConfiguration()->getOrm();
$configuration = $core->getConfiguration()->getService($serviceName);
$this['EM'] = $this->share(function() use ($core) {
$serviceName = $core->getConfiguration()->getOrm();
$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)
{
$serviceName = $core->getConfiguration()->getCache();
$this['Cache'] = $this->share(function() use ($core) {
$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)
{
$serviceName = $core->getConfiguration()->getOpcodeCache();
$this['OpcodeCache'] = $this->share(function() use ($core) {
$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)
{
$serviceName = $core->getConfiguration()->getTemplating();
$configuration = $core->getConfiguration()->getService($serviceName);
$this["Twig"] = $this->share(function() use ($core) {
$serviceName = $core->getConfiguration()->getTemplating();
$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()
{
$encoders = array(
'json' => new Serializer\Encoder\JsonEncoder()
);
$this['Serializer'] = $this->share(function() {
$encoders = array(
'json' => new Serializer\Encoder\JsonEncoder()
);
return new Serializer\Serializer(array(), $encoders);
});
return new Serializer\Serializer(array(), $encoders);
});
$this['monolog'] = $this->share(function () use ($core)
{
$logger = new \Monolog\Logger('Logger');
$this['monolog'] = $this->share(function () use ($core) {
$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)
{
$conf = $core->getConfiguration()->has('media-alchemyst') ? $core->getConfiguration()->get('media-alchemyst') : new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag(array());
$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());
$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();
@@ -199,15 +182,11 @@ class Core extends \Pimple
*/
private function init()
{
if ($this->configuration->isInstalled())
{
if ($this->configuration->isDisplayingErrors())
{
if ($this->configuration->isInstalled()) {
if ($this->configuration->isDisplayingErrors()) {
ini_set('display_errors', 'on');
error_reporting(E_ALL);
}
else
{
} else {
ini_set('display_errors', 'off');
}
}
@@ -292,11 +271,10 @@ class Core extends \Pimple
*/
public function getAuthenticatedUser()
{
$appbox = \appbox::get_instance($this);
$appbox = \appbox::get_instance($this);
$session = \Session_Handler::getInstance($appbox);
if ($session->get_usr_id())
{
if ($session->get_usr_id()) {
return \User_Adapter::getInstance($session->get_usr_id(), $appbox);
}
@@ -325,7 +303,6 @@ class Core extends \Pimple
return;
}
protected $request;
protected function getRequest()
@@ -368,12 +345,9 @@ class Core extends \Pimple
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');
}
else
{
} else {
ini_set('log_errors', 'off');
}
@@ -397,13 +371,12 @@ class Core extends \Pimple
protected function detectLanguage()
{
$this->getRequest()->setDefaultLocale(
$this->getRegistry()->get('GV_default_lng', 'en_GB')
$this->getRegistry()->get('GV_default_lng', 'en_GB')
);
$cookies = $this->getRequest()->cookies;
if (isset(static::$availableLanguages[$cookies->get('locale')]))
{
if (isset(static::$availableLanguages[$cookies->get('locale')])) {
$this->getRequest()->setLocale($cookies->get('locale'));
}
@@ -418,42 +391,33 @@ class Core extends \Pimple
*/
public static function initAutoloads($cacheAutoload = false)
{
if (static::$autoloader_initialized)
{
if (static::$autoloader_initialized) {
return;
}
require_once __DIR__ . '/Loader/Autoloader.php';
if ($cacheAutoload === true)
{
try
{
if ($cacheAutoload === true) {
try {
require_once __DIR__ . '/Loader/CacheAutoloader.php';
$prefix = 'class_';
$prefix = 'class_';
$namespace = md5(__DIR__);
$loader = new Loader\CacheAutoloader($prefix, $namespace);
}
catch (\Exception $e)
{
} catch (\Exception $e) {
//no op code cache available
$loader = new Loader\Autoloader();
}
}
else
{
} else {
$loader = new Loader\Autoloader();
}
$getComposerNamespaces = function()
{
return require realpath(__DIR__ . '/../../../vendor/.composer/autoload_namespaces.php');
};
$getComposerNamespaces = function() {
return require realpath(__DIR__ . '/../../../vendor/.composer/autoload_namespaces.php');
};
foreach ($getComposerNamespaces() as $prefix => $path)
{
foreach ($getComposerNamespaces() as $prefix => $path) {
if (substr($prefix, -1) === '_')
$loader->registerPrefix($prefix, $path);
else
@@ -461,18 +425,18 @@ class Core extends \Pimple
}
$loader->registerNamespaces(array(
'Entities' => realpath(__DIR__ . '/../../Doctrine/'),
'Repositories' => realpath(__DIR__ . '/../../Doctrine/'),
'Proxies' => realpath(__DIR__ . '/../../Doctrine/'),
'Doctrine\\Logger' => realpath(__DIR__ . '/../../'),
'Types' => realpath(__DIR__ . "/../../Doctrine"),
'PhraseaFixture' => realpath(__DIR__ . "/../../conf.d"),
'Entities' => realpath(__DIR__ . '/../../Doctrine/'),
'Repositories' => realpath(__DIR__ . '/../../Doctrine/'),
'Proxies' => realpath(__DIR__ . '/../../Doctrine/'),
'Doctrine\\Logger' => realpath(__DIR__ . '/../../'),
'Types' => realpath(__DIR__ . "/../../Doctrine"),
'PhraseaFixture' => realpath(__DIR__ . "/../../conf.d"),
));
$loader->register();
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;
@@ -488,8 +452,7 @@ class Core extends \Pimple
{
ini_set('output_buffering', '4096');
if ((int) ini_get('memory_limit') < 2048)
{
if ((int) ini_get('memory_limit') < 2048) {
ini_set('memory_limit', '2048M');
}
@@ -514,5 +477,4 @@ class Core extends \Pimple
{
return $this->configuration->getEnvironnement();
}
}

View File

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

View File

@@ -20,149 +20,142 @@ namespace Alchemy\Phrasea\Core\Configuration;
*/
class ApplicationSpecification implements Specification
{
protected $parser;
protected $parser;
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)
public function __construct()
{
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)
{
$this->parser = new \Symfony\Component\Yaml\Yaml();
}
return false;
}
public function setConfigurations($configurations)
{
return file_put_contents(
$this->getConfigurationsPathFile(), $this->parser->dump($configurations, 7)
);
}
protected function getConfigurationsPathFile()
{
return $this->getRealRootPath() . '/config/config.yml';
}
public function setConnexions($connexions)
{
return file_put_contents(
$this->getConnexionsPathFile(), $this->parser->dump($connexions, 7)
);
}
protected function getConnexionsPathFile()
{
return $this->getRealRootPath() . '/config/connexions.yml';
}
public function setServices($services)
{
return file_put_contents(
$this->getServicesPathFile(), $this->parser->dump($services, 7)
);
}
protected function getServicesPathFile()
{
return $this->getRealRootPath() . '/config/services.yml';
}
public function getConfigurations()
{
return $this->parser->parse(
file_get_contents($this->getConfigurationsPathFile())
);
}
protected function getRealRootPath()
{
return realpath(__DIR__ . '/../../../../../');
}
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))
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
{
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 isSetup();
public function delete();
public function isSetup();
}

View File

@@ -23,25 +23,20 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag,
class Builder
{
public static function create(Core $core, ParameterBag $configuration)
{
$classname = __NAMESPACE__ . '\\' . $configuration->get("type");
if (!class_exists($classname))
public static function create(Core $core, ParameterBag $configuration)
{
throw new Exception\ServiceNotFound(sprintf('Service %s not found', $classname));
}
$classname = __NAMESPACE__ . '\\' . $configuration->get("type");
try
{
$options = $configuration->get("options");
}
catch (\Exception $e)
{
$options = array();
}
if ( ! class_exists($classname)) {
throw new Exception\ServiceNotFound(sprintf('Service %s not found', $classname));
}
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
{
protected $cache;
protected $cache;
public function getDriver()
{
if (!extension_loaded('apc'))
public function getDriver()
{
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();
$this->cache->setNamespace(md5(realpath(__DIR__ . '/../../../../../../')));
return 'apc';
}
return $this->cache;
}
public function getType()
{
return 'apc';
}
}

View File

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

View File

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

View File

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

View File

@@ -26,38 +26,34 @@ use Doctrine\Logger\MonologSQLLogger;
*/
class Monolog extends ParentLog
{
const JSON_OUTPUT = 'json';
const YAML_OUTPUT = 'yaml';
const VAR_DUMP_OUTPUT = 'vdump';
const JSON_OUTPUT = 'json';
const YAML_OUTPUT = 'yaml';
const VAR_DUMP_OUTPUT = 'vdump';
public function getDriver()
{
$output = isset($this->options["output"]) ? $this->options["output"] : self::JSON_OUTPUT;
$outputs = array(
self::JSON_OUTPUT, self::YAML_OUTPUT, self::VAR_DUMP_OUTPUT
);
if (!in_array($output, $outputs))
public function getDriver()
{
throw new \Exception(sprintf(
"The output type '%s' declared in %s service is not valid.
$output = isset($this->options["output"]) ? $this->options["output"] : self::JSON_OUTPUT;
$outputs = array(
self::JSON_OUTPUT, self::YAML_OUTPUT, self::VAR_DUMP_OUTPUT
);
if ( ! in_array($output, $outputs)) {
throw new \Exception(sprintf(
"The output type '%s' declared in %s service is not valid.
Available types are %s."
, $output
, __CLASS__
, implode(", ", $outputs)
)
);
, $output
, __CLASS__
, 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\ServiceAbstract,
Alchemy\Phrasea\Core\Service\ServiceInterface;
use Doctrine\DBAL\Logging\EchoSQLLogger;
/**
*
* @package
@@ -26,14 +26,13 @@ use Doctrine\DBAL\Logging\EchoSQLLogger;
class Phpecho extends ServiceAbstract
{
public function getDriver()
{
return new EchoSQLLogger();
}
public function getType()
{
return 'phpecho';
}
public function getDriver()
{
return new EchoSQLLogger();
}
public function getType()
{
return 'phpecho';
}
}

View File

@@ -26,24 +26,21 @@ use Monolog\Handler\FirePHPHandler;
*/
class FirePHP extends ServiceAbstract
{
protected $logger;
protected $logger;
public function getDriver()
{
if (!$this->logger)
public function getDriver()
{
$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
{
const DEFAULT_MAX_DAY = 10;
const DEFAULT_MAX_DAY = 10;
protected $handlers = array(
'rotate' => 'RotatingFile'
, 'stream' => 'Stream'
);
protected $handlers = array(
'rotate' => 'RotatingFile'
, 'stream' => 'Stream'
);
/**
*
* @var \Monolog\Logger
*/
protected $monolog;
/**
*
* @var \Monolog\Logger
*/
protected $monolog;
protected function init()
{
$options = $this->getOptions();
if (empty($options))
protected function init()
{
throw new \Exception(sprintf("'%s' service options can not be empty", $this->name));
}
$options = $this->getOptions();
//defaut to main handler
$handler = isset($options["handler"]) ? $options["handler"] : false;
if (empty($options)) {
throw new \Exception(sprintf("'%s' service options can not be empty", $this->name));
}
if (!$handler)
{
throw new \Exception(sprintf(
"You must specify at least one handler for '%s' service"
, __CLASS__
)
);
}
//defaut to main handler
$handler = isset($options["handler"]) ? $options["handler"] : false;
if (!array_key_exists($handler, $this->handlers))
{
throw new \Exception(sprintf(
"The handler type '%s' declared in %s %s service is not valid.
if ( ! $handler) {
throw new \Exception(sprintf(
"You must specify at least one handler for '%s' service"
, __CLASS__
)
);
}
if ( ! array_key_exists($handler, $this->handlers)) {
throw new \Exception(sprintf(
"The handler type '%s' declared in %s %s service is not valid.
Available types are %s."
, $handler
, __CLASS__
, implode(", ", $this->handlers)
)
);
, $handler
, __CLASS__
, implode(", ", $this->handlers)
)
);
}
$handlerName = $this->handlers[$handler];
$handlerClassName = sprintf('\Monolog\Handler\%sHandler', $handlerName);
if ( ! class_exists($handlerClassName)) {
throw new \Exception(sprintf(
'Unable to log monolog handler %s looked for class %s'
, $handlerName
, $handlerClassName)
);
}
if ( ! isset($options["filename"])) {
throw new \Exception(sprintf(
"Missing filename option in '%s' service"
, __CLASS__
)
);
}
$logPath = __DIR__ . '/../../../../../../logs';
$file = sprintf('%s/%s', $logPath, $options["filename"]);
if ($handler == 'rotate') {
$maxDay = isset($options["max_day"]) ?
(int) $options["max_day"] :
self::DEFAULT_MAX_DAY;
$handlerInstance = new $handlerClassName($file, $maxDay);
} else {
$handlerInstance = new $handlerClassName($file);
}
$channel = isset($options["channel"]) ? $options["channel"] : "monolog";
$monologLogger = new \Monolog\Logger($channel);
$monologLogger->pushHandler($handlerInstance);
$this->monolog = $monologLogger;
}
$handlerName = $this->handlers[$handler];
$handlerClassName = sprintf('\Monolog\Handler\%sHandler', $handlerName);
if (!class_exists($handlerClassName))
public function getDriver()
{
throw new \Exception(sprintf(
'Unable to log monolog handler %s looked for class %s'
, $handlerName
, $handlerClassName)
);
return $this->monolog;
}
if (!isset($options["filename"]))
public function getType()
{
throw new \Exception(sprintf(
"Missing filename option in '%s' service"
, __CLASS__
)
);
return 'monolog';
}
$logPath = __DIR__ . '/../../../../../../logs';
$file = sprintf('%s/%s', $logPath, $options["filename"]);
if ($handler == 'rotate')
public function getMandatoryOptions()
{
$maxDay = isset($options["max_day"]) ?
(int) $options["max_day"] :
self::DEFAULT_MAX_DAY;
$handlerInstance = new $handlerClassName($file, $maxDay);
return array('channel', 'handler', 'filename');
}
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
{
protected $loggers = array(
'Log\\Doctrine\Monolog'
, '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 $loggers = array(
'Log\\Doctrine\Monolog'
, 'Log\\Doctrine\\Phpecho'
);
protected $entityManager;
protected $debug;
$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)
protected function init()
{
throw new \Exception(sprintf(
"Missing dbal configuration for '%s' service"
, __CLASS__
)
);
$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')
);
$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();
}
catch (\Exception $e)
{
throw new \Exception("Connexion '%s' is not declared");
$platform = $this->entityManager->getConnection()->getDatabasePlatform();
if ( ! Type::hasType('blob')) {
Type::addType('blob', 'Types\Blob');
}
if ( ! Type::hasType('enum')) {
Type::addType('enum', 'Types\Enum');
}
if ( ! Type::hasType('longblob')) {
Type::addType('longblob', 'Types\LongBlob');
}
if ( ! Type::hasType('varbinary')) {
Type::addType('varbinary', 'Types\VarBinary');
}
if ( ! Type::hasType('binary')) {
Type::addType('binary', 'Types\Binary');
}
$platform->registerDoctrineTypeMapping('enum', 'enum');
$platform->registerDoctrineTypeMapping('blob', 'blob');
$platform->registerDoctrineTypeMapping('longblob', 'longblob');
$platform->registerDoctrineTypeMapping('varbinary', 'varbinary');
$platform->registerDoctrineTypeMapping('binary', 'binary');
return;
}
$evm = new \Doctrine\Common\EventManager();
$evm->addEventSubscriber(new \Gedmo\Timestampable\TimestampableListener());
try
private function getLog($serviceName)
{
$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()
)
);
}
try {
$configuration = $this->core->getConfiguration()->getService($serviceName);
} catch (\Exception $e) {
$message = sprintf(
"%s from %s service"
, $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 (!Type::hasType('blob'))
{
Type::addType('blob', 'Types\Blob');
}
if (!Type::hasType('enum'))
{
Type::addType('enum', 'Types\Enum');
}
if (!Type::hasType('longblob'))
{
Type::addType('longblob', 'Types\LongBlob');
}
if (!Type::hasType('varbinary'))
{
Type::addType('varbinary', 'Types\VarBinary');
}
if (!Type::hasType('binary'))
{
Type::addType('binary', 'Types\Binary');
}
$platform->registerDoctrineTypeMapping('enum', 'enum');
$platform->registerDoctrineTypeMapping('blob', 'blob');
$platform->registerDoctrineTypeMapping('longblob', 'longblob');
$platform->registerDoctrineTypeMapping('varbinary', 'varbinary');
$platform->registerDoctrineTypeMapping('binary', 'binary');
return;
}
private function getLog($serviceName)
{
try
{
$configuration = $this->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.
if ( ! in_array($type, $this->loggers)) {
throw new \Exception(sprintf(
"The logger type '%s' declared in %s service is not valid.
Available types are %s."
, $type
, __CLASS__
, implode(", ", $this->loggers)
)
);
, $type
, __CLASS__
, 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()
{
return $this->entityManager;
}
public function getType()
{
return 'doctrine';
}
public function isDebug()
{
return $this->debug;
}
public function getMandatoryOptions()
{
return array('debug', 'dbal');
}
public function isDebug()
{
return $this->debug;
}
public function getMandatoryOptions()
{
return array('debug', 'dbal');
}
}

View File

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

View File

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

View File

@@ -18,196 +18,186 @@ use Alchemy\Phrasea\Core,
class Twig extends ServiceAbstract
{
/**
*
* @var \Twig_Environment
*/
protected $twig;
protected $templatesPath = array();
/**
*
* @var \Twig_Environment
*/
protected $twig;
protected $templatesPath = array();
protected function init()
{
$this->templatesPath = $this->resolvePaths();
try
protected function init()
{
if (!$this->options['debug'])
{
$this->options['cache'] = realpath(__DIR__ . '/../../../../../../tmp/cache_twig/');
}
$this->templatesPath = $this->resolvePaths();
$loader = new \Twig_Loader_Filesystem($this->templatesPath);
$this->twig = new \Twig_Environment($loader, $this->options);
$this->loadGlobals();
$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()
)
);
}
}
try {
if ( ! $this->options['debug']) {
$this->options['cache'] = realpath(__DIR__ . '/../../../../../../tmp/cache_twig/');
}
/**
* Load phraseanet global variable
* it' s like any other template variable,
* except that its available in all templates and macros
* @return void
*/
private function loadGlobals()
{
$appbox = \appbox::get_instance($this->core);
$session = $appbox->get_session();
$browser = \Browser::getInstance();
$registry = $appbox->get_registry();
$request = new \http_request();
$user = false;
if ($session->is_authenticated())
{
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
$loader = new \Twig_Loader_Filesystem($this->templatesPath);
$this->twig = new \Twig_Environment($loader, $this->options);
$this->loadGlobals();
$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()
)
);
}
}
$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);
}
/**
* 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())
/**
* Load phraseanet global variable
* it' s like any other template variable,
* except that its available in all templates and macros
* @return void
*/
private function loadGlobals()
{
$paths = $templatePath['mobile'];
}
else
{
$paths = $templatePath['web'];
$appbox = \appbox::get_instance($this->core);
$session = $appbox->get_session();
$browser = \Browser::getInstance();
$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);
$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()
{
return $this->twig;
}
private function loadTests()
{
$this->twig->addTest('null', new \Twig_Test_Function('is_null'));
}
public function getType()
{
return 'twig';
}
/**
* 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'));
}
public function getMandatoryOptions()
{
return array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
}
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'];
} 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
{
protected static $number = '3.7.0.0.a2';
protected static $name = 'Carnosaurus';
protected static $number = '3.7.0.0.a2';
protected static $name = 'Carnosaurus';
public static function getNumber()
{
return static::$number;
}
public static function getName()
{
return static::$name;
}
public static function getNumber()
{
return static::$number;
}
public static function getName()
{
return static::$name;
}
}

View File

@@ -22,48 +22,46 @@ use Symfony\Component\HttpFoundation\Request;
*/
class Helper
{
/**
*
* @var \Alchemy\Phrasea\Core\Kernel
*/
protected $core;
/**
*
* @var \Alchemy\Phrasea\Core\Kernel
*/
protected $core;
/**
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
*
* @param Kernel $kernel
* @return Helper
*/
public function __construct(Core $core, Request $Request)
{
$this->core = $core;
$this->request = $Request;
/**
*
* @param Kernel $kernel
* @return Helper
*/
public function __construct(Core $core, Request $Request)
{
$this->core = $core;
$this->request = $Request;
return $this;
}
return $this;
}
/**
*
* @return \Alchemy\Phrasea\Core
*/
public function getCore()
{
return $this->core;
}
/**
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()
{
return $this->request;
}
/**
*
* @return \Alchemy\Phrasea\Core
*/
public function getCore()
{
return $this->core;
}
/**
*
* @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
{
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)
public function get_search_datas()
{
return $search_datas;
}
$searchSet = $user->getPrefs('search');
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()
$search_datas = array(
'bases' => array(),
'dates' => array(),
'fields' => array()
);
}
$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);
$bases = $fields = $dates = array();
$user = $this->getCore()->getAuthenticatedUser();
if ( ! $user instanceof \User_Adapter) {
return $search_datas;
}
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
);
}
}
$searchSet = $user->getPrefs('search');
if (!$bases[$sbas_id]['thesaurus'])
continue;
if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modif_th'))
continue;
foreach ($user->ACL()->get_granted_sbas() as $databox) {
$sbas_id = $databox->get_sbas_id();
if (simplexml_load_string($databox->get_cterms()))
{
$bases[$sbas_id]['cterms'] = true;
}
$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();
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;
$search_datas['dates'] = $dates;
$search_datas['bases'] = $bases;
return $search_datas;
}
public function getRandom()
{
return md5(time() . mt_rand(100000, 999999));
}
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
{
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
{
/**
*
* @var Array
*/
protected $required_sbas_rights = array('bas_chupub');
/**
*
* @var Array
*/
protected $required_sbas_rights = array('bas_chupub');
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = true;
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = true;
/**
*
* @var boolean
*/
protected $flatten_groupings = true;
/**
*
* @var boolean
*/
protected $flatten_groupings = true;
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Feed
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
if ($this->is_single_grouping())
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Feed
*/
public function __construct(Core $core, Request $Request)
{
$record = array_pop($this->selection->get_elements());
foreach ($record->get_children() as $child)
{
$this->selection->add_element($child);
}
parent::__construct($core, $Request);
if ($this->is_single_grouping()) {
$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
{
/**
*
* @var set_selection
*/
protected $selection;
/**
*
* @var set_selection
*/
protected $selection;
/**
*
* @var boolean
*/
protected $is_possible;
/**
*
* @var boolean
*/
protected $is_possible;
/**
*
* @var Array
*/
protected $elements_received;
/**
*
* @var Array
*/
protected $elements_received;
/**
*
* @var Array
*/
protected $single_grouping;
/**
*
* @var Array
*/
protected $single_grouping;
/**
*
* @var int
*/
protected $sbas_id;
/**
*
* @var int
*/
protected $sbas_id;
/**
*
* @var boolean
*/
protected $has_many_sbas;
/**
*
* @var boolean
*/
protected $has_many_sbas;
/**
*
* @var Array
*/
protected $required_rights = array();
/**
*
* @var Array
*/
protected $required_rights = array();
/**
*
* @var Array
*/
protected $required_sbas_rights = array();
/**
*
* @var Array
*/
protected $required_sbas_rights = array();
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = false;
/**
*
* @var boolean
*/
protected $works_on_unique_sbas = false;
/**
*
* @var <type>
*/
protected $request;
protected $flatten_groupings = false;
/**
*
* @var <type>
*/
protected $request;
protected $flatten_groupings = false;
/**
*
* @var boolean
*/
protected $is_basket = false;
/**
*
* @var boolean
*/
protected $is_basket = false;
/**
*
* @var \Entities\Basket
*/
protected $original_basket;
/**
*
* @var \Entities\Basket
*/
protected $original_basket;
/**
*
* @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')) !== '')
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Helper
*/
public function __construct(Core $core, Request $Request)
{
$em = $this->getCore()->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
parent::__construct($core, $Request);
/* @var $$repository \Repositories\BasketRepository */
$Basket = $repository->findUserBasket($Request->get('ssel'), $this->getCore()->getAuthenticatedUser(), false);
$this->selection = new \set_selection();
$this->selection->load_basket($Basket);
$appbox = \appbox::get_instance($core);
$usr_id = $appbox->get_session()->get_usr_id();
$this->is_basket = true;
$this->original_basket = $Basket;
}
elseif (trim($Request->get('story')) !== '')
{
$em = $this->getCore()->getEntityManager();
$repository = $em->getRepository('\Entities\StoryWZ');
if (trim($Request->get('ssel')) !== '') {
$em = $this->getCore()->getEntityManager();
$repository = $em->getRepository('\Entities\Basket');
$storyWZ = $repository->findByUserAndId(
$this->getCore()->getAuthenticatedUser()
, $Request->get('story')
);
/* @var $$repository \Repositories\BasketRepository */
$Basket = $repository->findUserBasket($Request->get('ssel'), $this->getCore()->getAuthenticatedUser(), false);
$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->selection->load_basket($Basket);
$this->single_grouping = ($this->get_count_actionable() == 1 &&
$this->get_count_actionable_groupings() == 1);
$this->is_basket = true;
$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();
/**
* Tells if the original selection was a basket
*
* @return boolean
*/
public function is_basket()
{
return $this->is_basket;
}
$this->single_grouping = ($this->get_count_actionable() == 1 &&
$this->get_count_actionable_groupings() == 1);
/**
* If the original selection was a basket, returns the basket object
*
* @return \Entities\Basket
*/
public function get_original_basket()
{
return $this->original_basket;
}
$this->examinate_selection();
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;
}
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)
/**
* Tells if the original selection was a basket
*
* @return boolean
*/
public function is_basket()
{
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->is_basket;
}
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
{
/**
*
* @var Array
*/
protected $required_rights = array('candeleterecord');
/**
*
* @var Array
*/
protected $required_rights = array('candeleterecord');
/**
*
* @var Array
*/
protected $available_destinations;
/**
*
* @var Array
*/
protected $available_destinations;
/**
*
*/
protected $works_on_unique_sbas = true;
/**
*
*/
protected $works_on_unique_sbas = true;
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return MoveCollection
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$this->evaluate_destinations();
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return MoveCollection
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$this->evaluate_destinations();
return $this;
}
return $this;
}
/**
* Check which collections can receive the documents
*
* @return action_move
*/
protected function evaluate_destinations()
{
$this->available_destinations = array();
/**
* Check which collections can receive the documents
*
* @return action_move
*/
protected function evaluate_destinations()
{
$this->available_destinations = array();
if ( ! $this->is_possible)
return $this;
if (!$this->is_possible)
return $this;
$this->available_destinations = array_keys(
$this->available_destinations = array_keys(
$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
*
* @return Array
*/
public function available_destination()
{
return $this->available_destinations;
}
/**
* Returns an array of base_id
*
* @return Array
*/
public function available_destination()
{
return $this->available_destinations;
}
public function propose()
{
return $this;
}
public function propose()
{
return $this;
}
/**
*
* @param http_request $request
* @return action_move
*/
public function execute(Request $request)
{
$appbox = \appbox::get_instance($this->core);
$user = $this->getCore()->getAuthenticatedUser();
/**
*
* @param http_request $request
* @return action_move
*/
public function execute(Request $request)
{
$appbox = \appbox::get_instance($this->core);
$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') ?
$request->get('base_id') : false;
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()));
}
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 ( ! $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()));
}
}
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
{
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);
/**
*
* @param \Alchemy\Phrasea\Core $core
* @return Printer
*/
public function __construct(Core $core, Request $Request)
{
parent::__construct($core, $Request);
$grep = function(\record_adapter $record) {
$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;
}
catch (\Exception $e)
{
return false;
}
} catch (\Exception $e) {
return false;
}
};
$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)
{
}
$this->grep_records($grep);
}
return $n;
}
public function get_count_thumbnail()
{
$n = 0;
foreach ($this->get_elements() as $element)
public function get_count_preview()
{
try
{
$element->get_thumbnail()->get_type() == \media_subdef::TYPE_IMAGE;
$n++;
}
catch (\Exception $e)
{
$n = 0;
foreach ($this->get_elements() as $element) {
try {
$element->get_preview()->get_type() == \media_subdef::TYPE_IMAGE;
$n ++;
} 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
{
protected $flatten_groupings = true;
protected $required_rights = array('canpush');
protected $flatten_groupings = true;
protected $required_rights = array('canpush');
}

View File

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

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Helper\Record;
use Alchemy\Phrasea\Core;
use Symfony\Component\HttpFoundation\Request;
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
{
/**
*
* @var array
*/
protected $results;
/**
*
* @var array
*/
protected $results;
/**
*
* @var array
*/
protected $query_parms;
/**
*
* @var int
*/
protected $usr_id;
/**
*
* @var array
*/
protected $query_parms;
public function export()
{
$request = $this->request;
$appbox = \appbox::get_instance($this->core);
$session = $appbox->get_session();
/**
*
* @var int
*/
protected $usr_id;
$offset_start = (int) $request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start;
public function export()
{
$request = $this->request;
$appbox = \appbox::get_instance($this->core);
$session = $appbox->get_session();
$this->query_parms = array(
'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
);
$offset_start = (int) $request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start;
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
$query = new \User_Query($appbox);
$this->query_parms = array(
'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']))
$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']);
$user = \User_Adapter::getInstance($session->get_usr_id(), $appbox);
$query = new \User_Query($appbox);
$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'])
->get_inactives($this->query_parms['inactives'])
->include_templates(false)
->on_bases_where_i_am($user->ACL(), array('canadmin'))
->execute();
return $this->results->get_results();
}
return $this->results->get_results();
}
public function search()
{
$request = $this->request;
$appbox = \appbox::get_instance($this->core);
public function search()
{
$request = $this->request;
$appbox = \appbox::get_instance($this->core);
$offset_start = (int) $this->request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start;
$results_quantity = (int) $this->request->get('per_page');
$results_quantity = ($results_quantity < 10 || $results_quantity > 50) ? 20 : $results_quantity;
$offset_start = (int) $this->request->get('offset_start');
$offset_start = $offset_start < 0 ? 0 : $offset_start;
$results_quantity = (int) $this->request->get('per_page');
$results_quantity = ($results_quantity < 10 || $results_quantity > 50) ? 20 : $results_quantity;
$this->query_parms = array(
'inactives' => $this->request->get('inactives')
, 'like_field' => $this->request->get('like_field')
, 'like_value' => $this->request->get('like_value')
, 'sbas_id' => $this->request->get('sbas_id')
, 'base_id' => $this->request->get('base_id')
, 'srt' => $this->request->get("srt", \User_Query::SORT_CREATIONDATE)
, 'ord' => $this->request->get("ord", \User_Query::ORD_DESC)
, 'per_page' => $results_quantity
, 'offset_start' => $offset_start
);
$this->query_parms = array(
'inactives' => $this->request->get('inactives')
, 'like_field' => $this->request->get('like_field')
, 'like_value' => $this->request->get('like_value')
, 'sbas_id' => $this->request->get('sbas_id')
, 'base_id' => $this->request->get('base_id')
, 'srt' => $this->request->get("srt", \User_Query::SORT_CREATIONDATE)
, 'ord' => $this->request->get("ord", \User_Query::ORD_DESC)
, 'per_page' => $results_quantity
, 'offset_start' => $offset_start
);
$user = $this->getCore()->getAuthenticatedUser();
$query = new \User_Query($appbox);
$user = $this->getCore()->getAuthenticatedUser();
$query = new \User_Query($appbox);
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']);
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"])
$this->results = $query->sort_by($this->query_parms["srt"], $this->query_parms["ord"])
->like($this->query_parms['like_field'], $this->query_parms['like_value'])
->get_inactives($this->query_parms['inactives'])
->include_templates(true)
@@ -115,96 +116,83 @@ class Manage extends \Alchemy\Phrasea\Helper\Helper
->limit($offset_start, $results_quantity)
->execute();
try
{
$invite_id = \User_Adapter::get_usr_id_from_login('invite');
$invite = \User_Adapter::getInstance($invite_id, $appbox);
}
catch (\Exception $e)
{
$invite = \User_Adapter::create($appbox, 'invite', 'invite', '', false);
try {
$invite_id = \User_Adapter::get_usr_id_from_login('invite');
$invite = \User_Adapter::getInstance($invite_id, $appbox);
} 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');
$autoregister = \User_Adapter::getInstance($autoregister_id, $appbox);
}
catch (Exception $e)
{
$autoregister = \User_Adapter::create($appbox, 'autoregister', 'autoregister', '', false);
$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;
}
foreach ($this->query_parms as $k => $v)
public function create_template()
{
if (is_null($v))
$this->query_parms[$k] = false;
$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;
}
$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
{
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();
/**
*
* 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');
/* @var $repo_baskets \Doctrine\Repositories\BasketRepository */
$repo_baskets = $em->getRepository('Entities\Basket');
$sort = in_array($sort, array('date', 'name')) ? $sort : 'name';
$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);
$validations = $repo_baskets->findActiveValidationByUser($current_user, $sort);
/* @var $repo_stories \Doctrine\Repositories\StoryWZRepository */
$repo_stories = $em->getRepository('Entities\StoryWZ');
/* @var $repo_stories \Doctrine\Repositories\StoryWZRepository */
$repo_stories = $em->getRepository('Entities\StoryWZ');
$stories = $repo_stories->findByUser($current_user, $sort);
$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);
$ret->set(self::VALIDATIONS, $validations);
$ret->set(self::STORIES, $stories);
return $ret;
}
protected function sortBaskets(array $baskets)
{
$tmp_baskets = array();
}
return $ret;
}
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
{
/**
* {@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
{
/**
* An array of path to check
* @var type
*/
private $paths = array();
private $classmap = array();
/**
* An array of path to check
* @var type
*/
private $paths = array();
private $classmap = array();
/**
* Construct a new phrasea Autoloader
* 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/';
/**
* Construct a new phrasea Autoloader
* 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');
$getComposerClassMap = function() {
return require realpath(__DIR__ . '/../../../../vendor/.composer/autoload_classmap.php');
};
$this->classmap = $getComposerClassMap();
}
/**
* {@inheritdoc}
*/
public function findFile($class)
{
if (!$file = $this->checkFile($class))
{
$file = parent::findFile($class);
$this->classmap = $getComposerClassMap();
}
return $file;
}
/**
* 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]))
/**
* {@inheritdoc}
*/
public function findFile($class)
{
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;
}
}
}
/**
* Get Paths where classes are checked for autoloading
* @return Array
*/
public function getPaths()
{
return $this->paths;
}
/**
* 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];
}
$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
{
/**
* Array of all cache adapters
* @var type
*/
private $cacheAdapters = array(
'Apc',
'Xcache'
);
/**
* Array of all cache adapters
* @var type
*/
private $cacheAdapters = array(
'Apc',
'Xcache'
);
/**
* The cache adapater
* @var type
*/
private $cacheAdapter;
/**
* The cache adapater
* @var type
*/
private $cacheAdapter;
/**
* The prefix used to store id's in cache
* @var string
*/
private $prefix;
/**
* The prefix used to store id's in cache
* @var string
*/
private $prefix;
/**
* 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)
/**
* 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)
{
$file = sprintf("%s/%sAutoloader.php", __DIR__, $className);
parent::__construct();
if (!file_exists($file))
{
continue;
}
$this->prefix = $prefix;
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))
{
continue;
}
require_once $file;
$method = new $className();
$className = sprintf("\Alchemy\Phrasea\Loader\%sAutoloader", $className);
if($namespace)
{
$method->setNamespace($namespace);
}
if ( ! class_exists($className)) {
continue;
}
if ($method instanceof LoaderStrategy && $method->isAvailable())
{
$this->cacheAdapter = $method;
break;
}
$method = new $className();
if ($namespace) {
$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);
/**
* {@inheritdoc}
*/
public function findFile($class)
{
$file = $this->cacheAdapter->fetch($this->prefix . $class);
if (false === $file) {
$this->cacheAdapter->save($this->prefix . $class, $file = parent::findFile($class));
}
if (false === $file)
{
$this->cacheAdapter->save($this->prefix . $class, $file = parent::findFile($class));
return $file;
}
return $file;
}
/**
* {@inheritdoc}
*/
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;
}
/**
* {@inheritdoc}
*/
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;
}
}

View File

@@ -20,10 +20,9 @@ namespace Alchemy\Phrasea\Loader;
interface LoaderStrategy
{
/**
* Check wether the cacheAdapter is available
* @Return boolean
*/
public function isAvailable();
/**
* Check wether the cacheAdapter is available
* @Return boolean
*/
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 Doctrine\Common\Cache\XcacheCache;
/**
*
* @package
@@ -27,12 +28,11 @@ use Doctrine\Common\Cache\XcacheCache;
Class XcacheAutoloader extends XcacheCache implements CacheStrategy
{
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return extension_loaded('xcache') && PHP_SAPI !== 'cli';
}
/**
* {@inheritdoc}
*/
public function isAvailable()
{
return extension_loaded('xcache') && PHP_SAPI !== 'cli';
}
}

View File

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

View File

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

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef;
class Gif extends Image
{
const OPTION_DELAY = 'delay';
public function __construct()
@@ -35,12 +34,11 @@ class Gif extends Image
public function getMediaAlchemystSpec()
{
if ( ! $this->spec)
{
if ( ! $this->spec) {
$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();
$this->spec->setDelay($this->getOption(self::OPTION_DELAY)->getValue());
@@ -51,5 +49,4 @@ class Gif extends Image
return $this->spec;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -13,7 +13,6 @@ namespace Alchemy\Phrasea\Media\Subdef\OptionType;
class Range implements OptionType
{
protected $min_value;
protected $max_value;
protected $default_value;
@@ -28,16 +27,14 @@ class Range implements OptionType
$this->default_value = $default_value;
$this->step = $step;
if ($default_value)
{
if ($default_value) {
$this->setValue($default_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');
}
@@ -75,5 +72,4 @@ class Range implements OptionType
{
return $this->max_value;
}
}

View File

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

View File

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

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